Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

How to display PHP session variables in HTML page?

How can I display a PHP session variable in an html file? 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:

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? After this, I would like to display the value of the variable $_SESSON[$pagenum] in the title of my html pages.

question from:https://stackoverflow.com/questions/65852385/how-to-display-php-session-variables-in-html-page

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're on the right track, but looking at your code I guess that your variable $pagenum does not exist. The $_SESSION is just like an array, so use an unique string to assign something, e.g. $_SESSION['pageNumber']. Also in this case you cannot miss the else, or the starting value will be 2. So your code would become:

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

In your HTML you can echo it with:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...