开发者

PHP redirect_to not working

I am having an issue with PHP redirect_to. I have a form where a user can select an image to upload. Upon succussful upload I'd like the user to be redirected to a page that lists all images in the database. The following code comes from a PHP file called upload_image.php. It is in the same directory as the page I'd like to redirect to, list_images.php. I've narrowed down the problem area to the following code:

if(isset($_POST['submit'])){
$image = new Image();     //User defined class
$image->caption = $_POST['caption'];     //Pl开发者_C百科aces caption text field in the database
$image->attach_file($_FILES['file_upload']);     //Copies image to images folder

if($image->save()){
    //Success
    $session->message("Image uploaded successfully!");
    redirect_to('list_images.php');    //PROBLEM AREA. Page never redirects.
}else{
    //Failure
    $message = join("<br />", $image->errors);
}}

My function for redirect_to() is the following:

    function redirect_to($location = NULL){
if($location != NULL){
    header("Location: {$location}");
    exit;
}}

The uploaded image is always successfully copied to the correct location and its information gets stored in the database. After submitting however I am always left with a blank page and the url of upload_image.php in the browser. Through countless echo tests I've determined that the problem happens at redirect_to('list_images.php'); I am able to echo text onto the blank page just before redirect_to, but anything after redirect_to does not get executed.

Does anyone have any ideas to advice?

Thank you!


The way to redirect would be:

header("Location: list_images.php");
exit();


header("Location: {$location}");

That's not a valid header I think. Try removing the "{}" braces.


You should make your function really doing the job (and not optional). Additionally if you actually output the suggested HTTP response body, you would actually see if the function was called (or not):

function redirect_to($location)
{
    if (!headers_sent($file, $line))
    {
        header("Location: " . $location);
    } else {
        printf("<script>location.href='%s';</script>", urlencode($location));
        # or deal with the problem
    }
    printf('<a href="%s">Moved</a>', urlencode($location));
    exit;
}


Correct redirect function is defined below:

function redirect_url($path)
{
  header("location:".$path);
  exit;
}

For more information check this :

https://stackoverflow.com/questions/13539752/redirect-function/13539808

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