Domanda

I have two files, one file called Get_url.php, another file called Next.php. However, sessions are not working for me - session values are not remembered. What am I doing wrong?

This is my code for Get_url.php:

<!DOCTYPE html>

<html>
<body>
<?php
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

//connection
$con= mysql_connect("splasjcom.ipagemysql.com","splasj","Password") or die ("Could not connect");
mysql_select_db("splasj") or die ("Could not select db");

$query = "SELECT id FROM articles WHERE url = '". curPageURL() . "'";
$result = mysql_query($query);

while($row = mysql_fetch_array($result)) {
 $idie = $row['id'];

 $Next = $idie +1;
 }
$queryy = "SELECT url FROM articles WHERE id = '$Next'";
$resultt = mysql_query($queryy);

while($roww = mysql_fetch_array($resultt)) {
 $idiee = $roww['url'];

 echo $idiee;
}

session_start();
$_SESSION['Get_url']=$idiee;
?>




</body>
</html>

This is my code for Next.php:

<!DOCTYPE html>

<html>
<body>
<?php include ('Get_url.php');
echo $idiee;
session_start();
echo $_SESSION['Get_url'];
?>
</body>
</html>
È stato utile?

Soluzione 2

There are two issues at play here. First of all you need to start your session before sending any output to the client. For example, your file should begin like so:

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

If you do it the other way around (you send the DOCTYPE and HTML before the session is started) then PHP sends any pending HTTP headers followed by the content. By virtue of the way the HTTP protocol works, once any amount of content is sent, you cannot resend the headers. Thus a late session start (which needs to set a cookie header) will not work.

Your second issue is that you are calling a session_start() in Get_url.php, which is then include()ed in Next.php, which also has a session_start(). When you call that second session_start() it is overwriting the first session with a new session_id.

So in summary:

  1. session_start() before outputting data to the user
  2. only one session_start() at a time. If you must include another file that could potentially have a session_start() you may want to use something like this:

    $sid = session_id();
    if(empty($sid)) session_start();
    

Altri suggerimenti

You first need to set a value to $variable

in Hey.php

<?php
session_start();
$variable = 'test';
$_SESSION['hey']=$variable;
?>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top