Cookies disappear on redirect (PHP) - php

I created a log-in page and i used cookies for the auto-login option.
For some reason, when i'm trying to test it (going to the log-in page - for testing the redirecting)
its not working.
When i'm printing the $_COOKIE i see only the 'PHPSESSID'.
This is my code:
public function index(){
if (isset($_COOKIE[$_SESSION[SESSION_KEY.'id']]) && isset($_COOKIE[$_SESSION[SESSION_KEY.'password']]))
{
$login = $_COOKIE[$_SESSION[SESSION_KEY.'id']];
$password = 1;
}
else if(isset($_POST['login']) && isset($_POST['password']))
{
$password = $_POST['password'];
$login = $_POST['login'];
}
if(isset($login) && isset($password))
{
$query = "SELECT * FROM myDB WHERE id= '{$login}' AND Password = '{$password}'";
$result = $this->db->query($query)->result();
if(count($result) == 0 || count($result) > 1){
$this->load->view('admin/login');
}elseif(count($result) == 1){
$_SESSION[SESSION_KEY.'id'] = $result[0]->id;
$_SESSION[SESSION_KEY.'password'] = 1;
if (isset($_POST['remember']) && isset($_POST['remember']) == 1)
{
setcookie($_SESSION[SESSION_KEY.'id'], $login, time()+60*60*24*10, base_url());
setcookie($_SESSION[SESSION_KEY.'password'], $password, time()+60*60*24*10, base_url());
}
redirect('customers/customers_list');
}
}
else {
$this->load->view('admin/login');
return;
}
}
What could be the problem? where are all the cookies?
And yes, i have session_start();

