参数传递-如何在php脚本之间传递变量


parameter passing - How to pass variables between php scripts?

是否有办法在php脚本之间传递值和变量?

正式地,我试图编码一个登录页面,当用户输入错误的输入第一个脚本将检查输入,如果它是错误的,网站返回到最后一个脚本页面,并显示一个警告,如"这是错误的输入"。为了达到这个目的,我想我需要从脚本传递值。

问候……: P

通过信息通过获得:

    header('Location: otherScript.php?var1=val1&var2=val2');
<<p> 会话/strong>:
    // first script
    session_start(); 
    $_SESSION['varName'] = 'varVal';
    header('Location: second_script.php'); // go to other
    // second script
    session_start(); 
    $myVar = $_SESSION['varName'];

文章:看看这个。

您应该查看会话变量。这涉及到在服务器上存储链接到特定引用号("会话id")的数据,然后由浏览器在每次请求时发送(通常作为cookie)。服务器可以看到同一个用户正在访问页面,并设置$_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"

你不能include(或include_oncerequire)其他脚本吗?

快速的方法是使用全局变量或会话变量。

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

如果你真的需要,你也可以在缓存中存储一个变量

您可以使用:

  • 临时文件(如tempnam()),
  • cache (NoSQL: memcached, redis),
  • 会话变量($_SESSION),但需要先启动会话。

我使用extract()方法在PHP脚本之间传递变量。它看起来像下面的例子:

1。 File index.php

<?php
$data = [
    'title'=>'hello',
    'content'=>'hello world'
];
extract($data);
require 'content.php';

2。 File content.php:

<?php 
echo $title;
echo $content;