PHP Session 5.4 to 5.6 - php

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

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.

session_start() causing problems

I am having problems with my code. This is a login/register script I've made by following a tutorial.
The problem I have is that I want the script to echo "logged in" ONLY when the user has entered correct login details, and yet it still echoes "logged in" even if I don't enter any login details. I checked it and if I delete the "session_start()" function, it doesn't do the same thing, but it still doesn't give me access to the session when I want to login.
This is the init.php file, used to initiate the connection with the database and define some other functions:
<?php
session_start();
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
$errors = array();
?>
This is the connect.php file, used to connect to the database :
<?php
$connect_error = 'Sorry, we are experiencing connection issues. This will be solved as soon as possible.';
$con=mysqli_connect("localhost","root","","lr") or die ($connect_error);
mysqli_select_db($con,'lr') or die($connect_error);
mysqli_close($con);
?>
The general.php file is not important for this question.
This is the users.php file, where I keep some other functions.
function user_id_from_username ($username){
$username = sanitise($username);
$mysqli = new mysqli("localhost", "root", "", "lr");
$query = "SELECT * FROM users";
$result = $mysqli->query($query);
while($row=$result->fetch_row()){
if ($row[1]==$username){ //username == $username
return $row[0];//user_id;
}
}
}
function login ($username, $password){
$user_id= user_id_from_username($username);
$mysqli = new mysqli("localhost", "root", "", "lr");
$username = sanitise($username);
$password =md5 ($password);
$query = "SELECT * FROM users";
$result = $mysqli -> query($query);
while ($row =$result -> fetch_row()){
if($row[1]==$username && $row[2]==$password){
return TRUE;
}else {
return FALSE;
}
}
}
This is the file that calls the login function, presented above:
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) ===TRUE || empty ($password) === TRUE) {
$errors[]='You need to enter a username and password!';
} else if (user_exists($username) ===FALSE) {
$errors[]="We can't find that username, have you registered?";
} else if (user_active($username)===FALSE){
$errors[]="You have not activated your account!";
} else{
$login = login($username, $password);
session_start();
if ($login ==false) {
$errors[] ='That username/password combination is incorrect!';
}else if ($login==true) {
//set the user session
$_SESSION['username'] = $login;
//redirect user to homepage
header('Location: index.php');
exit();
}
}
if ($errors){
print_r($errors);
}
}
?>
And now the index.php file, in which I have the if statement that echoes 'logged in' even if I am not logged in :
<?php
if (empty($_SESSION['username'])) {
echo 'not logged_in';
}else {
echo 'logged in';
}
?>
Now I think the problem is located somewhere either in the users.php, login.php or in the index.php file. I presented all of the files so you could get an idea of what I am trying to achieve. This code is spread over so many files because I have functions and interfaces that I have included and I want to be able to reuse the code, so I am using includes.
For you to get a better idea, if my files did not help you enough, I will leave the Youtube link of the tutorial I am following :
https://www.youtube.com/watch?v=JUk2e8oqOvI&list=PLE134D877783367C7&index=7#t=6.296979
Thank you,
Waiting for your answer,
Best regards,
If you don't use $_GET requests to include the pages, you need to put session_start() on top of each file where you are using the $_SESSION variable otherwise you can't use the sessions.
<?php
session_start();
// Rest of your script
I hope this will help you.

PHP login got Too Many Redirect Loop error

Please help me. I got this error everytime I tried to login. - "This webpage has a redirect loop ERR_TOO_MANY_REDIRECTS"
Please help me and I'll appreciate your help very much. thanks.
This is my index.php
<?php
include('login.php'); // Includes Login Script
?>
This is my login.php
<?php
session_start();
$error = "";
if (isset($_POST['submit'])) {
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$usernameLogin = $_POST['email'];
$passwordLogin = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "apple", "Apple318992");
// To protect MySQL injection for Security purpose
$username = stripslashes($usernameLogin);
$password = stripslashes($passwordLogin);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("TS", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from Users where password='$password' AND email='$usernameLogin'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user'] = $usernameLogin; // Initializing Session
} else {
$error = "Username or Password is invalid";
}
}
}
if (isset($_SESSION["login_user"])) {
header("Location:timesheets.php");
}
?>
This is my session.php
<?php
include ('DBConnect.php');
session_start(); // Starting Session
// Storing Session
$user_check = $_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql = mysql_query("select email from Users where email='$user_check'", $conn);
$row = mysql_fetch_assoc($ses_sql);
$login_session = $row['email'];
if (!isset($login_session)) {
mysql_close($conn); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
?>
instead of : header('Location: index.php');
try to do it with javascript :
echo '< script> document.location.href="index.php"< /script>';
In your session.php you have to destroy the session because it might be set still but without that the query can find a existing user?
To unset sessions do this:
unset(); for all the session variables unset($_SESSION['login_user']); for a specific session
Please put that before redirecting to index.php.
Otherwise I don't know how to help you sorry.
Also do you have php error / debug enabled? Normally session_start(); should be at very first line in your php file if I am correct, or it throws error.

PHP Authentication works only local

I have a PHP login page that works perfectly locally, but when in server always come out with "Invalid Username or Password". I tried it in two different servers and the result was the same.
login.php
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password']))
{
$error = "Username or Password is invalid";
}
else
{
// Define $username1 and $password1
$username1 = $_POST['username'];
$password1 = $_POST['password'];
include_once ('lib/db.php');
$connection = new mysqli($servername, $username, $password, $dbname);
$username1 = stripslashes($username1);
$password1 = stripslashes($password1);
$username1 = mysql_real_escape_string($username1);
$password1 = mysql_real_escape_string($password1);
// SQL query to fetch information of registerd users and finds user match.
$query = "select * from login where PASSWORD='$password1' AND USERNAME='$username1'";
$result = $connection->query($query);
$rows = mysqli_num_rows($result);
if ($rows == 1)
{
$_SESSION['user']=$username1; // Initializing Session
$_SESSION['pppv'] = 10;
header("Location: logged-in.php"); // Redirecting To Other Page
}
else
{
$error = "Username or Password is invalid";
}
}
}
EDIT
Try printing the query after submission gives me this:
Local:
select * from login where PASSWORD='test' AND USERNAME='test'
Server:
select * from login where PASSWORD='' AND USERNAME=''
Use isset($_POST['username']) ||isset($_POST['password'])instead of empty($_POST['username']) || empty($_POST['password']).
Read this to know the difference between isset and empty.
There's no context, but check these things:
Does your database contain the same credentials as local?
Does your requested page return http status such as 200? If it's 404, there's something wrong with your path's. If it's 500, there's an internal error (right permissions set?)
Did you check your log files?
Did you clear your browser cookies and history?
Did you print the full query (including filled parameters) to the window and did you execute this query in your database management tool? And did you get result?

