Cookies aren't working - php

I tried to do use cookies to remember login information but the cookies never seemed to "take" as it were. Here's the initial login script:
//try to login using cookies, but first make sure it doesn't have a $_SESSION variable for it
if (!(isset($_SESSION['valid_user']))) {
if (isset($_COOKIE["login"])) {
//try to login using cookie
$query = "select from cookie_users where uniqueid = '".$_COOKIE["login"]."')";
$conn = new mysqli('localhost', 'user', 'password', 'test');
$result = $conn->query($query);
if ($result->num_rows>0) {
$result->fetch_assoc();
$result['username'] = $username;
$result['password'] = $password;
//try to login using password and username from cookie database
$query = "select * from authorized_users where username = '".$username."' and password = '".$password."'";
$result2 = $conn->query($query);
if ($result->num_rows>0) {
$_SESSION['valid_user'] = $username;
}
}
}
}
if (isset($_POST['userid']) && isset($_POST['password'])) {
// if the user has just tried to log in
$userid = $_POST['userid'];
$password = $_POST['password'];
$db_conn=new mysqli('localhost', 'user', 'password', 'test');
if (mysqli_connect_errno()) {
echo 'Connection to database failed: '.mysqli_connect_errno();
exit;
}
$query = 'select * from authorized_users '."where name='$userid' "."and password=sha1('$password')";
$result = $db_conn->query($query);
if ($result->num_rows > 0) {
//if they are in the database, register the user id
$_SESSION['valid_user'] = $userid;
//set up cookie
setcookie("login", $uniqueid, time()*60*60*24*14);
$query = "insert into cookie_users values ('".$userid."', sha1('".$password."'), '".$uniqueid."')";
$result = $db_conn->query($query);
if (!$result) {
echo 'Could not update cookie in database';
}
}
$db_conn->close();
}
Members only content:
if (isset($_SESSION['valid_user'] {
echo "members only content goes here";
} else {
echo "you need to login"; }
The sessions and login scripts work just fine. If they login directly using the login page, it shows up. If they go to another page and then come back, it still works; so that leaves me to believe that the sessions work just fine. However, if you close down the browser and come back, it doesn't register. If something's messed up with the script, please let me know. Either way, I did a test script and not even that works. Here it is:
<?php
setcookie("test", "the test is good", time()*60*60);
?>
<html>
<body>
<?php
echo $_COOKIE["test"];
?>
</body>
</html>
So I think I'm missing something fundamental. Sorry if the answer is painfully obvious, cookies are new to me. Thanks for any help you guys can give.

Your problem is in this line:
setcookie("login", $uniqueid, time()*60*60*24*14);
Here, you're multiplying the time instead of adding to it. You've multiplied it by enough to exceed the MAX_INT size (see Y2038). For whatever reason, Apache (at least, on my system) will ignore that header and the browser will then keep it only for the length of the session. Fortunately, you can fix the problem fairly simply:
setcookie("login", $uniqueid, time() + 60*60*24*14); // Adding two weeks, not multipying by >9000

Related

PHP - properly setting session for login page

On my website i log users in perfectly but i noticed that when a user is logged out, they can simply hit backspace and be re-logged in or even just put the file name in the URL. I found a lot questions on this matter but some are very vague with little steps and others are very outdated. I basically want to give the user a token for the session, that i have generated and set to the database already, and that token will be seen in the URL as GET request for security but i do not know how to go about this. Here is my code for the login page and upload page
PHP Login Page
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] =="POST"){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if(!empty($username) && !empty($password)){
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
$stmt = $handler->prepare("SELECT * FROM generalusersdata WHERE username = :username");
$stmt->execute(array(':username'=>$username));
if($result = $stmt->fetch()){
if(password_verify($password, $result['password'])){
$token = md5(uniqid(mt_rand(), true));
$stmtToken = $handler->prepare("SELECT * FROM token_table WHERE token = :token");
$stmtToken->execute(array(':token'=>$token));
if($rowToken = $stmtToken->fetch()){
die("Error, Please try again");
}
$userid = $result['user_id'];
$email = $result['email'];
$time = time();
$stmtSendToken = $handler->prepare("INSERT INTO token_table set timestamp=?, user_id=?, token=?");
$stmtSendToken->execute(array($time, $userid, $token));
$stmtUpdate = $handler->prepare("UPDATE generalusersdata SET isDev = true WHERE user_id =?");
$stmtUpdate->execute(array($userid));
$_SESSION['id'] = $userid;
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['timestamp'] = $time;
header("Location: developerUpload.php");
}
}else{
die("Username OR Password is incorrect! Please try again");
}
}else{
die("Values Missing!");
}
}
?>
PHP upload page after logging in
<?php
session_start();
if(array_key_exists("id", $_COOKIE)){
//set the session id equal to the cookie
$_SESSION['id']= $_COOKIE['id'];
}
if(array_key_exists("id", $_SESSION)){
$username = $_SESSION['username'];
echo "Welcome To the Developer Side ".$username."!";
echo "<br><br><button><a href='developerLogin.php?logout=1'>Log Out</a></button></br></br>";
if(isset($_FILES['file']) && $_FILES['file']['size'] > 0){
$target = "devFiles/";
$target_file = addslashes(trim($target . basename($_FILES["file"]["name"])));
// Check file size not > 500Mb
if($_FILES["file"]["size"] > 500000000){
echo "Files Cannot be bigger than 500MB";
exit;
}
if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)){
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
$dev_file = addslashes(trim($_FILES['file']['tmp_name']));
$file_name = addslashes(trim($_FILES['file']['name']));
$username = $_SESSION['username'];
$email = $_SESSION['email'];
$userid = $_SESSION['id'];
$time = $_SESSION['timestamp'];
$stmt = $handler->prepare("INSERT INTO developerfiles set user_id=?, username=?, email=?, dev_file=?, file_name=?, timestamp=?");
if(!$stmt->execute(array($userid, $username, $email, $dev_file, $file_name, $time))){
die("Error");
}else{
echo "Thank you for Submiting!";
}
}
}
}else {
header("Location: developerLogin.php");
}
?>
In your upload file you did not check the session again.
So every one could login into your upload file, only create an $_SESSSION['id']='1' and a $_COOKIE['id']='1' and your logged in (also if the id did not exists).
And one tipp: Set an Hash (md5, uniqueid,...) or somthing like that in your _SESSION (from your database, insted of an id) or every one could login as every user, only changing the _SESSION id.
The other thing is, you did not set an _COOKIE in your hole script, but in your upload file you check if the _COOKIE is set, or remove the _COOKIE check in your upload file
So add an setcookie() to your login page too, to work with your current file.
And add a second SQL request to your upload file, like:
$id=$_SESSION['id'];
if(!is_numeric($id) or $id<1) $id = 0; // a little bit of "security".
"SELECT * WHERE `id`='$id'";
if($sql_request => true){
// write the script
} else {
// you are not logged in
}
To destroy the _SESSION (logout) set the _SESSION like this $_SESSION['id']='empty'; unset($_SESSION['id']); so no one could use the back button to login back.
So there is no need to do it unsave with an token in your URL.

