I use a page with Jquery tabs and when i submit one of the tabs it only submits that tab, zo the other tabs stay the same (and do not submit). I use:
$(document).on("submit","#basis_advertentie,#prijzen_huidige_jaar", function(event) {
$.ajax({
type:"POST",
url:this.getAttribute('id')+".php",
cache: false,
data: data,
success:function(data){
wijziging_nog_bevestigen = 0;
$(innertab).html(data);
}
});
});
Also i check if the user is logged in, with a session.
After a submit i execute the following function to (re) start a session:
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = TRUE; //origineel was SECURE
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
if (ini_set('session.use_only_cookies', 1) === FALSE) {
//header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
email_error("Could not initiate a safe session (ini_set)): ");
exit();
}
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Sets the session name to the one set above.
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id(); // regenerated the session, delete the old one.
}
After that i do the login chech:
function login_check($mysqli) {
// Check if all session variables are set
if (isset($_SESSION['user_id'],
$_SESSION['username'],
$_SESSION['login_string'])) {
$user_id = $_SESSION['user_id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['username'];
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
if ($stmt = $mysqli->prepare("SELECT wachtwoord
FROM data_adverteerders
WHERE adverteerder_ID = ? LIMIT 1")) {
// Bind "$user_id" to parameter.
$stmt->bind_param('i', $user_id);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
if ($stmt->num_rows == 1) {
// If the user exists get variables from result.
$stmt->bind_result($wachtwoord);
$stmt->fetch();
$login_check = hash('sha512', $wachtwoord . $user_browser);
if ($login_check == $login_string) {
// Logged In!!!!
return true;
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
}
Problem is that the following error occurs:
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/huurhulp/domains/huurhulp.nl/public_html/wijzigen/basisgegevens_verhuur.php:5) in /home/huurhulp/domains/huurhulp.nl/public_html/inloggen/login_functions.php on line 23
Warning: session_regenerate_id() [function.session-regenerate-id]: Cannot regenerate session id - headers already sent in /home/huurhulp/domains/huurhulp.nl/public_html/inloggen/login_functions.php on line 24
How do i gett rid of the error, Is i necessery to restart the function or can i use the function that is already starter on the main page (where the tabs are on).
You are almost certainly sending some form of output before you are calling the session_start() and session_regenerate_id() functions. The problem with this is that, for output to be sent, the HTTP headers must be sent first... But sessions are managed by cookies, which must be sent in the headers. What's happening, then, is that you're sending your headers, sending some page content, and then trying to send more headers. That won't work.
Make sure you don't output any page content before starting or changing the session.
More info: How to fix "Headers already sent" error in PHP
Related
This question might be a bit stupid but I am only starting my adventure with sessions - didn't need to use them before. On the homepage I have a session which stores all the variables properly, that's no problem.
When I go to a sub-page under the same domain and try to call the variables from session, I just get empty fields. I tried doing print_r($_REQUEST); on the sub-page and it prints out the following:
Array ( [wp-settings-1] => libraryContent=browse&editor=html [wp-settings-time-1] => 1478015951 [PHPSESSID] => 0744bf21ab3712e4735e07d926433aa3 [sec_session_id] => 60e56049f51c76e9ec4932c6702e7b72 )
Which matches the output on the homepage. I know I should do a session_start(); but when I include that in my code I get the following error:
Notice: A session had already been started - ignoring session_start()
The reason I know that the variables are not being passed is because when I do
if(isset($_SESSION["user_id"])){
$user_id = $_SESSION["user_id"];
}
echo "User id: " .$_SESSION["user_id"];
I only get
User id:
And whenever I try to call the variable I get an error that it is not set.
Is there a step that I am missing?
Setting the session variables:
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $password) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
$sessions['user_id'] = $user_id;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512', $password . $user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
if (!$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')")) {
header("Location: ../error.php?err=Database error: login_attempts");
exit();
}
return false;
}
}
} else {
// No user exists.
return false;
And the function to start secure session:
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = SECURE;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
if (ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
// Sets the session name to the one set above.
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id(); // regenerated the session, delete the old one.
}
By seeing you code i understand it is wordpress site,
if yes follow following steps:
step1: add following code into your wp-content/themes-folder/functions.php
add_action('init', 'myStartSession', 1);
add_action('wp_logout', 'myEndSession');
add_action('wp_login', 'myEndSession');
function myStartSession() {
if(!session_id()) {
session_start();
}
}
function myEndSession() {
session_destroy ();
}
step 2: set user_id
$_SESSION['user_id'] = "your id";
step 3: to access your session id
if(isset($_SESSION['user_id'])) {
$value = $_SESSION['myKey'];
} else {
$value = '';
}
if your site is not a wordpress
add session_start() at header.php(or first line of your code)
then use your session variables.
I wanted to implement the secure login script from WikiHow in my project. I have got it working in CodeIgniter. I want to modify it a bit by logging out a user when he closes the browser (unless he checked Remember Me on the login page).
This is the login function (assume every variable is set because the function won't be called unless they are).
public function login() {
$error_msg = array();
// the email and password validation is here
// if error is found its pushed into the $error_msg array
// find the user corresponding to the given email address
$sql = "SELECT user_id, username, password, salt FROM users WHERE email = ? LIMIT 1";
$query = $this->db->query($sql, $email);
if ($query) {
if ($query->num_rows() == 1) {
$result = $query->row();
// user is found
// hash the pass with the salt
$password = hash('sha512', $password.$result->salt);
// check for number of tries
if ($this->check_brute($result->user_id) == TRUE) {
// account locked for repeated failed login attempts
$error_msg[] = "<p>Account is locked due to repeated failed login attempts.</p>";
// return FALSE;
} else {
// check password
if ($password == $result->password) {
$user_browser = $this->security->xss_clean($_SERVER['HTTP_USER_AGENT']); // browser
$user_id = preg_replace("/[^0-9]+/", "", $result->user_id);
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $result->username);
// i want to set the cookie expiry time depending on the
// remember me checkbox
if ($_POST['remember']) {
}
// i am guessing somekinda cookie manipulation should
// take place here
// assign session variables
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512', $password.$user_browser);
return TRUE; // login success
} else {
// wrong password input
// add activity in database
$sql = "INSERT INTO login_attempts (user_id, time) VALUES (?, ?)";
$this->db->query($sql, array($result->user_id, time()));
$error_msg[] = "<p>ERR PASS: Username/password combination is incorrect.</p>";
// return FALSE;
}
}
} else {
// user doesnt exist
// return FALSE;
$error_msg[] = "<p>NO USR: Username/password combination is incorrect.</p>";
}
}
return $error_msg;
}
And this is the code for the session starting:
public function sec_session_start() {
$session_name = "sec_session_id";
$secure = FALSE; // dev mode
$httponly = TRUE;
if(ini_set('session.use_only_cookies', 1) === FALSE) {
$error_msg = '<p>Could not initiate a secure session.</p>';
return $error_msg;
}
$cookieParams = session_get_cookie_params();
session_set_cookie_params(
$cookieParams['lifetime'],
$cookieParams['path'],
$cookieParams['domain'],
$secure,
$httponly);
session_name($session_name);
session_start();
session_regenerate_id(TRUE);
return TRUE;
}
The only place where there is a reference to cookies is in the logout function where it is unset. What should I do to set the cookie expiry time when a user logs in depending on their choice on "Remember me"?
I had the same problem using this script and this is the solution that I came up with.
In your login function, add this code:
(I am assuming $_POST['remember'] will be = 1 if user wants to be remembered, 0 otherwise)
if ($_POST['remember']) {
$_SESSION['remember'] = $_POST['remember'];
}
Then in the function sec_session_start() add this after session_start():
...
session_name($session_name);
session_start();
if($_SESSION['remember'] == 1){ session_set_cookie_params(60*60*24*60); }
session_regenerate_id(true);
...
The lifetime can obviously be changed to suit you. I chose 2 months for this example.
What this code is effectively doing is setting another session which contains the information as to whether or not the user wants to remembered.
The cookie is then initially set with the default value that your server has set for session lifetimes, but if the remember session has a value of 1, it changes this to the lifetime you have set.
I've not extensively tested this so let me know if any issues arise.
I have an issue where some of my pages take an extended period to load due to communications with various external APIs. I noticed that when I change to a different page or reload the current page before it has finished loading, it seems to drop my session and logs me out.
For example, if loading page about.php and then I click a link to load profile.php before about.php has loaded fully, it logs me out and drops me back at the login screen.
I don't know what to search for this but have not been able to find any information on similar problems. Can anyone shed light on what would be causing this?
Top of each page:
sec_session_start();
if(login_check($dp_conn) == false)
{
header("location:../login.php?error=1");
}
sec_session_start() function:
function sec_session_start()
{
$session_name = 'sec_session_id'; // Set a custom session name
$secure = false; // Set to true if using https.
$httponly = true; // This stops javascript being able to access the session id.
ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies.
$cookieParams = session_get_cookie_params(); // Gets current cookies params.
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
session_name($session_name); // Sets the session name to the one set above.
session_start(); // Start the php session
session_regenerate_id(); // regenerated the session, delete the old one.
}
login_check() function:
function login_check($db)
{
// Check if all session variables are set
if(isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string']))
{
$user_id = $_SESSION['user_id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['username'];
$user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.
$query = "SELECT password FROM users WHERE id = " . $user_id . " LIMIT 1";
$result = mysql_query($query, $db);
if (mysql_num_rows($result) == 1)
{
// If the user exists
$row = mysql_fetch_row($result);
$password = $row[0];
$login_check = hash('sha512', $password.$user_browser);
if($login_check == $login_string)
{
// Logged In!!!!
return true;
}
else
{
// Not logged in
return false;
}
}
else
{
// Not logged in
return false;
}
}
else
{
// Not logged in
return false;
}
}
I will add an answer as this can help others.
So using sec_session_start() will use different SESSION ID on every page request, particularly
session_regenerate_id();
If your site loads a page very slow and user opens a another link on you page while first page is not loaded fully SESSION ID will be lost hence causing a problem.
Just remove session_regenerate_id(); from sec_session_start function.
I followed a tutorial to Create a Secure Login Script in PHP and MySQL
there we made a function that made a secure session and created a cookie with it.
<?php
function sec_session_start() {
$session_name = 'COOKIENAME'; // Set a custom session name
$secure = SECURE;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
if (ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Sets the session name to the one set above.
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id(); // regenerated the session, delete the old one.
}
?>
now i want to add to that cookie the user id that i have in a mysql database
i want to use those id's for later so i can get more data from the user if i need.
or store settings they have selected.
how would i do that?
should i add something into the login function that on login the ID gets added to the session cookie?
function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password, salt
FROM members
WHERE email = ?
LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_id, $username, $db_password, $salt);
$stmt->fetch();
// hash the pasword with the unique salt.
$password = hash('sha512', $password . $salt);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
// Chec k if the password in the database matches
// the password the user submitted.
if ($db_password == $password) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/",
"",
$username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512',
$password . $user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')");
return false;
}
}
} else {
// No user exists.
return false;
}
}
link to tutorial http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
You add session like this $_SESSION['user_id'] = $user_id;
A session is just an array that doesn't go away and you access it via $_SESSION[]
Greetings,
I am working on a login system and getting stuck with Blackberry browsers authenticating. It seems they have an issue with PHP's session_regenerate_id(), can someone suggest an alternative? Here are the auth and login scripts:
UPDATE
It would appear that sessions in general are not working. Took out session_regenerate_id() just to see if it would work and it just redirects me every time, as though the $_SESSION['MD_SESS_ID']were blank. Really stuck here, any ideas would be appreciated. Cookies on the device are enabled, using a Blackberry Bold 9650. It works on my iPod Touch and every browser on my PC.
Login
<?php
session_start();
include $_SERVER['DOCUMENT_ROOT'] . '/includes/pdo_conn.inc.php';
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return $str;
}
$username = clean($_POST['username']);
$password = clean($_POST['password']);
if ($username != "" && $password != "") {
$getUser = $db->prepare("SELECT id, username, password, salt FROM uc_dev WHERE username = ? LIMIT 1");
$getUser->execute(array($username));
$userDetails = $getUser->fetch();
$dbPW = $userDetails['password'];
$dbSalt = $userDetails['salt'];
$hashedPassword = hash('sha512', $dbSalt . $password);
if ($hashedPassword == $dbPW) {
//Login Successful
session_regenerate_id();
$_SESSION['MD_SESS_ID'] = $userDetails['id'];
header('Location: http://somewhere.com');
session_write_close();
} else {
header('Location: http://www.somewhere.com');
exit();
}
} else {
header('Location: http://somewhere.com');
exit();
}
?>
Auth
<?php
//Start the session
session_start();
//Verify that MEMBER ID session is present
if(!isset($_SESSION['MD_SESS_ID']) || (trim($_SESSION['MD_SESS_ID']) == '')) {
$_SESSION = array();
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
header("Location: http://somewhere.com");
exit();
}
?>
A while ago, I was doing some Blackberry development, and found out that the browser couldn't handle multiple cookies with the same name. Not sure if they've fixed this yet.
So if you're sending out the Set-Cookie header more than once (using setcookie, session_start, or session_regenerate_id), using the same name each time, this could be causing your problem.
You might want to keep track of the cookies you need to output, in an object or array, and only send them to the browser at the very end of the request. This way, if you need to change their values in the middle of the request, you can just overwrite the array's value, rather than sending out another cookie header.
This page may also help -- someone linked to it from PHP's session_regenerate_id page.