PHP redirect_to无效

时间:2011-09-20 14:47:05

标签: php

我遇到了PHP redirect_to的问题。我有一个表单,用户可以选择要上传的图像。通过多次上传,我希望将用户重定向到列出数据库中所有图像的页面。以下代码来自名为upload_image.php的PHP文件。它与我要重定向到的页面list_images.php位于同一目录中。我已将问题区域缩小到以下代码:

if(isset($_POST['submit'])){
$image = new Image();     //User defined class
$image->caption = $_POST['caption'];     //Places 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);
}}

我的redirect_to()函数如下:

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

上传的图像始终成功复制到正确的位置,其信息存储在数据库中。提交后,我总是在浏览器中留下一个空白页面和upload_image.php的URL。通过无数的回声测试,我确定问题发生在redirect_to('list_images.php');我可以在redirect_to之前将文本回显到空白页面,但是redirect_to之后的任何内容都不会被执行。

有没有人有任何建议?

谢谢!

4 个答案:

答案 0 :(得分:2)

重定向的方法是:

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

答案 1 :(得分:0)

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

我认为这不是一个有效的标题。尝试删除“{}”大括号。

答案 2 :(得分:0)

你应该让你的功能真正完成工作(而不是可选)。另外,如果您实际输出建议的HTTP响应主体,您实际上会看到是否调用了该函数:

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;
}

答案 3 :(得分:-3)

正确的重定向功能定义如下:

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

有关详细信息,请查看:

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