问题
Is there any way to pass values and variables between php scripts?
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
回答1:
To pass info via 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.
回答2:
Can't you include
(or include_once
or require
) the other script?
回答3:
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.
For instance:
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"
回答4:
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
回答5:
I would say that you could also store a variable in cache if you really need.
回答6:
You can use:
- temporary file (e.g. tempnam()),
- cache (NoSQL: memcached, redis),
- session variable ($_SESSION), but you need to start the session first.
回答7:
I use extract()
method to pass variable among PHP Scripts. It look like below example:
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;
来源:https://stackoverflow.com/questions/5678567/how-to-pass-variables-between-php-scripts