Try to use the php set_cookie() function the first time the user logs in e.g
setcookie ("username" , $_POST ['username' mktime ()+( 84600 *30 ), "/")
Then get the username cookie if it exists, so you can use the stored value anywere you want e.g
if (isset($_COOKIE ['username' ])) {
//if the cookie exist allow user login e.g
$_SESSION['login']= 'true';
}
else {
//if a cookie doesn't exist
echo "Oops you have to log in!"
//then you display login form
}
Then on the other page you have something like
session_start();
if ($_SESSION['login']='true') {
//Then you display the page
}
else {
//redirect to login page
}

Related

.php file security using MAMP

I have generated a php file that has information stored in a database. To access this a person must use a login in page.
However, when you are using MAMP how can you prevent someone from accessing the file through writing the IP address and php file name e.g. 123.456.78.00:80/fileone.php. I want this fileone.php to be hidden and for them to only access it through a login page.
Thanks in advance.
<?php
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
mysql_connect("localhost", "root","root") or die(mysql_error()); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$query = mysql_query("SELECT * from users WHERE username='$username'"); //Query the users table if there are matching rows equal to $username
$exists = mysql_num_rows($query); //Checks if username exists
$table_users = "";
$table_password = "";
if($exists > 0) //IF there are no returning rows or no existing username
{
while($row = mysql_fetch_assoc($query)) //display all rows from query
{
$table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
$table_password = $row['password']; // the first password row is passed on to $table_users, and so on until the query is finished
$table_id = $row['id'];
$page_id = $row['page'];
}
if(($username == $table_users) && ($password == $table_password)) // checks if there are any matching fields
{
if($password == $table_password)
{
$_SESSION['user'] = $username; //set the username in a session. This serves as a global variable
//echo $table_id;
//echo $page_id;
redirect ($page_id); //take the user to the page specified in the users table
}
else
{
echo "Login Failed";
}
}
else
{
Print '<script>alert("1. Incorrect Password!");</script>'; //Prompts the user
Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
}
else
{
Print '<script>alert("Incorrect Username!");</script>'; //Prompts the user
Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
function redirect($page_id)
{
/* Redirect browser */
header('Location: ' . $page_id);
/* Make sure that code below does not get executed when we redirect. */
exit;
}
?>
Login check
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true) {
"Your script"
}
If you have a profile for your users, like a normal user = 0 and an admin = 1 you can do it like this
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true && $_SESSION['profile'] == 1) {
"Your script"
}
Set sessions
To set set the sessions to true you need this
if(isset($_POST['submit'])) {
$_SESSION['loggedIn'] = true;
// for set a profile
$_SESSION['profile'] = 1;
}
Maybe I didn't understand you good, but to be sure I will explain something:
You said attached checklogin.php, but you can't use that to deny access for non members. If they know that the file exists, they can type it in the URL and still read fileone.php. The first coding block need to be in your fileone.php.
Session time
Search in your php.ini for 'session.gc_maxlifetime'. There will be a number and that is the time in seconds.

PHP Login script with ajax works but session variables do not exist

On my website I only use ajax-calls to save and get data.
I am also using ajax with my login. So this is what I do:
FILE -> ajaxLogin.js
if (check === true) {
$.ajax({
type: 'POST',
url: 'PHPCalls.php?CallID=Login',
data: $("#formLogin").serialize(),
success: function(data) {
var result = $.trim(data);
if(result !== 'false') {
$("#spinner").hide();
window.location.replace(result);
}
else if(result === 'false') {
$("#spinner").hide();
alert('No match');
}
}
});
}
FILE -> PHPCalls.php
if(isset($_GET['CallID']))
{
//LOGIN
if ($_GET['CallID'] == 'Login') {
loginFromForm();
}
}
FILE -> functions.php -> loginFromForm()
function loginFromForm() {
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['riziv']) && isset($_POST['password'])) {
$riziv = htmlentities($_POST['riziv']);
$password = htmlentities($_POST['password']);
if (loginMember($riziv, $password) == true) {
//Login success
if(isset($_SESSION['oldURL'])) {
echo $_SESSION['oldURL'];
} else {
echo 'adminpanel.php';
}
} else {
echo 'false';
}
} else {
// The correct POST variables were not sent to this page.
echo 'false';
}
}
}
FILE -> functions.php -> loginMember($riziv, $password)
function loginMember($riziv, $password) {
// Using prepared statements means that SQL injection is not possible.
$db = MysqliDb::giveNewDbConnection();
$data = array('ID', 'Firstname', 'Admin', 'Salt', 'Password');
$db->where('RIZIV', $riziv);
if ($result = $db->getOne('tblMember')) {
$memberID = $result['ID'];
$firstname = $result['Firstname'];
$admin = $result['Admin'] = 1 ? true : false;
$salt = $result['Salt'];
$db_password = $result['Password'];
// hash the password with the unique salt.
$password = hash('sha512', $password . $salt);
if ($db->count == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkBrute($memberID) == 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
$memberID = preg_replace("/[^0-9]+/", "", $memberID);
$_SESSION['memberid'] = $memberID;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $firstname);
$_SESSION['username'] = $username;
$_SESSION['admin'] = $admin;
$_SESSION['riziv'] = $riziv;
$_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();
$db = MysqliDb::giveNewDbConnection();
$data = array("MemberID" => $memberID, "Time" => $now);
$db->insert('tblLoginAttempts', $data);
return false;
}
}
} else {
// No user exists.
return false;
}
}
}
FILE -> adminpanel.php (I add this snippet with an include on every page)
<?php
sec_session_start();
if(login_check() == false) {
header('location: index.php');
}
//redirects to a specific url
if (($_SERVER['REQUEST_URI'] != 'index.php') && ($_SERVER['REQUEST_URI'] != $_SESSION['oldURL'])) {
$_SESSION['oldURL'] = $_SERVER['REQUEST_URI'];
}
?>
//START THE HTML
FILE -> functions.php -> sec_session_start()
function sec_session_start() {
$session_name = 'sec_session_id';
$secure = false;
$httponly = true;
if (ini_set('session.use_only_cookies', 1) == FALSE) {
header("Location: admin/error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
$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);
}
RESULT OF print_r($_SESSION);
Array
(
[oldURL] => /hijw/admin/adminpanel.php
)
If the login is succesful I get 'adminpanel.php' as result to that is where my page is redirected to. This all works fine but the problem starts at the adminpanel.php:
although I use session_start() my session variables like id, username, login_string, ... have dissapeared.
I have read about an issue with asp.net where u can't pass session variables over ajax. Is that the same with php? Is there a way to solve it?
I have reviewed your code. Everything is perfect . But the problem is when you are assigning the session in "FILE -> functions.php -> loginMember($riziv, $password)". It will not be available to every pages beacuse you are requesting through ajax.
There is two way to resolve it either reload the page after successful login OR return the value from "FILE -> functions.php -> loginMember($riziv, $password)" and reset session in
"FILE -> adminpanel.php"
I hope you will get help from my response.

PHP Session for login - doesn't recognise

I'm writing a login code for my control panel for my website. I've made the login script. But for some reason the session doesn't save, here is the parts of my code I use:
index.php
session_start();
if(isset($_POST['username']) && isset($_POST['password'])) {
require('scripts/validateLogin.php');
}
if($_SESSION['login'] == 1) {
$loginOkay=1;
echo "Logged in";
} else {
$loginOkay=0;
echo "Not logged in";
}
validateLogin.php
require('mysql_connect.php');
$username = htmlspecialchars(strtolower($_POST['username']));
$password = md5(htmlspecialchars($_POST['password']));
$result = mysqli_query($con, "SELECT username,password FROM tb_mods WHERE username = '$username';");
while($row = mysqli_fetch_array($result)) {
if ($row['username'] == $username && $row['password'] == $password) {
$_SESSION['login'] == 1;
}
}
I call session_start(); before I load my loginValidation.php so session_start(); is active in both pages.
I keep getting: Not logged in as result.
I think the line $_SESSION['login'] == 1; is wrong, you need only one equal character to add value to the session variable. I hope it will help.

PHP script inexplicably stopped working without being touched

I have a login script where a page (index.php) can request the user to login (protect.php) however all that I see on index.php is a blank white screen with no source and no error messages. I should at least be seeing login.php to ask the user to log in. This script worked for a few minuets than just decided to stop working
This exact script has worked before in many other web apps that I have created however this one does not work. After hours of debugging I am still unable to find a solution to this problem.
index.php:
<?php
$allow=array('0','1','2');
require("users/protect.php");
?>
<script>window.location="/setup.php";</script>
protect.php:
<?php
session_start();
// --------------------------------THE VARIABLES---------------------------------- //
#include ("config.php");
// ----------------------------------THE CODE ------------------------------------ //
function clearance ($user_value, $pass_value, $level_value, $userlevel_value, $table_value, $column1, $column2, $path) { // Function to see if user can login
$check = mysql_query ("SELECT $userlevel_value FROM $table_value WHERE email='$user_value' AND password='$pass_value'"); // Query to see if user exists
$verify = mysql_num_rows ($check);
$get = mysql_fetch_array ($check);
if (count ($level_value) != 0) { // If the allow array contains userlevels
if (in_array ($get[$userlevel_value], $level_value) && $verify > 0) { // Search allow to see if userlevels match
$_SESSION['username'] = $user_value; // Register sessions
$_SESSION['password'] = sha1 ($pass_value); // sha1 password for extra security
$_SESSION['userlevel'] = $get[$userlevel_value];
}
} else {
if ($verify == 0) { // If attempt fails then redirect to login page
$_SESSION = array();
$error = "Sorry but your login details were incorrect";
#include ("login.php");
exit;
}
if ($verify > 0) { // If attempt is good then register the user
$_SESSION['username'] = $user_value;
$_SESSION['password'] = sha1 ($pass_value);
}
}
}
function protect ($level_value, $password_value, $userlevel_value, $table_value, $column1, $path) { // Function to keep pages secure
if (!isset ($_SESSION['username'])) { // If session doesn't exist then get user to login
if (isset ($_POST['username']) && isset ($_POST['password'])) {
$error = "Sorry but your login details were incorrect";
}
$_SESSION = array();
#include ("login.php");
exit;
} else { // If user is logged in check to see if session is valid and that they have the required userlevel
$check = mysql_query ("SELECT $password_value, $userlevel_value FROM $table_value WHERE $column1='$_SESSION[username]'"); // Query to see if user exists
$verify = mysql_num_rows ($check);
$get = mysql_fetch_array ($check);
if ($verify == 0) {
$_SESSION = array();
$error = "Sorry but your login details were incorrect";
#include ("login.php");
exit;
}
if ($verify > 0 && count ($level_value) != 0) {
if (!in_array ($get[$userlevel_value], $level_value)) { // Check to see if the users userlevel allows them to view the page
$error = "Sorry but your login details were incorrect";
#include ("login.php");
exit; // Ensure no other data is sent
}
}
}
}
if (isset ($_POST['username']) && isset ($_POST['password'])) { // If user submits login information then validate it
clearance ($_POST['username'], $_POST['password'], $allow, $userlevel, $table, $username, $password, $path);
}
protect ($allow, $password, $userlevel, $table, $username, $path);
mysql_close ($link); // Close the database connection for security reasons
// -----------------------------------THE END ------------------------------------ //
?>

Is $_SERVER[HTTP_HOST] the cause of redirect issues?

I have enabled vanity urls (user.domain.com). When a session expires or somebody clears the cookies, the page would get redirected to user.domain.com which has the login page. So, on all pages i am using the following code:
if(!isset($_SESSION['user_name'])) { header("Location: http://$_SERVER[HTTP_HOST]");}
2 of of 10 times i get a redirect error saying that the page is redirecting too many times.
Could this be the reason? And if it is what can i do to redirect in a way that won't cause such issues.
Thanks.
Login code:
<?php
session_start();
// Process the POST variables
$username = $_SESSION["user_name"];
//$password = $_POST["password"];
// Set up the session variables
$_SESSION["user_name"] = $username;
$ugData = $_REQUEST['sub_name'];
if($_POST){
$_SESSION['user_name']=$_POST["user_name"];
$_SESSION['password']=$_POST["password"];
}
$secret = $info['password'];
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site']))
//if there is, it logs you in and directes you to the members page
{
$username = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$check = mysql_query("SELECT user_name, password FROM accounts WHERE user_name = '$username' and sub_name='$ugData'")or die(mysql_error());
while($info = mysql_fetch_array( $check ))
{
if (# $info['password'] != $pass)
{
}
else
{
header("Location: home.php");
}
}
}
//if the login form is submitted
if (isset($_POST['submit'])) { // if form has been submitted
// makes sure they filled it in
if(!$_POST['user_name'] | !$_POST['password']) {
die('You did not fill in a required field.');
}
// checks it against the database
if (!get_magic_quotes_gpc()) {
$_POST['user_name'] = addslashes($_POST['user_name']);
}
$check = mysql_query("SELECT user_name,password FROM accounts
WHERE user_name = '".$_POST['user_name']."'
and sub_name='".$ugData."'")or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
die('That user does not exist in our database.
<a href=add.php>Click Here to Register</a>');
}
while($info = mysql_fetch_array( $check ))
{
$_POST['password'] = md5($_POST['password']);
$_POST['password'] = $_POST['password'];
//gives error if the password is wrong
if (# $_POST['password'] != $info['password']) {
die('Incorrect password, please try again');
}
else
{
// if login is ok then we add a cookie
$_POST['user_name'] = stripslashes($_POST['user_name']);
$hour = time() + 3600;
setcookie(ID_my_site, $_POST['user_name'], $hour);
setcookie(Key_my_site, $_POST['password'], $hour);
//then redirect them to the members area
header("Location: home.php");
}
}
}
else
{
?>
The header("Location: http://{$_SERVER['HTTP_HOST']}"); isn't the problem per-say.
However, if you do have that code on your login page then yes, you'll just keep redirecting yourself to the home page because you won't be able to login.
Make sure that you do not redirect the user if he's on the login page.
EDIT: Try header('Location: /'); Maybe you have some weird server issue which causes $_SERVER['HTTP_HOST'] do sometimes be null.
Assuming that redirecting to http://yourserver/ means http://yourserver/index.php, then you should change the if to read
if(!isset($_SESSION['user_name']) && $_SERVER['PHP_SELF'] != '/index.php')
{
header("Location: http://$_SERVER[HTTP_HOST]");
}
This will avoid endless redirects.
Try using this with a die():
if(!isset($_SESSION['user_name'])) { header("Location: http://user.domain.com"); die();}
If url changes from user to user grab username from db first, and use it in redirection. Try something like:
...
$username = $row["username"];
...
and use it:
if(!isset($_SESSION['user_name'])) { header("Location: http://".$username.".domain.com"); die();}

Categories