Upgrade from php5 to php7 problems

Please can some one help me. We have upgraded php and not i cant get the php page to correctly redirect the user to the login page if the user has not logged in and the get it to redirect to the index page. So the form sequence is as follows. User connects to index page, user clicks on link to add or delete data in mysql database, page must redirect to login page if user has not logged in, once logged in login page must redirect to add or delete page depending on the link clicked on. Addins and deleting data to the mysql database table works fine.

Below is the add,php page.

 <?php

ini_set(‘display_errors’, 1);
ini_set(‘display_startup_errors’, 1);
error_reporting(E_ALL);

session_start(); //start session.
if(!isset($_GET[‘name’])){//added this to check if name is sent
include(‘database.php’);
if (!isset($_SESSION[“user.id”]) && $_SESSION[“user.id”] !="")
{
}
else{
header(“Location: login.php”);
}

if($_POST[‘action’])
{

include(‘email.php’);
$address="";
$name=$_POST[‘name’];
$extension=$_POST[‘extension’];
$department=$_POST[‘department’];
$phone=$_POST[‘phone’];
$email=$_POST[‘email’];

$sql = “INSERT INTO users (ID, Name, Email, Extension, Phone, Department) VALUES (NULL, ‘$name’, ‘$email’, ‘$extension’, ‘$phone’, ‘$department’)”;

if ($conn->query($sql) === TRUE)
echo “New record added”;
else
echo "Error: " . $sql . “
” . $conn->error;
$conn->close();
}

}

Below is the login.php

<?php

ini_set(‘display_errors’, 1);
ini_set(‘display_startup_errors’, 1);
error_reporting(E_ALL);

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 $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
// mysqli_connect() function opens a new connection to the MySQL server.
$conn = mysqli_connect("localhost", "root", "Pr1v@cY", "T-List_VW");
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * from UserName where userName=? AND pass=? LIMIT 1";
// To protect MySQL injection for Security purpose
$stmt = $conn->prepare($query);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->fetch()) //fetching the contents of the row {
$_SESSION['login_user'] = $username; // Initializing Session
header("location: index.php"); // Redirecting To Profile Page
}
mysqli_close($conn); // Closing Connection
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="login">
<h2>Login Form</h2>
<form action="" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password"><br><br>
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</body>
</html>

Among other problems, the session variable you are setting and testing are not the same, so the posted code never worked, regardless of php version.

Hi, In php5 the code worked but i have removed and added so much that its not near the same as what it was in php5. I still have the code for php5 so i can post it. How do i fix it for php7. Im a beginner at this and its basically some one else who did the code for php5 and now its become my problem.

The php documentation contains detailed lists of all the major changes that have taken place between versions - https://www.php.net/manual/en/appendices.php You would start with whatever php5 version you were using and make sure your code isn’t using any backward incompatible, deprecated, or removed features in going all the way up to the current php7 version.

Some comments about the posted code that will help you write simple, uncluttered code that will either work or it will tell you why it isn’t working -

  1. Put the error related settings into the php.ini on your system.
  2. Only store the user id (auto-increment integer primary index) in a session variable to indicate who the logged in user is. Query on each page request to retrieve any other user related information.
  3. Every header() redirect needs an exit statement to stop program execution.
  4. Don’t copy variables to other variables without any good reason. Just use the original variables.
  5. Use ‘require’ for things that you code must have for it to work, and ‘require’ isn’t a function, so don’t use an ().
  6. Trim all input data (you can use a single statement) so that you can detect if all white-space characters were entered.
  7. Validate all input data before using it, storing validation errors in an array. This array will also serve as an error flag. If the array is empty, there are no errors.
  8. Use a prepared query when supplying external/unknown data to an sql query. You have one that is and one that isn’t. Consistency counts in programming.
  9. When testing a boolean value, don’t explicitly compare it with true or false values. This is missing the point of booleans.
  10. Don’t output raw database errors onto a web page. This just gives hackers useful information when they intentionally trigger errors. Use exceptions for database statements and in most cases let php catch and handle the exception where it will use its error related settings to control what happens with the actual error information (database errors will get displayed/logged the same as php errors.) The exception t this rule is when inserting/updating data that might be duplicate or out of range. In this case, you code should catch the exception, test the error number, and if the error is for something your code can handle, set up a user error message telling exactly what was wrong with the submitted data.
  11. Don’t bother closing database connections. Php will do that when the script ends.
  12. If you have the database connection code in a separate file (database.php), why aren’t you using that in each case? Don’t Repeat Yourself (DRY.)
  13. Don’t use the mysqli extension. Instead use the much simpler and consistent PDO extension.
  14. Don’t store plain-text passwords. Use php’s password_hash() and password_verify(). If you already have un-hashed passwords stored, make a backup of your database, add a new column to the table to hold the hashed passwords, and use an UPDATE query to populate the new column with the hashes. After you have tested to make sure all the code dealing with the password is working using password_hash() and password_verify(), delete the old column from the table holding the plain-text passwords.
