Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 53

PHP 5 Introduction

PHP is an open-sourced, general-purpose programming language. It is especially


useful in web development, and particularly working with the server, in other
words, the back-end.

PHP itself stands for Hypertext Preprocessor. Code written in PHP is meant
almost exclusively for the server. It can load data and put it into the HTML DOM,
but it does not have as much control as, for example, JavaScript. It can, however,
connect to the database, start sessions, apply a script to the HTML content.

Contents

 1. PHP Files
 2. PHP Functionality
 3. PHP Advantages

PHP Files

To write PHP code, you need to save it in a file with suffix ".php". While it has a
different suffix, it works as a basic HTML file too. The thing is though, that file
with the ".html" suffix cannot run PHP.

If you were to inspect the document as loaded though, you would not find any
trace of PHP. That is because PHP is executed on the server, and only the resulting
HTML content is shown on the browser.

PHP Functionality

While PHP is quite universal overall, it is best suited for web development. There
are multiple uses to PHP, when it comes to creating web applications.

With PHP you can:

 Create dynamic content


 Create, open, write to, read, delete, and close files on the server
 Collect data from forms
 Receive and send cookies
 Add and modify database information
 Data encryption
 PHP can output not only HTML but also PDF images, Flash files, XML text
files or any other text.

PHP Advantages

There are, of course, many advantages to using PHP overall as well. Here are a few
to name:

 PHP is easy to learn is very efficient server side language


 PHP runs on multiple platforms (Windows, Mac OS X, Linux, Unix, etc.)
 PHP can connect to almost every server (IIS, Apache etc.)
 PHP can connect to many databases
 PHP is free

Contents

 1. PHP 5 Installation Main Tips


 2. PHP 5 Installation Using A Web Host
 3. PHP 5 Installation For Personal Computers

PHP 5 Installation Main Tips

 To run PHP on your computer you may consider installing a web server.
 To start using PHP right away, you can find a web host with PHP and
MySQL support.
 One of the options to immediately install PHP on Windows is downloading
WebMatrix.

PHP 5 Installation Using A Web Host

Most web hosting servers nowadays support and don't need to install PHP
manually, so you can get to using PHP on web hosting right away.

To get started, you may create an index.php file and upload it via FTP access.
PHP 5 Installation For Personal Computers

