使用header()将数据从一个PHP页面传递到另一个PHP页面


Pass Data from One PHP Page to Another using header()

我想将数据从一个PHP文件发送到另一个PHP文件中的子文件夹,其中第一个PHP文件存在。我有一个名为folder1的文件夹,其中包含一个名为file1.php的PHP文件,我想在名为folder2folder1子文件夹中调用另一个名为file2.php的文件。我在file1.php中使用header()函数:

$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/''');
$extra = 'folder1/folder2/file2.php';
header("location:http://$host$uri/$extra?sms=".$msg."&num=".$msg_num);

数据未传递。是否有任何解决方案使用header() ?由于一些限制,我不能使用cURL

下面的代码可以工作:

file1.php:

<?php
header( 'Location: inner/file2.php?x=1&y=2&z=3' );
?>

inner/file2.php:

<?php
print '<pre>';
var_dump( $_GET );
print '</pre>';
?>

访问http://localhost/testing/file1.php的结果是重定向到http://localhost/testing/inner/file2.php?x=1&y=2&z=3,显示:

array(3) {
  ["x"]=>
  string(1) "1"
  ["y"]=>
  string(1) "2"
  ["z"]=>
  string(1) "3"
}

我建议复制这些测试文件,并向自己证明使用传递值进行重定向的基本概念是有效的。然后,围绕已知的良好内核构建代码的其余部分。好运!

如果没有要发送的变量的示例,就很难判断问题是什么,但可能的问题是变量中的字符。

为了确保没有无效字符,您可以使用urlencode(),或者与htmlentities()结合使用,参见手册:

header("location:http://$host$uri/$extra?sms=".urlencode($msg)."&num=".urlencode($msg_num));