1 Like

Excellent list @phdr. That pretty much covers the bulk of problems we see on the forums.

Ok thanks for that information i will go read it, but for now i just dont have the time to do so and are under pressure to get this fixed. I have already spend 4 evenings on this.

Thanks anyway for all your time.

The following is working, PDO based, example login code using the above list of programming practices, plus a few more (see comments in the code) -

<?php
session_start();

// detect if the current visitor is already logged in
if(isset($_SESSION['user_id']))
{
	die(header('location:index.php')); // go to main page
}

require 'pdo_connection.php'; // put database connection code in an external .php file and require it when needed
// note: the PDO connection code should - set the character set for the connection to match your database table character set, set error mode to exceptions, set emulated prepared queries to false, and set the default fetch mode to assoc

$errors = []; // an array to hold errors
$post = []; // an array to hold a trimmed working copy of the form data

// post method form processing
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
	// trim the submitted data
	$post = array_map('trim',$_POST); // if any of the form fields are arrays, use a recursive trim call-back function here instead of php's trim function

	// validate the submitted data
	if($post['username'] == '')
	{
		$errors['username'] = "Username is empty.";
	}
	if($post['password'] == '')
	{
		$errors['password'] = "Password is empty.";
	}
	
	// if no errors, use the submitted data
	if(empty($errors))
	{
		// list the columns you are SELECTing
		$sql = "SELECT id, password from users WHERE username = ?";
		$stmt = $pdo->prepare($sql);
		$stmt->execute([
			$post['username']
			]);
		if(!$row = $stmt->fetch()) // note the ! (not) being used
		{
			// username not found
			$errors['login'] = "Invalid Username/Password.";
		} else {
			// username found, verify password hash
			if(!password_verify($post['password'],$row['password']))
			{
				// password doesn't match
				$errors['login'] = "Invalid Username/Password.";
			} else {
				// password matches
				$_SESSION['user_id'] = $row['id'];
			}
		}
	}
	
	// if no errors, success
	if(empty($errors))
	{
		// redirect to the exact same url of this page to cause a get request - PRG Post, Redirect, Get.
		die(header("Refresh:0"));
	}
}


// at the point of (re)displaying the form, use the data in $errors to display any error messages and in $post to repopulate the form fields
// any 'dynamic' values should have htmlentities() applied when they are being output on a web page to help prevent cross site scripting
?>

you would output a complete and valid html document starting here...

<?php
// display any errors
if(!empty($errors))
{
	echo implode('<br>',$errors);
}

// output the form
?>
<form method='post'>
Username: <input type='text' name='username' value='<?php echo htmlentities($post['username'] ?? '',ENT_QUOTES); ?>'><br>
Password: <input type='password' name='password' value='<?php echo htmlentities($post['password'] ?? '',ENT_QUOTES); ?>'><br>
<input type='submit'>
</form>

Hi phdr, as far as i undertand PDO and MYSQLI is 2 diferent ways of connecting php to a mysql databse. All my database connections are mysqli based. In the below code php does redirect me to the login page and then back to the index page, then when i click on add again instead of taking me to the add php page it takes me back to the login php page. Its like its not reading the part where its suppose to check if the user has already logged in.

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start(); //start session.
if(!isset($_GET['name'])){//added this to check if name is sent
include('database.php');
if (!isset($_SESSION["user.id"]) && $_SESSION["user.id"] !="")
{
}
else{
    header("Location: login.php");
}

if($_POST['action'])
{

include('email.php');
  $address="";
  $name=$_POST['name'];
  $extension=$_POST['extension'];
  $department=$_POST['department'];
  $phone=$_POST['phone'];
  $email=$_POST['email'];

$sql = "INSERT INTO users (ID, Name, Email, Extension, Phone, Department) VALUES (NULL, '$name', '$email', '$extension', '$phone', '$department')";


if ($conn->query($sql) === TRUE)
echo "New record added";
else 
echo "Error: " . $sql . "<br>" . $conn->error;
$conn->close();
 }
}
?>

So i made some changes.

