使用 header() 将数据从一个 PHP 页面传递到另一个页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8227844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass Data from One PHP Page to Another using header()
提问by user1059869
I want to send data from one PHP file to another PHP file in a subfolder where the first PHP file is present. I have a folder named folder1
which has contains a PHP file named file1.php
and I want to call another file named file2.php
in a subfolder of folder1
named folder2
. I am using the header()
function like this in file1.php
:
我想将数据从一个 PHP 文件发送到存在第一个 PHP 文件的子文件夹中的另一个 PHP 文件。我有一个名为的文件夹folder1
,其中包含一个名为的 PHP 文件file1.php
,我想调用file2.php
在named的子文件夹中folder1
命名的另一个文件folder2
。我正在使用这样的header()
功能file1.php
:
$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);
Data is not passing. Is there any solution using header()
? I can't use cURL
because of some restrictions.
数据不通过。有什么解决方案header()
吗?cURL
由于某些限制,我无法使用。
回答by Andrew Kozak
The following code works:
以下代码有效:
file1.php
:
file1.php
:
<?php
header( 'Location: inner/file2.php?x=1&y=2&z=3' );
?>
inner/file2.php
:
inner/file2.php
:
<?php
print '<pre>';
var_dump( $_GET );
print '</pre>';
?>
The result of visiting http://localhost/testing/file1.php
is a redirect to http://localhost/testing/inner/file2.php?x=1&y=2&z=3
which displays:
访问的结果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"
}
I would suggest copying over these test files and proving to yourself that the basic concept of redirecting with passed values is working. Then, build up the rest of your code around a known-good kernel. Good luck!
我建议复制这些测试文件并向自己证明使用传递值重定向的基本概念是有效的。然后,围绕已知良好的内核构建其余代码。祝你好运!
回答by jeroen
Without an example of the variables you want to send, it's kind of hard to tell what the problem might be, but a possible problem could be the characters in the variables.
如果没有您要发送的变量示例,则很难判断可能是什么问题,但可能的问题可能是变量中的字符。
To make sure there are no invalid characters, you can use urlencode()
, perhaps in combination with htmlentities()
, see the manual:
为确保没有无效字符,您可以使用urlencode()
,也许与 结合使用htmlentities()
,请参阅手册:
header("location:http://$host$uri/$extra?sms=".urlencode($msg)."&num=".urlencode($msg_num));