php 如何在php脚本之间传递变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5678567/
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
How to pass variables between php scripts?
提问by erogol
Is there any way to pass values and variables between php scripts?
有没有办法在php脚本之间传递值和变量?
Formally, I tried to code a login page and when user enter wrong input first another script will check the input and if it is wrong, site returns to the last script page and show a warning like "It is wrong input". For this aim, I need to pass values from scripts I guess.
正式地,我尝试对登录页面进行编码,当用户首先输入错误的输入时,另一个脚本将检查输入,如果输入错误,站点将返回到最后一个脚本页面并显示“输入错误”之类的警告。为此,我想我需要从脚本中传递值。
Regards... :P
问候... :P
回答by Tanner Ottinger
To pass info via GET:
通过 GET 传递信息:
header('Location: otherScript.php?var1=val1&var2=val2');
Session:
会议:
// first script
session_start();
$_SESSION['varName'] = 'varVal';
header('Location: second_script.php'); // go to other
// second script
session_start();
$myVar = $_SESSION['varName'];
Post: Take a look at this.
帖子:看看这个。
回答by Albireo
Can't you include
(or include_once
or require
) the other script?
你不能include
(或include_once
或require
)其他脚本吗?
回答by lonesomeday
You should look into session variables. This involves storing data on the server linked to a particular reference number (the "session id") which is then sent by the browser on each request (generally as a cookie). The server can see that the same user is accessing the page, and it sets the $_SESSION
superglobal to reflect this.
您应该查看会话变量。这涉及在服务器上存储链接到特定参考号(“会话 ID”)的数据,然后浏览器根据每个请求(通常作为 cookie)发送该数据。服务器可以看到同一用户正在访问该页面,并设置$_SESSION
superglobal 以反映这一点。
For instance:
例如:
a.php
一个.php
session_start(); // must be called before data is sent
$_SESSION['error_msg'] = 'Invalid input';
// redirect to b.php
b.php
b.php
<?php
session_start();
echo $_SESSION['error_msg']; // outputs "Invalid input"
回答by Dan Blows
The quick way would be to use either global or session variables.
快速的方法是使用全局变量或会话变量。
global $variable = 'something';
The 'better' way of doing it would be to include the script and pass the variable by parameter like
这样做的“更好”方法是包含脚本并通过参数传递变量,例如
// script1.php contains function 'add3'
function add3( $value ) {
return $value + 3;
}
// script2.php
include "script1.php";
echo 'Value is '.add3(2); // Value is 5
回答by dotslashlu
I would say that you could also store a variable in cache if you really need.
我会说如果你真的需要,你也可以在缓存中存储一个变量。
回答by kenorb
回答by Tran Van Hoang
I use extract()
method to pass variable among PHP Scripts. It look like below example:
我使用extract()
方法在PHP 脚本之间传递变量。它看起来像下面的例子:
1.File index.php
1.文件index.php
<?php
$data = [
'title'=>'hello',
'content'=>'hello world'
];
extract($data);
require 'content.php';
2.File content.php:
2.文件content.php:
<?php
echo $title;
echo $content;