This code does not take me to the add page it just brings me to a blank page HTTP 500 (website cannot be displayed.

<?php

// To display any coding errors on the page
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start(); //start session.
include('database.php');
if(!isset($_SESSION['username'] && $_SESSION['username'] !="")){   // To check if the user has logged in
    header("Location: login.php"); // To redirect to login page if user has not logged in
   exit();   // To skip the login page and exit if the user has logged in
}

/?>

This code keeps taking me back to the login page

<?php

// To display any coding errors on the page
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start(); //start session.
include('database.php');
if(!isset($_SESSION['username'])){   // To check if the user has logged in
    header("Location: login.php"); // To redirect to login page if user has not logged in
   exit();   // To skip the login page and exit if the user has logged in
}

/?>

Hello phdr

Thanks for your help, really appreciate it.
I have started looking at your code, and using it i get a error that says Invalid password.

> <?php
> 
> //ini_set('display_errors', 1);
> //ini_set('display_startup_errors', 1);
> //error_reporting(E_ALL);
> 
> session_start();
> 
> // detect if the current visitor is already logged in
> if(isset($_SESSION['user_id']))
> {
>         die(header('location:index.php')); // go to main page
> }
> 
> require 'pdo_connection.php'; // put database connection code in an external .php file and require it when needed
> // note: the PDO connection code should - set the character set for the connection to match your database table character set, set error mode to exceptions, set emulated prepared queries to false, and set the default fetch mode to assoc
> 
> $errors = []; // an array to hold errors
> $post = []; // an array to hold a trimmed working copy of the form data
> 
> // post method form processing
> if($_SERVER['REQUEST_METHOD'] == 'POST')
> {
>         // trim the submitted data
>         $post = array_map('trim',$_POST); // if any of the form fields are arrays, use a recursive trim call-back function here instead of php's trim function
> 
>         // validate the submitted data
>         if($post['username'] == '')
>         {
>                 $errors['username'] = "Username is empty.";
>         }
>         if($post['password'] == '')
>         {
>                 $errors['password'] = "Password is empty.";
>         }
> 
>         // if no errors, use the submitted data
>         if(empty($errors))
>         {
>                 // list the columns you are SELECTing
>                 $sql = "SELECT userNameID, pass from UserName WHERE userName = ?";
>                 $stmt = $pdo->prepare($sql);
>                 $stmt->execute([
>                         $post['username']
>                         ]);
>                 if(!$row = $stmt->fetch()) // note the ! (not) being used
>                 {
>                         // username not found
>                         $errors['login'] = "Invalid Username.";
>                 } else {
>                         // username found, verify password hash
>                         if(!password_verify($post['password'],$row['password']))
>                         {
>                                 // password doesn't match
>                                 $errors['login'] = "Invalid Password.";
>                         } else {
>                                 // password matches
>                                 $_SESSION['user_id'] = $row['id'];
>                         }
>                 }
>         }
> 
>         // if no errors, success
>         if(empty($errors))
>         {
>                 // redirect to the exact same url of this page to cause a get request - PRG Post, Redirect, Get.
>                 die(header("Refresh:0"));
>         }
> }
> 
> 
> // at the point of (re)displaying the form, use the data in $errors to display any error messages and in $post to repopulate the form fields
> // any 'dynamic' values should have htmlentities() applied when they are being output on a web page to help prevent cross site scripting
> ?>
> 
> # you would output a complete and valid html document starting here...
> 
> <?php
> // display any errors
> if(!empty($errors))
> {
>         echo implode('<br>',$errors);
> }
> 
> // output the form
> ?>
> <form method='post'>
> Username: <input type='text' name='username' value='<?php echo htmlentities($post['username'] ?? '',ENT_QUOTES); ?>'><br>
> Password: <input type='password' name='password' value='<?php echo htmlentities($post['password'] ?? '',ENT_QUOTES); ?>'><br>
> <input type='submit'>
> </form>

my database connection file is this.

 <?php
$servername = "localhost";
$username = "******";
$password = "**********";
$dbname = "T-List_AK";
$charset = "utf8md4";

try {
    $pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
?>

The output on my page is:
Connected successfully # you would output a complete and valid html document starting here… Invalid Password
So the database connection is working and if i put the incorrect username in it will tell me incorrect username, but its not reading the password for some reason. I changed the password in the database to be 1234 and i changed it to bike and it gives me the same error. Invalid password.

Please read the above information, I also recommend that you read the php.net documentation for password_hash() and password_verify().

Sponsor our Newsletter | Privacy Policy | Terms of Service