session_start() creates new session every refresh, no warning
Ok, I figured it out. It is simply that session.cookie_secure = On
and I was not using https. So, just as expected, no session cookie was returned back and a new session was created. Still, I feel that it could help others to see that. I don't get at all why such questions are marked as duplicate, even before people have a chance to answer. It is especially hard to understand given that, clearly, the "duplicated" questions did not have satisfying answers. It is as if some people here have the attitude that, if there are a few ways some thing can go wrong, then don't ask why. There are not so many ways a session can get recreated at each reload. This question can be taken care in a Q&A format, perfectly.
session_start() creates new session every reload
This code seems designed very poorly. Except for the usual "PHP4-style" errors (more on that later), it doesn't really make sense to me.
- If you're using PHP's sessions, why do you need to replicate a session table in your database? Y using session_start() you're already telling PHP to handle all that hassle.
- Why are you accessing users' cookies directly?
I recommend that you stick with a design and follow it.
Do you want to manage sessions yourself, including passing session ids, handling cookies, etc? Then don't PHP's builtin sessions (but be careful: the possibility to write flawed code here is really high).
Do you want to use PHP's builtin sessions? Then just stick with them.
If you want to attach to each users details like "isAdmin", you can use session variables: that's what they're made for :)
<?php
session_start();
if(empty($_SESSION)) {
// Redirect to login
}
else {
if(empty($_SESSION['logged_in'])) {
// Redirect to login
}
else {
// User is logged in
// Is admin?
if(!empty($_SESSION['is_admin'])) {
// YES
}
else {
// NO
}
}
}
?>
There's plenty of guides and tutorials on using sessions with PHP. For example: http://www.phpro.org/tutorials/Introduction-To-PHP-Sessions.html
Additionally, make sure that in php.ini sessions are enabled. I strongly recommend to use "cookie_only" sessions: that is, never make PHP pass the session id as GET or POST parameter. That will screw those users with cookies disabled (are there still some?), but will save all the others from being easy targets for session hijacking.
Thus said... About your "PHP4-style" code:
- Don't use
mysql_*
functions. They're deprecated. Use MySQLi or PDO, and use prepared statements when possible. For example, the linemysql_query("select * from session_noti where sid='$user_cookie'");
is a perfect place for an SQL Injection attack. - Don't use the
@
operator. It's bad! Instead, just check if the variable exists withisset()
orempty()
.
How do I give a new session-id every time I refresh the home page but keep the same session- id between all pages?
Here are two different ways you can do this (Sessions & Cookies):
Sessions
You can use session by setting a session variable at the top of your subpages and then check to see if the session variable exists on your home page. if the session var does exist unset it and if it doesn't, then generate a new random session ID.
try this
home.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<body>
<p>Random session ID (---session-id---). Reload the page to create a new session ID.</p>
<a href="link.php"> First link </a> <br>
<a href="link.php"> Second link </a> <br>
<form action="info.php" method="Post">
<input type="hidden" name="session-id" value="---session-id---">
Name: <input type="text" name="name"> <br> <br>
<input type="submit" name="submit" value="Send">
</form>
</body>
</html>
index.php
<?php
session_start(); //start the session so we can check if there are any session vars set
if(isset($_SESSION['page'])){ //the last page was a subpage
unset($_SESSION['page']); //unset the session var so if the page is refreshed it will give a new session id
}else{ // last page was homepage.
session_destroy(); //destroy the session so we can create a new session with random ID
session_id(rand());
session_start();
}
$html = file_get_contents('home.php');
$html = str_replace('---session-id---', session_id(), $html);
echo $html;
?>
link.php
<?php
session_start();
$_SESSION['page'] = true; //set a session var to show a sub page has been visited
echo "session-id = " . session_id();
?>
Cookies
You can use cookies by updating the cookie value depending on what page you visted and then check the cookie value on the homepage to see if the last page was the home page.
try this:
home.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<body>
<p>Random session ID (---session-id---). Reload the page to create a new session ID.</p>
<a href="link.php"> First link </a> <br>
<a href="link.php"> Second link </a> <br>
<form action="info.php" method="Post">
<input type="hidden" name="session-id" value="---session-id---">
Name: <input type="text" name="name"> <br> <br>
<input type="submit" name="submit" value="Send">
</form>
</body>
</html>
index.php
<?php
//check to see if a cookie has been set and to see if it has the value of home
if(!isset($_COOKIE["page"]) || $_COOKIE["page"] == 'home'){
//last page was the home page or the cookie was not set.
session_id(rand());
}else{ //last page visted was not the home page, update the cookie
setcookie("page", 'home');
}
session_start();
$html = file_get_contents('home.php');
$html = str_replace('---session-id---', session_id(), $html);
echo $html;
?>
link.php
<?php
session_start();
setcookie("page", 'not-home'); //set a cookie to say this is not homepage
echo "session-id = " . session_id();
?>
session start() creates new session file entry in every request
finally, after hours of digging i figured it out. The problem is that on cross origin requests cookie is not sent to the server, so my angular code did not sent it. I changed this
angular 2 code for those who are interested:
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers, withCredentials: true });
let body = { action: 'login_admin', username: 'test', password: 'password' };
return this.http.post('url',
JSON.stringify(body), options)
.map(this.success)
.catch(this.error);
and i added
header('Access-Control-Allow-Credentials: true');
in user.php file and session_start() does not anymore creates new file entries, it is working like expected.
Related Topics
Why Are Escape Characters Being Added to the Value of the Hidden Input
Dealing with Special Characters in Object Property Names
Blank Spaces in Column Names with MySQL
Does PHP Close the File After the File Handler Is Garbage Collected
How to Detect and Handle MySQL Warnings with PHP
PHP Object of Class Dateinterval Could Not Be Converted to String
PHP - Get the Size of a Directory
Permission Denied Despite Appropriate Permissions Using PHP
"Error 404 Not Found" in Magento Admin Login Page
Update Xampp from Maria Db 10.1 to 10.2
How to Properly Display Chinese Characters in PHP
How to Print the Actual Query That MySQLi->Execute() Makes
Quickest Way to Read First Line from File
PHP Date Showing '1970-01-01 ' After Conversion