PHP 5 Introduction
PHP 5 Introduction
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.
PHP Advantages
There are, of course, many advantages to using PHP overall as well. Here are a few
to name:
Contents
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.
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
3. Comments in PHP
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.
<?php
// Here is PHP code
?>
".php" is the default PHP file extension.
Example
<!DOCTYPE html>
<html>
<body>
Comments in PHP
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.
Example
<!DOCTYPE html>
<html>
<body>
<?php
// 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>
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>
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
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; ?>
Output
Example
<?php $txt = "learn.xyz"; echo "I want to visit
$txt!";?>
Unlike PHP, different languages like Java, C and C++ also require to declare the
variable type.
Scope
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();
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();
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
?>
Example
<?php
$x = 20;
$y = 10;
function learnTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
learnTest();
echo $y; // outputs 30
?>
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();
?>
Contents
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.
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!";
?>
Example
<?php
$text1 = "I am ";
$text2 = "Ready!";
$var1 = 4;
$var2 = 3;
echo "<h2>" . $text1 . $text2 . "</h2>";
echo $var1 + $var2;
?>
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!";
?>
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 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;?>
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.
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);
?>
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);
?>
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.";
}
PHP Arrays
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);
?>
PHP Objects
An object is a data type that can store data and info for how the data can be
processed.
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;
?>
This is a special type of data, which can only have a single value: NULL.
Example
<?php
$txt = "Hello world!";
$txt = null;
var_dump($txt);
?>
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.
<?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
?>
<option value=" <?php echo $result['country_name']; ?>
"> <?php echo $result['country_name'];?> </option>
</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);
}
?>
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.
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:
);
//connection variables
$host = 'localhost';
$user = '';
$password = '';
if ($mysqli->connect_errno) {
die();
$mysqli->query('
CREATE TABLE `accounts`.`users`
);') 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
$host = 'localhost';
$user = 'root';
$pass = 'mypass123';
$db = 'accounts';
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.
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
</head>
<body>
<div class="form">
<h1>Error</h1>
<p>
<?php
echo $_SESSION['message'];
else:
endif;
?>
</p>
</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
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')
require 'login.php';
require 'register.php';
?>
<body>
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
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.
*/
$_SESSION['email'] = $_POST['email'];
$_SESSION['first_name'] = $_POST['firstname'];
$_SESSION['last_name'] = $_POST['lastname'];
$first_name = $mysqli->escape_string($_POST['firstname']);
$last_name = $mysqli->escape_string($_POST['lastname']);
$email = $mysqli->escape_string($_POST['email']);
// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {
header("location: error.php");
$sql = "INSERT INTO users (first_name, last_name, email, password, hash) "
if ( $mysqli->query($sql) ){
$_SESSION['message'] =
$to = $email;
$message_body = '
Hello '.$first_name.',
http://localhost/login-system/verify.php?email='.$email.'&hash='.$hash;
header("location: profile.php");
else {
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:
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:
echo $password;
//output:
$2y$10$PXzvWecpHeXEW.CremYvreh2/4rDdCIlGFsNtxQbigAcCC4HgtbuW
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 );
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 ) {
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:
$sql = "INSERT INTO users (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['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:
$to = $email;
$message_body = '
Hello '.$first_name.',
Thank you for signing up!
http://localhost/login-system/verify.php?email='.$email.'&hash='.$hash;
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;
*/
require 'db.php';
session_start();
{
$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)
if ( $result->num_rows == 0 )
header("location: error.php");
else {
$_SESSION['active'] = 1;
header("location: success.php");
else {
We first make sure the variables that we passed in the verify.php URL (email and
hash) aren't empty and have values:
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)
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 )
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.
or die($mysqli->error);
$_SESSION['active'] = 1;
header("location: success.php");
This completes account registration and verification process, let's now move on to
the login.php part
$email = $mysqli->escape_string($_POST['email']);
header("location: error.php");
$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'];
$_SESSION['logged_in'] = true;
header("location: profile.php");
else {
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:
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
[password] =>
$2y$10$4UOoPPUJbqx.eK83UQTXY.KNrm1xepeBq0.Q4WbBlyPuDF8DdYwOa
[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'];
$_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:
require 'db.php';
session_start();
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
$email = $mysqli->escape_string($_POST['email']);
$email = $user['email'];
$hash = $user['hash'];
$first_name = $user['first_name'];
$_SESSION['message'] = "";
Please check your email $email" . " for a confirmation link to complete your
password reset!
$to = $email;
$message_body = '
Hello '.$first_name.',
http://localhost/login-system/reset.php?email='.$email.'&hash='.$hash;
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'] = "";
Please check your email $email" . " for a confirmation link to complete your
password reset!
$to = $email;
$message_body = '
Hello '.$first_name.',
http://localhost/login-system/reset.php?email='.$email.'&hash='.$hash;
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:
*/
require 'db.php';
session_start();
$email = $mysqli->escape_string($_GET['email']);
$hash = $mysqli->escape_string($_GET['hash']);
if ( $result->num_rows == 0 )
header("location: error.php");
else {
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
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 -->
require 'db.php';
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ( $_POST['newpassword'] == $_POST['confirmpassword'] ) {
$new_password = password_hash($_POST['newpassword'],
PASSWORD_BCRYPT);
$email = $mysqli->escape_string($_POST['email']);
$hash = $mysqli->escape_string($_POST['hash']);
. "hash='$hash'";
if ( $mysqli->query($sql) ) {
header("location: success.php");
else {
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
$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
. "hash='$hash'";
if ( $mysqli->query($sql) ) {
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.
Shehryar Khan
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
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.
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.
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. }
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
all done, Now you can run your index.html through localhost.