有没有办法在php脚本之间传递值和变量?
我曾试图编写一个登录页面,当用户第一次输入错误时,另一个脚本将检查输入内容,如果有误,则网站将返回上一个脚本页面并显示警告信息“输入不正确”。为了实现这个目的,我想需要在脚本之间传递值。
祝好…:P
有没有办法在php脚本之间传递值和变量?
我曾试图编写一个登录页面,当用户第一次输入错误时,另一个脚本将检查输入内容,如果有误,则网站将返回上一个脚本页面并显示警告信息“输入不正确”。为了实现这个目的,我想需要在脚本之间传递值。
祝好…:P
通过GET传递信息:
header('Location: otherScript.php?var1=val1&var2=val2');
会话:
// first script
session_start();
$_SESSION['varName'] = 'varVal';
header('Location: second_script.php'); // go to other
// second script
session_start();
$myVar = $_SESSION['varName'];
文章:请看这里。
$_SESSION
超全局变量以反映此情况。a.php
session_start(); // must be called before data is sent
$_SESSION['error_msg'] = 'Invalid input';
// redirect to b.php
b.php
<?php
session_start();
echo $_SESSION['error_msg']; // outputs "Invalid input"
快速的方法是使用全局变量或会话变量。
global $variable = 'something';
// script1.php contains function 'add3'
function add3( $value ) {
return $value + 3;
}
// script2.php
include "script1.php";
echo 'Value is '.add3(2); // Value is 5
global $variable; $variable = 'something';
所以声明和赋值不能在同一行。 - Pavel你不能直接include
(或include_once
或require
)另一个脚本吗?
include
另一个脚本时,它的代码会被“粘贴”到包含它的脚本中,因此它会得到与直接在第一个脚本中编写代码相同的东西。 - Albireoinclude
找不到指定的文件,它会发出一个警告,而 require
将抛出一个致命异常。 - Albireo我使用extract()
方法在PHP脚本之间传递变量。它看起来像下面的例子:
1. 文件 index.php
<?php
$data = [
'title'=>'hello',
'content'=>'hello world'
];
extract($data);
require 'content.php';
2. 文件 content.php :
<?php
echo $title;
echo $content;