Session script not setting variable

I'm new to sessions and don't think my code is working correctly.
My aim is to use PDO and not SQL, but as I'm also new to PDO too, I'm getting a little stuck.
I'm trying to set up my $who as a session but things are getting confusing for me as I go between SQL and PDO. Can you help me make things kosher?
<?php
require_once('/scripts/include.php');
require_once('/scripts/includePDO.php');
$error = '';
$form = $_POST['submit'];
$email = $_POST['email'];
$password = $_POST['password'];
if( isset($form) ) {
if( isset($email) && isset($password) && $email !== '' && $password !== '' ) {
$sql = "SELECT * FROM tbl_users WHERE email = :email and password = :password";
$q = $conn->prepare($sql); // the default way of PDO to manage errors is quite the same as `or die()` so no need for that
$q->bindValue(':email',$email,PDO::PARAM_STR);
$q->bindValue(':password',$password,PDO::PARAM_STR);
$q->execute();
$r = $q->fetch(PDO::FETCH_ASSOC);
if(($r)!=0)
{ //success
$info = mysql_fetch_array( $sql );
$answer = $info['id'];
$_SESSION['logged-in'] = true;
$_SESSION['who']=$answer;
//If the login details are entered and they match those in the database, forward to new page.
header('Location: /social3/home/');
exit;
// If information is wrong or missing, provide error message.
} else { echo "Sorry, something hasn't worked. Are you entering all the information correctly?"; }
}
}
?>
I think everything is fine until I get to //success and then I lost my way.
----- Additional session question ----
At the top of each of my website pages, I include a php file that allows PDO to connect to my database. This is necessary as most of my pages use PDO queries.
But looking back at that coding now, it, for some reason, has some session coding at the top. Should this be there (taking into account, I assign a session on an entirely different page?
<?php
session_start();
$host = "xxxx";
$db = "xxxx";
$user = "xxxx";
$pass = "xxxxx";
$conn = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
?>
--- Further questioning ---
So, finally... more session and PDO wonderings.
At the top of each page, I include a file to ensure the user is logged in, if not they get forwarded to the login page.
I'm changing this code to PDO from SQL also, and obviously have gaps in my PDO knowledge which show in the below code. Help?
<?php
session_start();
$who = $_SESSION['who'];
$host = "xxx";
$username = "xxxx";
$password = "xxxx";
$db = "xxx";
#mysql_connect(:host,:username,:password);
$q = $conn->prepare($sql);
$q->bindValue(':host',$host,PDO::PARAM_STR);
$q->bindValue(':username',$username,PDO::PARAM_STR);
$q->bindValue(':password',$password,PDO::PARAM_STR);
$q->execute();
#mysql_select_db($db) or die("error");
// is the one accessing this page logged in or not?
if ( !isset($_SESSION['logged-in']) || $_SESSION['logged-in'] !== true) {
// not logged in, move to login page
header('Location: /social3/');
exit;
}
?>
You are using PDO, so these line will not work -
$info = mysql_fetch_array( $sql );
$answer = $info['id'];
You have already fetched the row and stored it in $r, so you just need -
$answer = $r['id'];
in response to your edit.
The session_start(); that is on the top of your included php code/page is necessary. Without it you could not do $_SESSION['logged-in'] = true; & $_SESSION['who']=$answer;. You need to start a session in order to set session values, and it must be before any data/headers are sent. Take a look at the manual - http://php.net/session_start

Categories