且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用会话将值从一个php页面传递到另一个

更新时间:2021-11-10 22:25:59

使用类似这样的内容:

page1.php

page1.php

<?php
session_start();
$_SESSION['myValue']=3; // You can set the value however you like.
?>

任何其他PHP页面:

<?php
session_start();
echo $_SESSION['myValue'];
?>

但是要记住一些注意事项:您需要在输出,HTML,回声-甚至空格之前调用session_start().

A few notes to keep in mind though: You need to call session_start() BEFORE any output, HTML, echos - even whitespace.

您可以继续更改会话中的值-但只能在第一页之后使用 -这意味着,如果您在第1页中进行了设置,则将无法使用直到进入另一页面或刷新页面.

You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.

可以通过多种方式之一来设置变量本身:

The setting of the variable itself can be done in one of a number of ways:

$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];

如果要在出现潜在错误之前检查变量是否已设置,请使用以下代码:

And if you want to check if the variable is set before getting a potential error, use something like this:

if(!empty($_SESSION['myValue'])
{
    echo $_SESSION['myValue'];
}
else
{
    echo "Session not set yet.";
}