EDIT: 4
I went and tried this out with teh regular session handler, same issue could it be some OS error?
session_start();
$_SESSION['h0']=5;
session_regenerate_id(true);
Again when reloading the page multiple times you get A LOT sessions all with the same data.
For some reason when executing this script the
define('endl', "<br>");
$session->start_session();
echo session_id().endl;
session_regenerate_id(true);
echo session_id().endl;
On the top part I'm using delete_old_session
session_regenerate_id(true)
bool session_regenerate_id ([ bool $delete_old_session = false ] )
So the expected behavior is to generate a new session and then delete the old one
if I execute it normally I have the right behavior...
output:
d5ips18ji4rg7q63skuf7955b4
udk903d5o2nbeoq5soujng0bp5
http://s7.postimg.org/67dbyv3x7/image.png
But if I reload the page multiple times, (keep f5 pressed for a couple o seconds...)
it created over 60 sessions
http://s7.postimg.org/442wr744b/image.png
I dont know if Im implementing this correctly...
EDIT 2:
Destroy callback
public function destroy($sessionId) {
$qry = "DELETE FROM sessions WHERE id = :id";
if (!isset($this->dStatement)) {
$this->dStatement = $this->pdo->prepare($qry);
}
$this->dStatement->bindParam(':id', $sessionId, PDO::PARAM_INT);
if ($this->dStatement->execute()) {
return true;
} else {
echo "error destroy()";
return false;
}
}
I've even tryied this methods insted of the regular sess_reg_id(true)
public function regen_id(){
$sessionId = session_id();
echo $sessionId;
$qry = "INSERT INTO sessiondeletequeue VALUES (:id, 0)";
if(!isset($this->regQuery)){
$this->regQuery = $this->pdo->prepare($qry);
}
$this->regQuery->bindParam(':id', $sessionId, PDO::PARAM_STR);
if($this->regQuery->execute()){
session_regenerate_id();
echo "<br>";
$this->forceDelete();
return true;
}
else{
return false;
}
}
private function forceDelete(){
$qry = "SELECT id FROM sessiondeletequeue";
foreach($this->pdo->query($qry) as $row){
$this->destroy($row['id']);
if(!isset($this->forceQuery)){
$this->forceQuery = $this->pdo->prepare("UPDATE sessiondeletequeue SET deleted = 1 WHERE id = :id");
}
$this->forceQuery->bindParam(':id', $row['id'], PDO::PARAM_STR);
$this->forceQuery->execute();
}
$this->pdo->query("DELETE FROM sessiondeletequeue WHERE deleted = 1 ");
EDIT 3:
I know I could find a way around it, but I'm curious to know why the heck is creating that many sessions!! D:
You're probably mixing up PHP's default session mechanism with your framework's or your own session implementation.
$session->start_session(); // where does $session come from?
//and then
session_id();
Yes, it's working the expected way. You're generating a new session ID on every page reload. So the newly generated session ID is being stored on the database.
Regenerate the session ID only when you need. You probably don't need it generated on every request to the page.
Related
I have a external API where I want to GET some data, and I want to keep session id through all the request until I log out. Using cURL lib in codeigniter I have the following flow (myacc and mypass are just placeholders):
public function getCURL() {
echo $this->curl->simple_get('http://37.99.110.537:6001/webapi/auth.cgi?api=SYNO.API.Auth&method=login&version=2&account=myacc&passwd=mypassD&format=sid&session=SurveillanceStation');
}
This will output:
{"data":{"sid":"lH6WJCWMm5rkA14B0MPN570354"},"success":true}
I will have to keep that provided sid (session id) when making the next request:
http://37.99.110.537:6001/webapi/entry.cgi?api=SYNO.SurveillanceStation.Camera&method=GetSnapshot&version=1&cameraId=2×tamp=1480512959&preview=true&_sid="lH6WJCWMm5rkA14B0MPN570354"
See at the end sid="lH6WJCWMm5rkA14B0MPN570354".
And then log out and kill that sid.
After each login I would get a new sid that I have to use it to get a picture (with that URL) and then logout.
I think that saving and using cookies from a file in my case isn't needed, I think something like:
public function getCURL() {
echo $this->curl->simple_get('http://37.99.210.237:6001/webapi/auth.cgi?api=SYNO.API.Auth&method=login&version=2&account=myacc&passwd=mypassD&format=sid&session=SurveillanceStation');
if ($this->form_validation->run()){
$data= array(
'sid'=> $this->input->post('sid'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
if(false == $this->CI->session->userdata('is_logged_in')) {
echo $this->curl->simple_get('http://37.99.110.537:6001/webapi/entry.cgi?api=SYNO.SurveillanceStation.Camera&method=GetSnapshot&version=1&cameraId=2×tamp=1480512959&preview=true&_sid="sid"');
}
}
}
^^ That syntax is messed up, but how I can make it in a proper way or how it's the best way to keep session id on the request chain ?
if you want to keep sid for long session, for multiple request etc, you can save this json to some json file and clear content of file while logging out.
wrap your $sid getter to some other function.
function getSid()
{
//try to read from json
if(is_file('path/to/sid.json'){
$sid = json_decode(file_get_contents('path/to/sid.json', true));
if(!isset($sid['logout'])){
return $sid['data']['sid'];
}
}
$sid = $this->curl->simple_get('http://37.99.110.537:6001/webapi/auth.cgi?api=SYNO.API.Auth&method=login&version=2&account=myacc&passwd=mypassD&format=sid&session=SurveillanceStation');
//check and save `$sid`
if(strlen($sid) > 20) {
file_put_contents('path/to/sid.json', $sid);
return json_decode($sid, true)['data']['sid'];
}
return false;
}
and update content of sid.json while logging out.
function logout()
{
file_put_contents('path/to/file', json_encode(['logout' => 'true']));
}
and call these methods.
for every request in one execution, it will use the same sid, and when you'll hit 'logout()' it will destroy the sid so that new generated and used on next execution.
I have a problem, I searched around a bit but could not find anything that would help me in my particular case.
I come to the point, I created a small function to log log (), inside of course step the variables $ username and $ password, everything works.
The problem is that last night I made a small change, inserting a string of code after the passage of SESSIONS, who was setcookie etc etc because I believed that in doing so the user's connection to last for a long time (I'm no expert).
This morning, the session was timed course, it makes a new login but the data are not passed. (So the User Account box is not refreshed with your username etc.).
I'll post some code:
class User {
private $db;
private $username;
private $password;
/**
* Construct
* #param type $pdo
*/
function __construct($pdo){
$this->db = $pdo;
}
public function login($username, $password){
$this->db->query("SELECT * FROM users WHERE username = :username AND status = :status LIMIT 1");
$this->db->bind(':username', $username);
$this->db->bind(':status', 1);
$row = $this->db->single();
$count = $this->db->rowCount();
if ($count > 0) {
if (password_verify($password, $row['password'])) {
$_SESSION['session'] = [
'id' => $row['id'],
'username' => $row['username'],
'email' => $row['email'],
];
return true;
} else {
return false;
}
}
}
public function isLoggedIn() {
if (isset($_SESSION['session'])) {
return true;
}
}
I do not understand what happened, I hope that I explained to the fullest, I apologize for my bad English.
Also another question, is it safe enough to protect the pages?
Some users told me to register the token, but do not know how to do.
Thank you
Try removing
","
after 'email' => $row['email'],
And yes, If not started your session, use
<?php session_start() ?>
Get PHP Session Variable Values
session variables are not passed individually to each new page,
instead they are retrieved from the session we open at the beginning
of each page (session_start())
Straight from http://www.w3schools.com/php/php_sessions.asp. In your case you have to start your session. You can start your session by using session_start();. But remember to do it once at the beginning of your script.
I ask for help to you, I explain my problem. In my User () class, I wrote a small function to log in, then recording sessions and setting cookies.
Here it is:
public function login($username, $password) {
$this->db->query("SELECT * FROM users WHERE username = :username AND status = :status LIMIT 1");
$this->db->bind(':username', $username);
$this->db->bind(':status', 1);
$row = $this->db->single();
$count = $this->db->rowCount();
if ($count > 0) {
if (password_verify($password, $row['password'])) {
$this->setSession($row);
return true;
} else {
return false;
}
}
}
public function setSession($row) {
$_SESSION['session'] = [
'id' => $row['id'],
'username' => $row['username'],
'email' => $row['email']
];
//set cookie
setcookie("name_cookie", md5($_SESSION['session']['username']/$_SESSION['session']['password']), time()+3600 * 24 * 365);
}
And here is the function to check if the user is connected or not, to protect the pages:
public function isLoggedIn() {
if(isset($_SESSION['session'])) {
return true;
}
return false;
}
My problem would be that even if cookies are set, unfortunately the session after a total time expires.
I set the cookies to a year, but as I said, the user's login session expires after a while. How can I correct this?
PHP sessions expire at the server level. The default is around 20 minutes, and you can control this in your php.ini settings.
You could use setcookie to save a cookie to the user's browser, and then check it using the $_COOKIE variable in PHP. See setcookie.
But be aware of the security risks with this. Anyone can steal the cookie and then get access to the site as that user. Some good ideas for securing your cookie can be found here.
I'm sorry for the small amount of information, but there is not much else I can give you. The problem is, when trying to extend my login function to add an option for staying logged in, the cookies won't set. The session itself works (so there are no blank characters or something). I get no error messages, the cookie just doesn't set (tested with opera/firefox). After being puzzled for over an hour, i decided to ask it here. Below is the login function. Further down you will find how it's called. Don't worry about the password in the cookie, it's hashed. I tested if the code is in fact executed (placed an echo 'abc' before setcookie) which is the case.
public function login($password,$stayloggedin) {
if ( is_null( $this->id ) ) trigger_error ( "user::login(): Attempt to login an user object that does not have its ID property set.", E_USER_ERROR );
if ($this->compare_password($password))
{
if ($stayloggedin)
{
setcookie("userid", $this->id, time()+3600);
setcookie("userid", $this->password, time()+3600);
}
session_start();
$_SESSION['user_id'] = $this->id;
$_SESSION['user_name'] = $this->name;
$_SESSION['user_nummer'] = $this->user_nummer;
return true;
}
else
{
return false; //wrong password
}
}
This is how the above function is called.
<?php
header('Content-type: text/html; charset=UTF-8');
require_once 'required_script.php';
if (isset($_GET['login']))
{
require_once CLASS_PATH.'user.class.php';
$user_logging_in=new user();
$user_logging_in->load_from_name($_POST['user_name']);
if (isset($user_logging_in->id))
{
if ($user_logging_in->login($_POST['user_pass'],$_POST['remember_me']=='true'))
{
echo '1';
}
else
{
echo '0';
}
}
else
{
echo '2';
}
die;
}
Thanks a lot.
Your cookie won't set because you're outputting HTML headers before the log in / cookie setting functionality happens.
You can't pass any headers to the browser prior to creating the cookie.
Here's the code:
final public function login($email) {
$this->email = mysql_real_escape_string($email);
$this->q = "SELECT id FROM users WHERE mail = '$this->email'";
$this->r = mysql_query($this->q);
$this->id = mysql_result($this->r, 0);
$_SESSION['id'] = "$this->id";
header('Location: me.php');
exit;
}
I'm not sure when I redirect the session does not stay. I've echoed it on the current page and it showed. Any solutions? I have a global namespace so the session is set in all files.
Whenever you're dealing with Sessions in PHP, you should use session_start() to load session data into memory.
Call session_start() only once per you page.