且构网

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

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

更新时间:2022-05-09 22:21:40

像这样使用:

page1.php

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

任何其他 PHP 页面:

Any other PHP page:

<?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.";
}