Most computers don't support PHP by default. To install PHP on your computer,
you need the following on your computer:

 Web server
 PHP ( PHP.net offers instructions to install
PHP: http://php.net/manual/en/install.php)
 Database (i.e. MySQL)

PHP 5 Syntax

Contents

 1. PHP 5 Syntax Main Tips

 2. Basic PHP Syntax

 3. Comments in PHP

 4. PHP Case Sensitivity

PHP 5 Syntax Main Tips

 A PHP script is run on the server, and only the plain HTML is sent back to
the web browser.
 A semicolon symbol (;) is at the every PHP statement end.
 Remember that only variables are case-sensitive.

Basic PHP Syntax

A PHP script can be put anywhere in the document.

A PHP script is written between <?php and ?>:

<?php
// Here is PHP code
?>
".php" is the default PHP file extension.

A PHP file is contained of HTML tags, and PHP script..


THis is simple PHP example, with echo statement:

Example
<!DOCTYPE html>
<html>
<body>

My first PHP web page

<?php echo "Hello Drago!"; ?> </body> </html>

Find Coding Exercises

Comments in PHP

A comment in PHP cannot be executed as a program, it can be seen only by


reading the code.

It is used to help understand the code or/and put some reminders, to remind what
was is your head when the code was written.

Several ways of commenting are supported:

Example
<!DOCTYPE html>
<html>
<body>
<?php
// A comment in the single line

# Another way of a comment in the single line

/*
A comment in
the multiple
lines
*/
// A code line parts can be left out with comments
$number = 19 /* + 39 */ + 12;
echo $number;
?>
</body>
</html>

Find Coding Exercises

PHP Case Sensitivity

In PHP, all keywords (e.g. else, if, echo, while etc.), functions, user-defined
functions, and classes are NOT case-sensitive.

In this example, all three echo lines are equal and legal.

Example
<!DOCTYPE html>
<html>
<body>

<?php
ECHO "Hello, Drago!<br>";
echo "Hello, Drago!<br>";
EcHo "Hello, Drago!<br>";
?>

</body>
</html>

Find Coding Exercises

However; all variable names are case-sensitive.

In this example, first echo statement with &name will be displayed correctly, and
other two not because $NAME and $nAmE are treated as different variables.

Example
<!DOCTYPE html>
<html>
<body>

<?php
$name = "John";
echo "I love " . $name . "<br>";
echo "This is " . $NAME . "<br>";
echo "My friend is " . $nAmE . "<br>";
?>

</body>
</html>

PHP 5 Variables

Contents

 1. PHP 5 Variables Main Tips


 2. The Variables
 3. Output
 4. A Relatively Loose Language
 5. Scope
 6. Global/Local
 7. Global
 8. Static

PHP 5 Variables Main Tips

 In php variables start with a $ sign.


 Information is stored in these variables.
 A variable can't start with a number.
 These variables are case-sensitive and should start with either a letter or a
underscore character _.

The Variables

Variables can consist of a tiny name like a letter (x, y, z and so on) or a longer one
(tree, household, longestwordintheworld)

This example shows that the variable $text is a container to the value of Hey
coders! and both $x and $y variables hold their respective values 9 and 1.
Example
<?php $text = "Hey coders!"; $x = 9;$y = 1; ?>

Find Coding Exercises

Note: In order to correctly assign text to a variable, quotes are used.

Output

An echo statement outputs information to the monitor

Example
<?php $txt = "learn.xyz"; echo "I want to visit
$txt!";?>

Find Coding Exercises

A Relatively Loose Language

Unlike PHP, different languages like Java, C and C++ also require to declare the
variable type.

PHP detects the correct one automatically.

Scope

There are three main scopes:

 local
 global
 static

Because variables in PHP can be expressed at any place inside the script, these
scopes are used at the variable reference.

Global/Local

Expressing a variable outside the function gives it a Global variable scope which
makes it usable anywhere outside the function

Example
<?php
$x = 10; // global scope
 
function LearnTest() {
    // using x inside this function will generate an
error
    echo "The x inside function is: $x";

LearnTest();

echo "The x outside function is: $x";


?>

Find Coding Exercises

Expressing a variable inside the function gives it a Local variable scope which
makes it usable only inside that particular function

Example
<?php
function learnTest() {
    $x = 9; // local scope
    echo "Variable x inside function is: $x";

learnTest();

// using x outside the function will generate an error


echo "Variable x outside function is: $x";
?>

Find Coding Exercises

Note:  Duplicating named variables can exist inside their respective functions thus
having Local scope.

Global

In order to use a variable with a global scope from inside the functions a Keyword
global is used

Example
<?php
$x = 10;
$y = 10;

function learnTest() {
    global $x, $y;
    $y = $x + $y;
}

learnTest();
echo $y; // outputs 20
?>

Find Coding Exercises

Global variables are stored in a $GLOBALS[index] array. These variables can be


accessed and thus changed right inside functions

Example
<?php
$x = 20;
$y = 10;

function learnTest() {
    $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];

learnTest();
echo $y; // outputs 30
?>

Find Coding Exercises

Static

Usually after the function is executed, the variables inside are deleted. In order for
the local variable to stay after the function is done, a static keyword must be used.

Example
<?php
function learnTest() {
    static $x = 0;
    echo $x;
    $x++;
}

learnTest();
learnTest();
learnTest();
?>

PHP 5 Echo And Print Statements

Contents

 1. PHP 5 echo And print Statements Main Tips


 2. PHP echo Statement
 3. PHP print Statement

PHP 5 echo And print Statements Main Tips

 The two standard ways of displaying text in PHP are echo and print.
 Both of these statements are mostly similar.
 Echo is much faster than print.
 Echo has no return value, print returns 1.
 Echo can display multiple parameters in a single statement, unlike print.
 You can write echo without parentheses as well as with them.

PHP echo Statement

The code here shows how you can display text using echo and include HTML
markup into the statement:

Example
<?php
echo "<h2>Am I ready?!</h2>";
echo "Howdy!<br>";
echo "I'm ready!<br>";
echo "I ", "made ", "this ", "string ", "with my handy
hands!";
?>

Find Coding Exercises


The code below shows how you can display both text and variable using echo:

Example
<?php
$text1 = "I am ";
$text2 = "Ready!";
$var1 = 4;
$var2 = 3;
echo "<h2>" . $text1 . $text2 . "</h2>";
echo $var1 + $var2;
?>

Find Coding Exercises

PHP print Statement

The code here shows how you can display text using print and include HTML
markup into the statement:

Example
<?php
print "<h2>I am ready to learn PHP!</h2>";
print "Hey there!<br>";
print "I will learn ALL the PHP!";
?>

Find Coding Exercises

The code below shows how you can display both text and variable using print:

Example
<?php
$text1 = "Learning PHP";
$text2 = "ALL the PHP";
$var1 = 58;
$var2 = 4;
print "<h6>" . $text1 . $text2 . "</h6>";
print $var1 + $var2;
?>

PHP 5 Data Types


Contents

 1. PHP 5 Data Types Main Tips


 2. PHP Strings
 3. PHP Integers
 4. PHP Floats
 5. PHP Booleans
 6. PHP Arrays
 7. PHP Objects
 8. PHP NULL Values
 9. PHP Resources

PHP 5 Data Types Main Tips

 PHP 5 Data Types include variables, integers, strings, booleans, floats,


arrays, objects, NULL and resources.
 Data types and can tell you about how these data forms they can be used.

PHP Strings

Strings are sequences of characters, which can make up words, sentences, and
others.

Strings have to be defined inside quotes. Using both double and single quotes
works:

Example
<?php
$txt1 = "Hello world!";
$txt2 = 'Hello world!';
echo $txt1;
echo "<br>";
echo $txt2;?>

Find Coding Exercises

Note: If you want to display quotes inside a string, you need to surround them with
a different kind of quotes, i.e. if you surround a string with single quotes, you can
use double quotes inside, and vice versa.

PHP Integers
An integer is a data type, a numeric variable that is non-decimal and between
-2,147,483,648 and 2,147,483,647.

Integers have to abide a few rules:

 Must contain at least a single digit.


 Cannot have a decimal point.
 It can be positive or negative.
 Integers come in decimal, hexadecimal and octal forms.

The example below has an integer $x. A function called PHP var_dump() will
return the data type and value of a variable:

Example
<?php
$x = -6532;
var_dump($x);
?>

Find Coding Exercises

PHP Floats

Floats (floating point numbers) are numbers that have a decimal point or numbers
in an exponential form.

The example below has a float $x. A function called PHP var_dump() will return
the data type and value of a variable:

Example
<?php
$x = 201.9865;
var_dump($x);
?>

Find Coding Exercises

PHP Booleans
A boolean can have one of these two values: TRUE or FALSE. You can treat it as
a sort of switch. This makes them very lightweight and useful for conditional
statements.

Example
$true = true;
$false = false;
if ($false=true)
{
echo "This isn't right.";
}

Find Coding Exercises

PHP Arrays

An array is a variable, that can store multiple values.

The example below has an array $x. A function called PHP var_dump() will return
the data type and value of a variable:

Example
<?php
$x = array("1","2","3");
var_dump($x);
?>

Find Coding Exercises

PHP Objects

An object is a data type that can store data and info for how the data can be
processed.

In PHP, objects have to be declared.

Firstly the class of the object has to be declared. To do this, you have to use a class
keyword. Classes are structures containing properties and methods:

Example
<?php
class obj {   
function x() {       
$this->num = "2";}}
// create an object
$obj_value = new obj();
// show object properties
echo $obj_value->num;
?>

Find Coding Exercises

PHP NULL Values

This is a special type of data, which can only have a single value: NULL.

NULL variables have no real value assigned to them.

Variable values can be cleared by setting them to NULL:

Example
<?php
$txt = "Hello world!";
$txt = null;
var_dump($txt);
?>

Find Coding Exercises

Tip: Values that are created without an assigned value, they are assigned the value
of NULL by default.

PHP Resources

The resource data type is not exactly a data type. It is a storage of a reference to
various resources outside of PHP.

A commonly used example of a resource is a database call.

<?php include("header.php")?>
<?php include("menu.php")?>
<div id="registrationPage">
<div id="registrationDiv" ></div>
<fieldset id="registrationFieldPos">
<legend><h3>Register</h3></legend>
<form id="registrationForm"
action="registrationaction.php" method="POST"
enctype="multipart/form-data">
<table>
<tr>
<td><label>First Name :</label></td>
<td><input type="text" name="fname" /></td>
</tr>
<tr>
<td><label>Last Name :</label></td>
<td><input type="text" name="lname" /></td>
</tr>

<tr>
<td><label>Username :</label></td>
<td><input type="text" name="username" /></td>
</tr>

<tr>
<td><label>Password :</label></td>
<td><input type="password" name="password" /></td>
</tr>

<tr>
<td><label>Confirm Password :</label></td>
<td><input type="password" name="passwordconfirm"
/></td>
</tr>

<tr>
<td><label>Email :</label></td>
<td><input type="email" name="email" /></td>
</tr>

<tr>
<td><label>Image :</label></td>
<td><input type="file" name="fileUpload" /></td>
</tr>
<tr>
<td><label>Country :</label></td>
<td>
<select name="country">
<?php

$connection = mysqli_connect('localhost', 'root', '',


'mutetistore') or die('connection error'.
mysql_error());
mysqli_select_db($connection, 'mutetistore');

$sql = "SELECT * FROM apps_countries" ;


$results = mysqli_query($connection, $sql);
while($result = mysqli_fetch_array($results)):;

?>
<option value=" <?php echo $result['country_name']; ?>
"> <?php echo $result['country_name'];?> </option>

<?php endwhile; ?>

</select>
</td>
</tr>

<tr>
<td><label>Languages :</label></td>
<td>
<label>English <input type="checkbox"
name="Languages[]" value = "English" /></label>
<label>French<input type="checkbox" name="Languages[]"
value = "French" /></label>
<label>Swahili<input type="checkbox" name="Languages[]"
value = "Swahili" /></label>
</td>
</tr>

<tr>
<td><label>Gender:</label></td>
<td>
<label>Male <input type="radio" name="gender" value =
"male"/></label>
<label>Female</label><input type="radio" name="gender"
value = "female"/>
</td>

</tr>

<tr>
<td><input type="submit" name="save" value =
"registered"/></td>
</tr>

</table>

</form>
</fieldset>
<div id="divEnd">
</div>
</div>
<?php include("footer.php")?>
<?php

require('databaseconn.php');
if(isset($_POST['save']) ) {
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$username = $_POST['username'];
$password = $_POST['password'];
$passwordconfirm = $_POST['passwordconfirm'];
$country = $_POST['country'];
$gender = $_POST['gender'];
$Languages = $_POST['Languages'];
$imagename = $_FILES['fileUpload']['name'];
$imagesize = $_FILES['fileUpload']['size'];
$imagetmp = $_FILES['fileUpload']['tmp_name'];
if(empty( $firstname)) {
echo "please enter username";
}else if(empty( $lastname)) {
echo "please enter lastname";
}else if(empty( $username)) {
echo "please enter username";
}else if(empty( $password)) {
echo "please enter password";
}else if(empty( $password !== $passwordconfirm)) {
echo "password do not match";
}else if(empty( $country)) {
echo "please select your country ";
}else if(empty( $gender)) {
echo "please select your gender ";
}else if(empty( $imagename)) {
echo "please select image";
}else {

$uploadFolder = "Uploads/";
$filename = rand(1000,100000)."-".$imagename;
$filenameUpload = move_uploaded_file($imagetm,
$uploadFolder, $filename);

$sql = "INSERT INTO `register` (`id`, `firstname`,


`lastname`, `username`, `password`, `country`,
`gender`, `language`, `imageName`, `imageSize`,
`imageTemp`)
VALUES (NULL, '$firstname', '$lastname', '$username',
'$password', '$country', '$gender', '$Languages',
'$filenameUpload', '$imagesize', '$imagetmp')";

}
?>

<?php echo $_POST["fname"]; ?><br>


<?php echo $_POST["lname"]; ?><br>
<?php echo $_POST["username"]; ?><br>
<?php echo $_POST["password"]; ?><br>
<?php echo $_POST["passwordconfirm"]; ?><br>
<?php echo $_POST["country"]; ?><br>
<?php echo $_POST["gender"]; ?><br>
<?php echo $_POST["password"]; ?><br>
<?php echo $_POST["passwordconfirm"]; ?><br>
<?php echo $_POST["country"]; ?><br>

Create a Login System using PHP and MYSQL Database


PHP    |    1 Feb, 2017    |    Clever Techie

Google +53  278  3  17  5

In this lesson, we're going to learn how to create a fully functional login system in
PHP including user registration, login, logout, forgot password and reset
functionality. We're going to use MySQL to store registered users in a database,
and implement sessions for knowing when the user has been logged in and logged
out.

Below is a codepen we will be using for this tutorial which is a perfect match for
what we're trying to do here, a complete registration and login form with Forgot
Password link

Click on the following link to download all of this form's HTML, CSS and
Javascript source code, we're going to need it for this tutorial: Download the Login
System source code and Cheat Sheets Make sure you download this file, and not
the actual codepen, because I've included many extra files, images and code which
you'll need to follow this lesson.
Below is a chart showing how all the PHP files in the system are interacting with
each other and what important action and display message each one does. I've
colored most PHP files yellow, mailed PHP files are in blue, and form action file
which is being called other than the file itself, which is the only one -
reset_password.php is in red. All the display messages are colored green. Finally,
the most important action a PHP file is responsible for is in gray.

Download Login System Chart from Patreon

There are three actions a user can take on the index.php page - login.php,
register.php or forgot.php, each leading to other PHP pages with important actions
and functions performed on each page. Hopefully you can see how all the pages
are connected and it gives you a good picture of how it all works, I honestly was
getting confused with the number of files myself while writing this and that's how
the chart was born.

When you download the login-system.zip file, all the source code will be included,
but if you prefer to type the code yourself, I've also included a folder called "new"
which only contains HTML and CSS code, so you can finish typing PHP yourself
by following this article. You can always refer back to the completed version to
check your code and also glance back at the chart, also included in the folder called
"img" to understand the big picture better.

The SQL code to create the database and accounts which we'll be working with is
also included in a folder called "sql". Here is what it looks like:

CREATE DATABASE accounts;

CREATE TABLE `accounts`.`users`

`id` INT NOT NULL AUTO_INCREMENT,

`first_name` VARCHAR(50) NOT NULL,

`last_name` VARCHAR(50) NOT NULL,

`email` VARCHAR(100) NOT NULL,

`password` VARCHAR(100) NOT NULL,


`hash` VARCHAR(32) NOT NULL,

`active` BOOL NOT NULL DEFAULT 0,

PRIMARY KEY (`id`)

);

Also included is a sql_import.php, which is a PHP script to execute above SQL


code, make sure you set your own $user and $password variables to connect to
MySQL database:

//connection variables

$host = 'localhost';

$user = '';

$password = '';

//create mysql connection

$mysqli = new mysqli($host,$user,$password);

if ($mysqli->connect_errno) {

printf("Connection failed: %s\n", $mysqli->connect_error);

die();

//create the database

if ( !$mysqli->query('CREATE DATABASE accounts') ) {

printf("Errormessage: %s\n", $mysqli->error);

//create users table with all the fields

$mysqli->query('
CREATE TABLE `accounts`.`users`

`id` INT NOT NULL AUTO_INCREMENT,

`first_name` VARCHAR(50) NOT NULL,

`last_name` VARCHAR(50) NOT NULL,

`email` VARCHAR(100) NOT NULL,

`password` VARCHAR(100) NOT NULL,

`hash` VARCHAR(32) NOT NULL,

`active` BOOL NOT NULL DEFAULT 0,

PRIMARY KEY (`id`)

);') or die($mysqli->error);

With the SQL database and table created, we're now ready to start coding the login
system. Let's begin with db.php file

/* Database connection settings */

$host = 'localhost';

$user = 'root';

$pass = 'mypass123';

$db = 'accounts';

$mysqli = new mysqli( $host, $user, $pass,$db ) or die($mysqli->error);

This file will be included, using PHP "require" construct on most pages, and it
simply connects us to the 'accounts' MySQL database so we can work with it.

Before we jump to the main functionality of index.php, I just wanted to go over


error.php and success.php very quickly. If you glance back at the chart, you can
see that they're simply there for displaying success and error messages
respectively. Let's look at error.php:

<?php

/* Displays all error messages */

session_start();

?>

<!DOCTYPE html>

<html>

<head>

<title>Error</title>

<?php include 'css/css.html'; ?>

</head>

<body>

<div class="form">

<h1>Error</h1>

<p>

<?php

if( isset($_SESSION['message']) AND !empty($_SESSION['message']) ):

echo $_SESSION['message'];

else:

header( "location: index.php" );

endif;
?>

</p>

<a href="index.php"><button class="button button-block"/>Home</button></a>

</div>

</body>

</html>

As you can see, the only thing it does it prints out the message from the
$_SESSION['message'] variable, which will be set on the previous page. We must
first start the session by calling "session_start()" function so we have access to
$_SESSION global variable. We then make sure that the variable is set with
"isset()" and not empty "!empty()" functions before attempting to print it out. If the
variable is not set, we redirect the user back to the "index.php" page with header()
function.

The success.php contains exactly the same code with the exception of different title
and header, so instead of error it's called success. Let's now move on to the main
file: "index.php". Note that I've excluded all the HTML below <body> tag for
brevity:

<?php

/* Main page with two forms: sign up and log in */

require 'db.php';

session_start();

?>

<!DOCTYPE html>

<html>

<head>

<title>Sign-Up/Login Form</title>
<?php include 'css/css.html'; ?>

</head>

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST')

if (isset($_POST['login'])) { //user logging in

require 'login.php';

elseif (isset($_POST['register'])) { //user registering

require 'register.php';

?>

<body>

<!-- register and login form code here -->

We check if the form is being submitted with method="post" by making sure the
request_method of $_SERVER variable is equal to POST. We then check if the
$_POST['login'] is set which is a variable of the login form, in that case we
proceed to login.php by including the code with "require" keyword. Else if....
$_POST['register'] variable is set, which is a variable of the register form, we
proceed to register.php by including it's code

Here is the HTML part where $_POST['login'] or $_POST['register'] come from:

<button class="button button-block" name="login" />Log In</button>


<button type="submit" class="button button-block" name="register"
/>Register</button>

Also, note the require 'db.php' and session_start() at the top this page. Since we're
also including login.php and register.php from the same page, the inclusion of
db.php and session_start() will also apply to any page which is being included
from index.php, in this case login.php and register.php, so we won't have to repeat
database inclusion and session start function on either pages.

Let's now look at register.php, below is the full code:

/* Registration process, inserts user info into the database

and sends account confirmation email message

*/

// Set session variables to be used on profile.php page

$_SESSION['email'] = $_POST['email'];

$_SESSION['first_name'] = $_POST['firstname'];

$_SESSION['last_name'] = $_POST['lastname'];

// Escape all $_POST variables to protect against SQL injections

$first_name = $mysqli->escape_string($_POST['firstname']);

$last_name = $mysqli->escape_string($_POST['lastname']);

$email = $mysqli->escape_string($_POST['email']);

$password = $mysqli->escape_string( password_hash($_POST['password'],


PASSWORD_BCRYPT) );

$hash = $mysqli->escape_string( md5( rand(0,1000) ) );

// Check if user with that email already exists


$result = $mysqli->query("SELECT * FROM users WHERE email='$email'") or
die($mysqli->error);

// We know user email exists if the rows returned are more than 0

if ( $result->num_rows > 0 ) {

$_SESSION['message'] = 'User with this email already exists!';

header("location: error.php");

else { // Email doesn't already exist in a database, proceed...

// active is 0 by DEFAULT (no need to include it here)

$sql = "INSERT INTO users (first_name, last_name, email, password, hash) "

. "VALUES ('$first_name','$last_name','$email','$password', '$hash')";

// Add user to the database

if ( $mysqli->query($sql) ){

$_SESSION['active'] = 0; //0 until user activates their account with verify.php

$_SESSION['logged_in'] = true; // So we know the user has logged in

$_SESSION['message'] =

"Confirmation link has been sent to $email, please verify

your account by clicking on the link in the message!";

// Send registration confirmation link (verify.php)

$to = $email;

$subject = 'Account Verification ( clevertechie.com )';

$message_body = '
Hello '.$first_name.',

Thank you for signing up!

Please click this link to activate your account:

http://localhost/login-system/verify.php?email='.$email.'&hash='.$hash;

mail( $to, $subject, $message_body );

header("location: profile.php");

else {

$_SESSION['message'] = 'Registration failed!';

header("location: error.php");

We set some session variables which we'll use to welcome the user on the
profile.php which is where register.php will redirect on a successful register. We
then prepare all the $_POST variables by applying $mysqli->escape_string()
function to protect again SQL injections. Let's take a closer look at the following
two lines which create secure password hash and generate a unique hash string:

$password = $mysqli->escape_string( password_hash($_POST['password'],


PASSWORD_BCRYPT) );

$hash = $mysqli->escape_string( md5( rand(0,1000) ) );

For the $password I have used the built-in PHP function password_hash() which
takes in two parameters, the first is the raw password provided by the user and the
second is the encryption algorithm constant, in this case - PASSWORD_BCRYPT.

To generate unique hash string, we simply use the rand() function which will
generate a random number from 0 to 1000, and then we use md5() function to
generate a unique hash from the random number. If we printed out $password and
$hash at this point, they would look something like this:

$password = $mysqli->escape_string( password_hash($_POST['password'],


PASSWORD_BCRYPT) );

echo $password;

//output:
$2y$10$PXzvWecpHeXEW.CremYvreh2/4rDdCIlGFsNtxQbigAcCC4HgtbuW

$hash = $mysqli->escape_string( md5( rand(0,1000) ) );

echo $hash;

//output: 847cc55b7032108eee6dd897f3bca8a5

die;

We then check, if the user with the entered email already exists in the database
before proceeding, if they do, we redirect to error.php page. If you recall,
whenever we run "SELECT" statement in a PHP SQL query, we get the result
object returned, so it makes sense to call the variable $result. Here is what the
object would look like if we used var_dump() function on it:

var_dump( $result );

//output: object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=>


int(7) ["lengths"]=> NULL ["num_rows"]=> int(0) ["type"]=> int(0) }

As you can see there is "num_rows" property, which would be equal to 1 if the
user with the email already existed in the database, that's how we find out if the
user exists by running the following if statement:

// We know user email exists if the rows returned are more than 0

if ( $result->num_rows > 0 ) {

$_SESSION['message'] = 'User with this email already exists!';

header("location: error.php");
}

Else...if the user doesn't exist, we proceed by first preparing the SQL insert
statement with all our previously set variables:

// active is 0 by DEFAULT (no need to include it here)

$sql = "INSERT INTO users (first_name, last_name, email, password, hash) "

. "VALUES ('$first_name','$last_name','$email','$password', '$hash')";

We then check if the mysql->query() is successful, if it is, we know the user has
been added to the database. Next we set some session variables to be used on the
profile.php page

$_SESSION['active'] = 0; //0 until user activates their account with verify.php

$_SESSION['logged_in'] = true; // So we know the user has logged in

$_SESSION['message'] =

"Confirmation link has been sent to $email, please verify

your account by clicking on the link in the message!";

We know the account won't be activated when a user first registers, so we can
safely set $_SESSION['active'] to zero. We set the session logged_in to true, so we
know the user has logged in and finally the message to display that the account
activation link has been sent.

The final step, is to send the user an email with the account activation link:

// Send registration confirmation link (verify.php)

$to = $email;

$subject = 'Account Verification ( clevertechie.com )';

$message_body = '

Hello '.$first_name.',
Thank you for signing up!

Please click this link to activate your account:

http://localhost/login-system/verify.php?email='.$email.'&hash='.$hash;

mail( $to, $subject, $message_body );

//redirect to profile.php page

header("location: profile.php");

The PHP mail() function takes in three parameters - $to (user email where to send
the message), $subject (email subject) and $message_body (the main body of the
email message).

The most important part of the verification message if the following URL which
sends a user to verify.php with email and hash variables: http://localhost/login-
system/verify.php?email='.$email.'&hash='.$hash;

By passing email=$email&hash=$hash variables in this way, we'll be able to


access them from verify.php from the $_GET global PHP varible and match the
user email with their unique hash, so we can verify their account. Let's take a look
at verify.php next:

/* Verifies registered user email, the link to this page

is included in the register.php email message

*/

require 'db.php';

session_start();

// Make sure email and hash variables aren't empty

if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !


empty($_GET['hash']))

{
$email = $mysqli->escape_string($_GET['email']);

$hash = $mysqli->escape_string($_GET['hash']);

// Select user with matching email and hash, who hasn't verified their account yet
(active = 0)

$result = $mysqli->query("SELECT * FROM users WHERE email='$email' AND


hash='$hash' AND active='0'");

if ( $result->num_rows == 0 )

$_SESSION['message'] = "Account has already been activated or the URL is


invalid!";

header("location: error.php");

else {

$_SESSION['message'] = "Your account has been activated!";

// Set the user status to active (active = 1)

$mysqli->query("UPDATE users SET active='1' WHERE email='$email'") or


die($mysqli->error);

$_SESSION['active'] = 1;

header("location: success.php");

else {

$_SESSION['message'] = "Invalid parameters provided for account verification!";


header("location: error.php");

We first make sure the variables that we passed in the verify.php URL (email and
hash) aren't empty and have values:

// Make sure email and hash variables aren't empty

if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !


empty($_GET['hash']))

We then escape $email and $hash variables as usual, to protect again SQL
injections. Then we run a mysqli query which selects user email and hash with
active status zero:

// Select user with matching email and hash, who hasn't verified their account yet
(active = 0)

$result = $mysqli->query("SELECT * FROM users WHERE email='$email' AND


hash='$hash' AND active='0'");

By selecting user email and their uniquely generated hash, we know the
appropriate user is verifying their own account. Next, we check if the num_rows
property is equal to zero, if it is we redirect to error.php page with an error
message, else we continue verifying the user

if ( $result->num_rows == 0 )

$_SESSION['message'] = "Account has already been activated or the URL is


invalid!";

header("location: error.php");

else {
$_SESSION['message'] = "Your account has been activated!";

If everything went well and the user has been found with matching email and hash,
we proceed to next MySQL statement which sets the value of user to 1 (active = 1)
WHERE email=$email. We also set the session 'active' variable to 1, so that the
"unverified account message" is removed from user's profile right away.

// Set the user status to active (active = 1)

$mysqli->query("UPDATE users SET active='1' WHERE email='$email'")

or die($mysqli->error);

$_SESSION['active'] = 1;

//show successful verification message

header("location: success.php");

This completes account registration and verification process, let's now move on to
the login.php part

/* User login process, checks if user exists and password is correct */

// Escape email to protect against SQL injections

$email = $mysqli->escape_string($_POST['email']);

$result = $mysqli->query("SELECT * FROM users WHERE email='$email'");

if ( $result->num_rows == 0 ){ // User doesn't exist

$_SESSION['message'] = "User with that email doesn't exist!";

header("location: error.php");

else { // User exists

$user = $result->fetch_assoc();
if ( password_verify($_POST['password'], $user['password']) ) {

$_SESSION['email'] = $user['email'];

$_SESSION['first_name'] = $user['first_name'];

$_SESSION['last_name'] = $user['last_name'];

$_SESSION['active'] = $user['active'];

// This is how we'll know the user is logged in

$_SESSION['logged_in'] = true;

header("location: profile.php");

else {

$_SESSION['message'] = "You have entered wrong password, try again!";

header("location: error.php");

The first step is to check if the user exists in the database with that email, so we run
a simple SQL query and select the user based on the email provided:

$result = $mysqli->query("SELECT * FROM users WHERE email='$email'");

if ( $result->num_rows == 0 ){ // User doesn't exist

$_SESSION['message'] = "User with that email doesn't exist!";

header("location: error.php");

}
If the user with provided email is found, we store the result in the $user array, if we
used print_r() function on $user array at this point, it would look something like
the following:

$user = $result->fetch_assoc();

print_r($user); die;

/*output

Array (

[id] => 1

[first_name] => Clever

[last_name] => Techie

[email] => shustikov@gmail.com

[password] =>
$2y$10$4UOoPPUJbqx.eK83UQTXY.KNrm1xepeBq0.Q4WbBlyPuDF8DdYwOa

[hash] => 54a367d629152b720749e187b3eaa11b

[active] => 1

*/

As you can see our user data is neatly organized and we can now access all of the
current user's data from the $user array

We then use PHP built-in function password_verify() to make sure the password
entered and the current user password which exists in the database match each
other:

if ( password_verify($_POST['password'], $user['password']) )

If the two passwords match, we log the user in, by setting session variables which
we'll need on the next page and redirect the user to profile.php welcome page
$_SESSION['email'] = $user['email'];

$_SESSION['first_name'] = $user['first_name'];

$_SESSION['last_name'] = $user['last_name'];

$_SESSION['active'] = $user['active'];

// This is how we'll know the user is logged in

$_SESSION['logged_in'] = true;

header("location: profile.php");

We have used all of our values from the $user array which we looked at previously
to set a lot of our session variables to display on the profile page. Also,
$_SESSION['logged_in'] is set to true so that we know the user is in fact logged in.
The login process is now complete. Finally, let's take a look at forgot.php to see
how password reset process works:

/* Reset your password form, sends reset.php password link */

require 'db.php';

session_start();

// Check if form submitted with method="post"

if ( $_SERVER['REQUEST_METHOD'] == 'POST' )

$email = $mysqli->escape_string($_POST['email']);

$result = $mysqli->query("SELECT * FROM users WHERE email='$email'");

if ( $result->num_rows == 0 ) // User doesn't exist

$_SESSION['message'] = "User with that email doesn't exist!";


header("location: error.php");

else { // User exists (num_rows != 0)

$user = $result->fetch_assoc(); // $user becomes array with user data

$email = $user['email'];

$hash = $user['hash'];

$first_name = $user['first_name'];

// Session message to display on success.php

$_SESSION['message'] = "";

Please check your email $email" . " for a confirmation link to complete your
password reset!

// Send registration confirmation link (reset.php)

$to = $email;

$subject = 'Password Reset Link ( clevertechie.com )';

$message_body = '

Hello '.$first_name.',

You have requested password reset!

Please click this link to reset your password:

http://localhost/login-system/reset.php?email='.$email.'&hash='.$hash;

mail($to, $subject, $message_body);

header("location: success.php");

}
}

The code should look familiar at this point. We first check if the form is being
submitted with POST method. We then check if the user exists by running a simple
SQL statement which selects user email, based on the email entered in the form. If
the user exists, we store data in the $user array. We also set the
$_SESSION['message'] which will display on success.php page. Finally, we send
the user a message which contains reset.php link with email and hash variables:

// Session message to display on success.php

$_SESSION['message'] = "";

Please check your email $email" . " for a confirmation link to complete your
password reset!

// Send registration confirmation link (reset.php)

$to = $email;

$subject = 'Password Reset Link ( clevertechie.com )';

$message_body = '

Hello '.$first_name.',

You have requested password reset!

Please click this link to reset your password:

http://localhost/login-system/reset.php?email='.$email.'&hash='.$hash;

mail($to, $subject, $message_body);

header("location: success.php");

When a user clicks on the URL with reset.php, they land on reset.php page with
their email and hash variables set, we're doing this in exactly the same way we
have verified account, so this should be a review. Let's now look at reset.php code:

/* The password reset form, the link to this page is included


from the forgot.php email message

*/

require 'db.php';

session_start();

// Make sure email and hash variables aren't empty

if( isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !


empty($_GET['hash']) )

$email = $mysqli->escape_string($_GET['email']);

$hash = $mysqli->escape_string($_GET['hash']);

// Make sure user email with matching hash exist

$result = $mysqli->query("SELECT * FROM users WHERE email='$email' AND


hash='$hash'");

if ( $result->num_rows == 0 )

$_SESSION['message'] = "You have entered invalid URL for password reset!";

header("location: error.php");

else {

$_SESSION['message'] = "Sorry, verification failed, try again!";

header("location: error.php");
}

There is nothing new in this code, so I'm not going to go over the details. However,
let's look at a couple of HTML lines of reset.php page, because there are a few
important things going on

<form action="reset_password.php" method="post">

As you can see we're calling another page called "reset_password.php" which will
complete the reset process. We need to do this because the current page already
checks for $_GET variables which are transferred differently then $_POST
variables which we'll need on the next page.

Also, the following two hidden input fields have been included, so we can access
user email and hash on the reset_password.php page. This let's us know which user
is resetting their password.

<!-- This input field is needed, to get the email of the user -->

<input type="hidden" name="email" value="<?= $email ?>">

<input type="hidden" name="hash" value="<?= $hash ?>">

Finally, let's examine "reset_password.php" which will conclude the password


reset process

/* Password reset process, updates database with new user password */

require 'db.php';

session_start();

// Make sure the form is being submitted with method="post"

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

// Make sure the two passwords match

if ( $_POST['newpassword'] == $_POST['confirmpassword'] ) {
$new_password = password_hash($_POST['newpassword'],
PASSWORD_BCRYPT);

// We get $_POST['email'] from the hidden input field of reset.php form

$email = $mysqli->escape_string($_POST['email']);

$hash = $mysqli->escape_string($_POST['hash']);

$sql = "UPDATE users SET password='$new_password' WHERE email='$email'


AND"

. "hash='$hash'";

if ( $mysqli->query($sql) ) {

$_SESSION['message'] = "Your password has been reset successfully!";

header("location: success.php");

else {

$_SESSION['message'] = "Two passwords you entered don't match, try again!";

header("location: error.php");

If the form is submitted with the post, we check to make sure the new password
and confirm password match, we then access the hidden input fields so we know
what email and hash to select

// We get $_POST['email'] and $_POST['hash'] from the hidden input field of


reset.php form

$email = $mysqli->escape_string($_POST['email']);
$hash = $mysqli->escape_string($_POST['hash']);

Lastly, we run the SQL query and update user password to new one and redirect
them to success.php page with the appropriate message

$sql = "UPDATE users SET password='$new_password' WHERE email='$email'


AND"

. "hash='$hash'";

if ( $mysqli->query($sql) ) {

$_SESSION['message'] = "Your password has been reset successfully!";

header("location: success.php");

You did it! This was a long tutorial and I hope you learned a lot from it, if at any
point you get confused, go back and look at the chart so you can see the big picture
of how everything is put together and where important things are happening.
Please post any questions, comments and concerns below.

Signup Login page in PHP with Database MySQL Source Code


By

Shehryar Khan

May 27, 2018

I have also written step by step Tutorial for Restful Web Services in PHP Example
– PHP + MySQL Best Practice. Today I’m going to connect login & Signup
Webservices using Login & Signup HTML page. You can use any HTML page,
I’m using This because it has a really beautiful design and has Form for both Login
& Signup.
What we’ll cover in Signup Login page in PHP with Database

1. File Structure
2. Creating HTML page
3. Connecting HTML page with Webservices

File Structure

We’ll use this folders & files structure inside our “app” folder for our Login &
Signup page.

index.html
 |
assets
├─── css
├────── style.css
api
├─── config/
├────── database.php – file used for connecting to the database.
├─── objects/
├────── user.php – contains properties and methods for “user” database
queries.
├─── User/
├────── signup.php – file that will accept user data to be saved to the DB.
├────── login.php – file that will accept username & password and validate

Recommended for you

as you can see that we have added pages and assets folders, pages folder will
contain all HTML pages and assets folder is for CSS, JS, images etc.

Creating HTML page

as I stated that you can create your own design or you can use any other design, for
this tutorial I’m using This template and I just modified it according to my
Webservices.

Get Complete Page HTML Code

inside your “app” folder, create a new file as “index.html” and paste this code there
1. <!DOCTYPE html>
2. <html lang="en" >
3.
4. <head>
5. <meta charset="UTF-8">
6. <title>PHP Learning</title>
7.
8.
9. <link rel='stylesheet prefetch' href='https://fonts.googleapis.com/css?
family=Open+Sans:600'>
10.
11.<link rel="stylesheet" href="./assets/css/style.css">
12.
13.
14.</head>
15.
16.<body>
17.
18.<div class="login-wrap">
19.<div class="login-html">
20.<input id="tab-1" type="radio" name="tab" class="sign-in" checked><label
for="tab-1" class="tab">Sign In</label>
21.<input id="tab-2" type="radio" name="tab" class="sign-up"><label
for="tab-2" class="tab">Sign Up</label>
22.<div class="login-form">
23.<form class="sign-in-htm" action="./api/user/login.php" method="GET">
24.<div class="group">
25.<label for="user" class="label">Username</label>
26.<input id="username" name="username" type="text" class="input">
27.</div>
28.<div class="group">
29.<label for="pass" class="label">Password</label>
30.<input id="password" name="password" type="password" class="input"
data-type="password">
31.</div>
32.<div class="group">
33.<input id="check" type="checkbox" class="check" checked>
34.<label for="check"><span class="icon"></span> Keep me Signed in</label>
35.</div>
36.<div class="group">
37.<input type="submit" class="button" value="Sign In">
38.</div>
39.<div class="hr"></div>
40.<div class="foot-lnk">
41.<a href="#forgot">Forgot Password?</a>
42.</div>
43.</form>
44.<form class="sign-up-htm" action="./api/user/signup.php"
method="POST">
45.<div class="group">
46.<label for="user" class="label">Username</label>
47.<input id="username" name="username" type="text" class="input">
48.</div>
49.<div class="group">
50.<label for="pass" class="label">Password</label>
51.<input id="password" name="password" type="password" class="input"
data-type="password">
52.</div>
53.<div class="group">
54.<label for="pass" class="label">Confirm Password</label>
55.<input id="pass" type="password" class="input" data-type="password">
56.</div>
57.<div class="group">
58.<input type="submit" class="button" value="Sign Up">
59.</div>
60.<div class="hr"></div>
61.<div class="foot-lnk">
62.<label for="tab-1">Already Member?</a>
63.</div>
64.</form>
65.</div>
66.</div>
67.</div>
68.
69.
70.
71.</body>
72.
73.</html>

Now go to the “assets” folder and create a new folder as “css” and create a new file
there as “style.css” and paste this code there

1. body{
2. margin:0;
3. color:#6a6f8c;
4. background:#c8c8c8;
5. font:600 16px/18px 'Open Sans',sans-serif;
6. }
7. *,:after,:before{box-sizing:border-box}
8. .clearfix:after,.clearfix:before{content:'';display:table}
9. .clearfix:after{clear:both;display:block}
10.a{color:inherit;text-decoration:none}
11.
12..login-wrap{
13.width:100%;
14.margin:auto;
15.margin-top: 30px;
16.max-width:525px;
17.min-height:570px;
18.position:relative;
19.background:url(http://codinginfinite.com/demo/images/bg.jpg) no-repeat
center;
20.box-shadow:0 12px 15px 0 rgba(0,0,0,.24),0 17px 50px 0 rgba(0,0,0,.19);
21.}
22..login-html{
23.width:100%;
24.height:100%;
25.position:absolute;
26.padding:90px 70px 50px 70px;
27.background:rgba(40,57,101,.9);
28.}
29..login-html .sign-in-htm,
30..login-html .sign-up-htm{
31.top:0;
32.left:0;
33.right:0;
34.bottom:0;
35.position:absolute;
36.-webkit-transform:rotateY(180deg);
37.transform:rotateY(180deg);
38.-webkit-backface-visibility:hidden;
39.backface-visibility:hidden;
40.transition:all .4s linear;
41.}
42..login-html .sign-in,
43..login-html .sign-up,
44..login-form .group .check{
45.display:none;
46.}
47..login-html .tab,
48..login-form .group .label,
49..login-form .group .button{
50.text-transform:uppercase;
51.}
52..login-html .tab{
53.font-size:22px;
54.margin-right:15px;
55.padding-bottom:5px;
56.margin:0 15px 10px 0;
57.display:inline-block;
58.border-bottom:2px solid transparent;
59.}
60..login-html .sign-in:checked + .tab,
61..login-html .sign-up:checked + .tab{
62.color:#fff;
63.border-color:#1161ee;
64.}
65..login-form{
66.min-height:345px;
67.position:relative;
68.-webkit-perspective:1000px;
69.perspective:1000px;
70.-webkit-transform-style:preserve-3d;
71.transform-style:preserve-3d;
72.}
73..login-form .group{
74.margin-bottom:15px;
75.}
76..login-form .group .label,
77..login-form .group .input,
78..login-form .group .button{
79.width:100%;
80.color:#fff;
81.display:block;
82.}
83..login-form .group .input,
84..login-form .group .button{
85.border:none;
86.padding:15px 20px;
87.border-radius:25px;
88.background:rgba(255,255,255,.1);
89.}
90..login-form .group input[data-type="password"]{
91.text-security:circle;
92.-webkit-text-security:circle;
93.}
94..login-form .group .label{
95.color:#aaa;
96.font-size:12px;
97.}
98..login-form .group .button{
99.background:#1161ee;
100. }
101. .login-form .group label .icon{
102. width:15px;
103. height:15px;
104. border-radius:2px;
105. position:relative;
106. display:inline-block;
107. background:rgba(255,255,255,.1);
108. }
109. .login-form .group label .icon:before,
110. .login-form .group label .icon:after{
111. content:'';
112. width:10px;
113. height:2px;
114. background:#fff;
115. position:absolute;
116. transition:all .2s ease-in-out 0s;
117. }
118. .login-form .group label .icon:before{
119. left:3px;
120. width:5px;
121. bottom:6px;
122. -webkit-transform:scale(0) rotate(0);
123. transform:scale(0) rotate(0);
124. }
125. .login-form .group label .icon:after{
126. top:6px;
127. right:0;
128. -webkit-transform:scale(0) rotate(0);
129. transform:scale(0) rotate(0);
130. }
131. .login-form .group .check:checked + label{
132. color:#fff;
133. }
134. .login-form .group .check:checked + label .icon{
135. background:#1161ee;
136. }
137. .login-form .group .check:checked + label .icon:before{
138. -webkit-transform:scale(1) rotate(45deg);
139. transform:scale(1) rotate(45deg);
140. }
141. .login-form .group .check:checked + label .icon:after{
142. -webkit-transform:scale(1) rotate(-45deg);
143. transform:scale(1) rotate(-45deg);
144. }
145. .login-html .sign-in:checked + .tab + .sign-up + .tab + .login-form
.sign-in-htm{
146. -webkit-transform:rotate(0);
147. transform:rotate(0);
148. }
149. .login-html .sign-up:checked + .tab + .login-form .sign-up-htm{
150. -webkit-transform:rotate(0);
151. transform:rotate(0);
152. }
153.
154. .hr{
155. height:2px;
156. margin:60px 0 50px 0;
157. background:rgba(255,255,255,.2);
158. }
159. .foot-lnk{
160. text-align:center;
161. }

Now you’ll see the page same as this


Connecting HTML page with Webservices

Download Login & Signup API from Github you can also create these API
following my previous post, Restful Web Services in PHP Example – PHP +
MySQL Best Practice

setup Database and paste “api” folder inside “app” folder.

all done, Now you can run your index.html through localhost.

You might also like