开发者

Simple PHP Sessions Error

I have actually discovered my problem but I am really want to know why this is an issue. I had two pages form1.php I started a session on that page and hit submit. Then I had a link to session2.php which started that session and was able to pull the information from form1.php. I am just learning about sessions and this was a very simple exercise to learn what a session can do.

Here lies the issue, I had a stylesheet link in my head and it had a blank href well it was href="#" and when that was there the session2.php would not start the session from form1.php and grab the info from the form. Without that href="#" in the style tag it worked fine, and it also worked fine if it was a fake styletag href="something.css" but href="" doesn't work either.

Why is this? I only have those in because its a temp开发者_如何转开发late I made for workflow, maybe I cant include the css link in my template anymore to prevent future issues.

You can see this site working here, if I haven't explained myself.

form1.php

<?php
session_start();
$_SESSION['name'] = $username;
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>

<head>
<title></title>
<!--//CSS STYLESHEETS//-->
<link rel="stylesheet" href="#" type="text/css">
</head>

<body>
<a href="sessions2.php">Go to session 2</a>
<!--form stuff is in here-->
</body

session2.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>

<head>
<title></title>
</head>

<body>
   <?php
 session_start();
  $username = $_SESSION['name'];
  echo $username;


  ?>
  </body>
</html>


Your second page needs to look like this:

<?php
    session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
       <title></title>
    </head>
    <body>
    <?php
        $username = $_SESSION['name'];
        echo $username;
    ?>
    </body>
</html>

Note that session_start() must appear before any content is printed to the screen.

Per the note on the session_start PHP manual page:

Note: To use cookie-based sessions, session_start() must be called before outputing anything to the browser.


To work like you want it, you need to have started the session first. Sounds simple, because it is. When you say session_start, php then looks for an accepted session cookie first to process content.

From http://php.net/manual/en/function.session-start.php

Note: To use cookie-based sessions, session_start() must be called before outputing anything to the browser.


Are you trying to output stuff to the page before you send the headers? What happens if you put the stylesheet after you call session_start()?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