PHP Session 5.4 to 5.6

I have created a website lately with a group of students, but were having some troubles.
We created the website in php 5.4 on a localhost and it worked perfectly.
But now we wanted to get the site online and the webhosting is using a different version of php(5.6).
So now the session does not start.
It redirects us to the homepage, but we are not logged in.
We were thinking that it was because of the version of php, since it did work at first.
<?php
include_once 'connect.php';
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['gebruiker'];
// SQL Query To Fetch Complete Information Of User
$ses_sql="select email_adres from gebruiker where email_adres='".$user_check".'";
$row = mysqli_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
header('Location: login.php'); // Redirecting To Home Page
}
else{
header('Location: acountgegevens.php');
}
?>
<?php
include_once 'connect.php';
function logincheck(){
if(isset($_POST['submit'])){
$error = 0;
// declare variables
$email = null;
$password = null;
// check if email address has been set
if (isset($_POST['email_adres']) &&
!empty($_POST['email_adres'])) {
$email = addslashes($_POST['email_adres']);
}
// check if password has been set
if (isset($_POST['password']) && !empty($_POST['password'])) {
$password = md5($_POST['password']);
}
if ($email == null || $password == null) {
$error = 1;
}
// query database for user credentials
$db = new PDO('**');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $db->prepare("SELECT *
FROM gebruiker
WHERE email_adres = :email
AND wachtwoord = :password
LIMIT 1");
$statement->execute(array(':email' => $email, ':password' => $password));
$result = $statement->fetch(PDO::FETCH_OBJ);
if (!$result) {
$error = 1;
} else {
session_start();
$_SESSION['gebruiker'] = $email;
var_dump($_SESSION);
?>
<script>location.href='index.php'</script>
<?php
}
return $error;
}
}
?>
These two files are included, but we cant figure it out.
Could someone help?
I would hazzard a guess that your connect.php has not been changed to match the hosting companies host/user/password and therefore is outputting an error message.
This of course means that session_start() , which was placed after the connect.php and therefore after your script has attempted to send something to the browser, will not work.
You are only seeing the result of the failed session_start() but I would check the connect.php is configured correctly for its new hosting location

PHP MySQLi authentication using if_num_rows not matching database information

I am new to PHP / MySql programming. I have purchased a book to help learn the language and I have done well so far except when I tried to create an authentication system.
I want to be able to match the record to the database using MD5 encryption and if found send to the website. If the username and password are incorrect then send them to the login page again.
At one point it would only match the first record. Now it won't match any. I can type exactly what is in the database and the result still goes to 0 or back to the login page.
Also I am wanting to set a session variable for the username and auth_level so that I can call on it throughout my website/application.
I am using XAMPP on Mac if that helps.
Auth Script:
if ((!isset($_POST['username'])) || (!isset($_POST['password']))) {
header('Location: login.html');
exit;
}
$mysqli = mysqli_connect('localhost', 'username', 'password', 'testDB')
or die(mysql_error($mysqli));
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$password = mysqli_real_escape_string($mysqli, $_POST['password']);
$auth_sql ="SELECT username , auth_level FROM auth_users WHERE
username ='".$username."' AND password =MD5('".$password."')";
$auth_sql_res = mysqli_query($mysqli, $auth_sql) or die(mysqli_error($mysqli));
if (mysqli_num_rows($auth_sql_res) == 1) {
$_SESSION['username'] = $username;
header('Location: homebeta.php');
} else {
header("Location:index.php");
exit;
}
PHP v5.3.1
Thank you everyone that takes the time to look, analyze, and/or help. I really appreciate your time.
You forgot an exit after the first call to header:
header('Location: homebeta.php');
exit;
Are you checking PHP errors? Read How to get useful error messages in PHP? to know more.
I think your script may output something at the beginning, that prevents headers or session information to be sent.
Try this:
if ((!isset($_POST['username'])) || (!isset($_POST['password']))) {
header('Location: http://www.replacethis.com/login.html');
} else {
$mysqli = mysqli_connect('localhost', 'username', 'password', 'testDB')
or die(mysql_error($mysqli));
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$password = mysqli_real_escape_string($mysqli, $_POST['password']);
$auth_sql = "SELECT `username`, `auth_level`
FROM `auth_users`
WHERE `username` = '$username' AND `password` = MD5('$password')";
$auth_sql_res = mysqli_query($mysqli, $auth_sql)
or die(mysqli_error($mysqli));
if (mysqli_num_rows($auth_sql_res) > 0) {
$_SESSION['username'] = $username;
header('Location: http://www.replacethis.com/homebeta.php');
} else {
header("Location: http://www.replacethis.com/index.php");
exit;
}
}
Else statement added.
Backticks in your SQL query (Just to be on the safe side)
Absolute URL in the header location.
And try removing the MD5 hashing from your query and copy n paste both username AND password in your HTML-form and then login.
Well, you may not getting your error messages, since you are using mysql_error instead of mysqli like everything else, and specifically on connect, there is mysqli_connect_error().
Also, according to the manual, inside the parentheses should be void for mysqli_connect_error:
$mysqli = mysqli_connect('localhost', 'username', 'password', 'testDB')
or die(mysqli_connect_error());

Password protect a page?(with db access)

Couple questions here: My end goal is to password protect the file logged_in.php.
Note: I'm only a beginner/intermediate programmer so i would like clear explanations, please.
First off, i have set a username and password within a database table.
I have two pages: login.php and logged_in.php(names are just for example purposes). How do i "require" a user to first go through login.php(the log in process) in order to gain access to logged_in.php(if the entered username/password are correct)?
Is this the best way to password protect a page?
What i've tried:
Login.php:
<?php
$db_host="host";
$db_user="user";
$db_pass="pass";
$db_name="name";
$db_table="table";
$user = mysql_real_escape_string(strip_tags($_POST['user']));
$pass = mysql_real_escape_string(strip_tags($_POST['pass']));
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
if(isset($user) && isset($pass))
{
$sql = "SELECT * FROM $db_table WHERE username='$user' AND password='$pass'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1)
{
header("location:logged_in.php");
}
else
header("location:bad_login.html");
}
?>
The problem with my code at the moment is that, someone can directly type in the URL of logged_in.php and access the page without being "required" to go through login.php first(i'm sure this is obvious to everyone..).
I put require(login.php); at the top of logged_in.php; however, that didn't work out.
I've checked google for some good tutorials on this topic, unfortunately i couldn't find any that had clear explanations.
I also saw a few other questions regarding this topic on stackoverflow, but they didn't really help me out.
I'm also interested in being able to pass-protect my page using the method phpMyAdmin uses(when you type in the URL and press enter it drops down a menu from the top of the browser asking for a username/password). I don't know how that works. If someone can tell me how that works i'm willing to completely disregard the method i'm attempting to use at the moment(if the phpMyAdmin method is secure enough and is fairly easy to implement).
Thanks in advance!
Use $_SESSION variable:
<?php
session_start();
$db_host="host";
$db_user="user";
$db_pass="pass";
$db_name="name";
$db_table="table";
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
$user = mysql_real_escape_string(strip_tags($_POST['user']));
$pass = mysql_real_escape_string(strip_tags($_POST['pass']));
if(isset($user) && isset($pass))
{
$sql = "SELECT * FROM $db_table WHERE username='$user' AND password='$pass'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1)
{
$_SESSION['username'] = $user;
header("location:logged_in.php");
exit();
}
else
header("location:bad_login.html");
exit();
}
?>
logged_in.php:
<?php
session_start();
// check if $_SESSION was setting before
if (!isset($_SESSION['username']))
{
header("Location: login.php?e=access_denied");
exit();
}
?>
The phpMyAdmin login is different because use the MySQL username and password to login, so phpMyAdmin does not need to create a database and table to login like your code
Also you need the logout:
logout.php
<?php
session_start(); // <-- Oops!!
// unset all $_SESSION variables
session_unset();
session_destroy();
header("Location: logged_in.php?m=logout_success");
exit;
?>

User login using PHP

I haven't been able to trace what's wrong with this code. I am trying to login the user by taking his username and password. Here is what I am trying to do.
index.php:
This file checks if the username cookie is set and displays the file accordingly. This file submits the username and password to a file called validate.php.
validate.php:
<?php
session_start();
include("connector.php");
$var=connect();
if($var==10)
{
$valid=false;
$row= mysql_query('select * from users where username="'.$_POST["username"].'"');
if($row['password']==$_POST["password"])
$valid=true;
if($valid)
{
$_SESSION["username"]=$_POST["username"];
$_SESSION["userid"]=$row['userid'];
echo "<script>document.location.href='./session_creator.php'</script>";
}
else
{
echo "invalid";
}
}
?>
connector.php==>
<?php
$connection=0;
function connect()
{
$dbc = mysql_connect('localhost:3306','root','root');
if (!$dbc)
{
die ('Not connected:'. mysql_error());
return -10;
}
else
{
$connection = mysql_select_db("citizennet",$dbc);
if(!$connection)
{
die("Not connected: ". mysql_error());
return -20;
}
}
return 10;
}
?>
session_creator.php:
<?php
session_start();
setcookie("username",$_SESSION['username'],time()+3600);
setcookie("userid",$_SESSION['userid'],time()+3600);
echo "<script>document.location.href='./index.php'</script>";
?>
the redirected index.php file reports that the cookie is not set. I am newbie, please correct me if the process I am following is wrong.
I am adding index.php that verifies if the user is logged in:
<?php
if(!isset($_COOKIE["username"]))
echo '<a id="login_button">login</a> <div id="login_box_pane"><form action=validate.php method="post">Username: <input type="text"/> Password:<input type="password"/><input type="submit"/></form></div>';
else
echo "<a>".$_COOKIE["username"]."</a>";
?>
When you set your cookie on your page it should be like this:
<?php //login page
session_start()
$username = $_POST['username'];
$password = $_POST['password'];
/*
Check authentication with database values
*/
//if login successful set whatever session vars you want and create cookie
$_SESSION['username'] = $username;
setcookie($username, $password, time()+3600);
?>
Prior to this you will have check the users credentials and log them in or deny them. Once logged in you set the session variables. Then to create the cookie you use the code above.
$user = mysql_real_escape_string($_POST['user']);
$pass = mysql_real_escape_string($_POST['pass']);
$sql = "SELECT * FROM users WHERE username='$user' AND password='$pass'";
$result = mysql_query($sql);
That will take care of your sql injection vulnerabilities and also get you the correct account only if both the username and password are correct
Now you can use your conditions to set the cookies and sessions

Categories