【问题标题】:PHP script not redirecting via headerPHP脚本不通过标头重定向
【发布时间】:2012-07-30 02:49:27
【问题描述】:

我正在寻找我的代码中导致此 PHP 页面无法重定向的某种错误。我正在寻找是否有人可能知道此问题的原因(可能与 cookie 有关)。

inc_vars.php:

<?php
//some of the variables have been omitted.
$pid = 'gbb';
$dbtable ='';
$dbname = '';
$dbuser = '';
$dbpass = '';

$connect = mysql_connect('localhost', $dbuser, $dbpass);

if(!$connect){
    header('Location: omitted');
    die();
}

mysql_select_db ($dbname, $connect);

$webroot = 'omitted';

$share_page = $webroot . '/share-the-training';

$gift = $webroot . '/free-video?setuser=1199';

$bonus_content = $webroot . '/awesome-bonus';

$share_php = $webroot . '/share.php';

?>

刷新_id.php:

<?php

include_once('inc_vars.php');

$results = mysql_query("SELECT id FROM " . $dbtable . " WHERE email='" . $_GET['email'] . "'");


if(!$results || mysql_num_rows($results)==0){
    header('Location: ' . $share_page . '?errorcode=1');
    die();
}

$res_arr = mysql_fetch_assoc ($results);

setcookie($pid . "_viral", (string)$res_arr['id'], time() + 3600 * 365);

move_on();

function move_on(){
    header ('Location: ' . $share_php);
    die();
}

?>

当此人访问 refresh_id.php?email=their_email 时,他们应该重定向到 $share_php 页面。这不起作用。

但是,如果发生这种情况:refresh_id.php?email=an-email-that-is-not-in-database 然后脚本重定向到 $share_page 绝对没问题。

我已经尝试过使用和不使用 gbb_viral cookie。我不确定为什么这不起作用。如果您想自己寻找,所有页面现在都在互联网上。

省略

数据库中存在的一封电子邮件如下:acctrafficcop@gmail.com(对于那些想要测试的人)

更新

范围的愚蠢错误。我只是在 move_on() 函数中添加了全局 $share_php,现在一切正常。感谢大家对 SQL 注入的关注,我现在正在切换到准备好的语句。

【问题讨论】:

  • 提防 SQL 注入攻击 - 您将 GET 变量直接转储到查询中。使用准备好的语句。

标签: php mysql cookies


【解决方案1】:

在您的move_on 函数中,变量$share_php 不存在,因为variable scope。因此,您的重定向看起来像这样:Location:。 Location 标头中没有 URL。

您可以将变量传递给函数,或使用global 关键字使其可用。试试这个:

move_on('/redirect_url');

function move_on($url){
    header ('Location: ' . $url);
    die();
}

事实上,在refresh_id.php 中,我在任何地方都没有看到名为$share_php 的变量,因此您正在重定向到一个空的URL。

【讨论】:

  • $share_php 在 inc_vars.php 中定义,但在函数中使用 $share_php 不等效
【解决方案2】:

您还需要为浏览器设置状态标头以尊重位置标头。尝试添加

header('HTTP/1.1 303 See Other');

使用 curl 将帮助您进行调试。此外,您正在为自己的 SQL 查询设置 SQL 注入。

编辑:阅读第二个答案后,您没有将位置传递给重定向功能是正确的。这也应该修复。

$results = mysql_query("SELECT id FROM " . $dbtable . " WHERE email='" . $_GET['email'] . "'");

永远不要相信这样的用户输入。而是使用 SQL 绑定。以下是使用 mysqli 库的方法:http://php.net/manual/en/mysqli-stmt.bind-param.php

【讨论】: