简体   繁体   English

如何在PHP脚本之间传递变量?

[英]How to pass variables between php scripts?

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

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 . 发布 :看看这个

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

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). 这涉及将数据存储在链接到特定参考号(“会话ID”)的服务器上,然后由浏览器在每个请求(通常作为cookie)发送。 The server can see that the same user is accessing the page, and it sets the $_SESSION superglobal to reflect this. 服务器可以看到同一个用户正在访问该页面,并设置$_SESSION超全局以反映这一点。

For instance: 例如:

a.php a.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"

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

You can use: 您可以使用:

I use extract() method to pass variable among PHP Scripts . 我使用extract()方法在PHP Scripts中传递变量。 It look like below example: 它看起来像下面的例子:

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;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM