简体   繁体   English

如何在 HTML 页面中显示 PHP session 变量?

[英]How to display PHP session variables in HTML page?

How can I display a PHP session variable in an html file?如何在 html 文件中显示 PHP session 变量? I am redirecting users to random html pages without repetition, and for each page they see I would like the page number to increase by 1. I've started a session on the PHP file that succeeds the first HTML page and I have this PHP session variable: I am redirecting users to random html pages without repetition, and for each page they see I would like the page number to increase by 1. I've started a session on the PHP file that succeeds the first HTML page and I have this PHP session多变的:

if(!isset($_SESSION[$pagenum]))
{
    //New user
    $_SESSION[$pagenum] = 1;   
}

$_SESSION[$pagenum]++; 

Is this the correct way to store a session variable that increases by 1?这是存储增加 1 的 session 变量的正确方法吗? After this, I would like to display the value of the variable $_SESSON[$pagenum] in the title of my html pages.在此之后,我想在我的 html 页面的标题中显示变量$_SELSON[$pagenum]的值。

Not sure what you want to achieve, but simply like this?不确定您想要实现什么,但只是这样?

<?php
if(!isset($_SESSION[$pagenum]))
{
    //New user
    $_SESSION[$pagenum] = 1;   
}

$_SESSION[$pagenum]++; 

?>

<h1><?php echo $_SESSION[$pagenum] ?></h1>

same in the title:标题相同:

<title><?php echo $title; ?></title>

You're on the right track, but looking at your code I guess that your variable $pagenum does not exist.您走在正确的轨道上,但是查看您的代码,我猜您的变量$pagenum不存在。 The $_SESSION is just like an array, so use an unique string to assign something, eg $_SESSION['pageNumber'] . $_SESSION 就像一个数组,所以使用一个唯一的字符串来分配一些东西,例如$_SESSION['pageNumber'] Also in this case you cannot miss the else, or the starting value will be 2. So your code would become:同样在这种情况下,您不能错过 else,否则起始值为 2。因此您的代码将变为:

if(!isset($_SESSION['pageNumber'])) {
  $_SESSION['pageNumber'] = 1;
} else {
  $_SESSION['pageNumber']++;
}

In your HTML you can echo it with:在您的 HTML 中,您可以使用:

<h1>Hello world!</h1>
<p>You are visiting page <?php echo $_SESSION['pageNumber']; ?></p>

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

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