简体   繁体   English

PHP - 将变量从一个页面传递到另一个页面

[英]PHP - Passing variables from one page to another

I am trying to pass on the value of one variable from one PHP page to another PHP page, but for some reason, it's not working.. 我试图将一个变量的值从一个PHP页面传递到另一个PHP页面,但由于某种原因,它不起作用..

Here's my code for phpOne.php: 这是我的phpOne.php代码:

<?php
    $x = 100;
    $_SESSION['sessionVar'] = $x;
    echo "$x";
?>

And here's my code for phpTwo.php: 这是phpTwo.php的代码:

<?php
$x = $_SESSION['sessionVar'];
echo "$x";
?>

Thanks in-advance! 提前致谢! Tom! 汤姆!

You need to call session_start(); 你需要调用session_start(); on both pages. 在两个页面上。

Use this: 用这个:

session_start();

to start up your session. 启动你的会话。 You need to add this on all pages that need to access the $_SESSION[] variables, otherwise it won't work. 您需要在需要访问$ _SESSION []变量的所有页面上添加此项,否则它将无法正常工作。

<?php
  session_start();
  $x = 100;
  $_SESSION['sessionVar'] = $x;
  echo "$x";
?>


<?php
  session_start();
  $x = $_SESSION['sessionVar'];
  echo "$x";
?>

You have to init session_start() to make use of the session variables. 您必须初始化session_start()才能使用会话变量。

Everyone is right. 每个人都是对的。 Session variables are stored in the server with a reference key. 会话变量使用引用密钥存储在服务器中。 The key(known as PHP SESSION ID) is stored in the server as well as the browser cookie. 密钥(称为PHP SESSION ID)存储在服务器以及浏览器cookie中。 Each time the browser sends the key to the server. 每次浏览器将密钥发送到服务器。 If the server gets a session_start() without a key then it initiates a new session. 如果服务器在没有密钥的情况下获得session_start(),则会启动新会话。 Whereas if the browser page has the key then it restores the session. 然而,如果浏览器页面具有密钥,则它将恢复会话。 Which is why it becomes essential that you call the session_start() in both pages. 这就是为什么在两个页面中调用session_start()变得至关重要的原因。 I hope this clears it up!! 我希望这清除它! Good luck 祝好运

Read this for deeper explanation (if you want) : http://www.php.net/manual/en/intro.session.php 阅读本文以获得更深入的解释(如果需要): http//www.php.net/manual/en/intro.session.php

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

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