You are on page 1of 68

PHP User Authentication with MySQL

In this tutorial, we are going to see how to implement user authentication


mechanism in PHP using MySQL. Authentication is used validate users
entering into our website. It protects our website by preventing anonymous
access and allows genuine users who clear authentication process.

In this user authentication example, it has a login panel to let users enter
their login details. On submitting login details to a PHP page, it compares
the submitted data with the user database table. If there is a match found
in the user database for the user who attempts login then he will be
considered as an authenticated user and allowed to enter into our website.

Steps to create user authentication system in PHP.

1. Create MySQL database with users table.


2. Create user login panel to submit login details to PHP.
3. Generate query to compare user login details with the MySQL user
database.
Create MySQL Database with Users Table.
Create a new database using MySQL query or by using any database client
like SQLYog, PHPMyAdmin and etc. In this example, I created a database
named as payload and the table name is users. The table fields are shown in
the figure below.

Create User Login Panel.


The following HTML code is used to show user login panel to enter
authentication details. It has two input fields for entering username and
password. On submitting this form these two field values will be posted to
PHP.

<form name="frmUser" method="post" action="">

<div class="message"><?php if($message!="") { echo


$message; } ?></div>

<table border="0" cellpadding="10"


cellspacing="1" width="500" align="center" class="tblLogin">

<tr class="tableheader">

<td align="center" colspan="2">Enter Login


Details</td>

</tr>
<tr class="tablerow">

<td>

<input type="text" name="userName"


placeholder="User Name" class="login-input"></td>

</tr>

<tr class="tablerow">

<td>

<input type="password" name="password"


placeholder="Password" class="login-input"></td>

</tr>

<tr class="tableheader">

<td align="center" colspan="2"><input


type="submit" name="submit" value="Submit"
class="btnSubmit"></td>

</tr>

</table>

</form>

And the CSS is,

body{

font-family: calibri;

.tblLogin {

border: #95bee6 1px solid;

background: #d1e8ff;

border-radius: 4px;
}

.tableheader { font-size: 24px; }

.tableheader td { padding: 20px; }

.tablerow td { text-align:center; }

.message {

color: #FF0000;

font-weight: bold;

text-align: center;

width: 100%;

.login-input {

border: #CCC 1px solid;

padding: 10px 20px;

.btnSubmit {

padding: 10px 20px;

background: #2c7ac5;

border: #d1e8ff 1px solid;

color: #FFF;

The HTML code and styles above with display the authentication form to
the user like,
Generate Query to Compare User Input with the
Database.
After receiving user authentication details in PHP, it compares the form
data with the using database by executing a query. The following PHP code
connects MySQL database and checks if the user authentication
information submitted via the form is correct. Based on the result of the
authentication process, it stores acknowledgment message to be shown to
the user at the end of authentication.

<?php

$message="";

if(count($_POST)>0) {

$conn =
mysqli_connect("localhost","root","","phppot_examples");

$result = mysqli_query($conn,"SELECT * FROM users


WHERE user_name='" . $_POST["userName"] . "' and password =
'". $_POST["password"]."'");

$count = mysqli_num_rows($result);

if($count==0) {

$message = "Invalid Username or Password!";


} else {

$message = "You are successfully


authenticated!";

?>

download

This PHP code tutorial was published on May 7, 2013.

PHP Login Script with Session


In this tutorial, let us see how we can implement authentication using a


standard login form with session handling. Most of the website will have
login script to provide user authentication. I will present you an example
PHP code to implement authentication using a login script. With
authentication, we can protect our website by filtering genuine users.

There are different ways to implement authentication and the most popular
way is to using the login form and authenticate based on a username and
respective password. Recently authentication using dynamically generated
OTP is also becoming a norm and we will see about it in a coming tutorial.

In this tutorial, we are storing authentication credentials in a database. We


will show a login form to enter login credentials. We compare the entered
data against the user database. If match found, then the user is considered
as authenticated. We use PHP session to preserve the logged-in state of the
authenticated users. In previous tutorials, we have already seen about login
via form submit and also via AJAX call.

PHP Login Sessions


We let the user submit their login credentials on a form and compare it
with the users database. If a match is found, then we authenticate the
user and store their logged in status by using the $_SESSION super
global. For example, $_SESSION[member_id],
$_SESSION[display_name]. This logged-in status will be preserved until
the user logout. Once the user clicked the logout link, we clear his session
by using PHP unset().

User Login Interface


First, we need to create login interface to allow the user to submit
authentication information. It shows the username and password input
fields in a form. On submitting this form, we post the values to PHP. The
HTML and CSS code is as follows.

<form action="" method="post" id="frmLogin">


<div class="error-message"><?php if(isset($message)) {
echo $message; } ?></div>

<div class="field-group">

<div><label for="login">Username</label></div>

<div><input name="user_name" type="text"


class="input-field"></div>

</div>

<div class="field-group">

<div><label
for="password">Password</label></div>

<div><input name="password" type="password"


class="input-field"> </div>

</div>

<div class="field-group">

<div><input type="submit" name="login"


value="Login" class="form-submit-button"></span></div>

</div>

</form>

and the styles are,

#frmLogin {

padding: 20px 60px;

background: #B6E0FF;

color: #555;

display: inline-block;

border-radius: 4px;

}
.field-group {

margin:15px 0px;

.input-field {

padding: 8px;width: 200px;

border: #A3C3E7 1px solid;

border-radius: 4px;

.form-submit-button {

background: #65C370;

border: 0;

padding: 8px 20px;

border-radius: 4px;

color: #FFF;

text-transform: uppercase;

.member-dashboard {

padding: 40px;

background: #D2EDD5;

color: #555;

border-radius: 4px;

display: inline-block;

text-align:center;

}
.logout-button {

color: #09F;

text-decoration: none;

background: none;

border: none;

padding: 0px;

cursor: pointer;

.error-message {

text-align:center;

color:#FF0000;

.demo-content label{

width:auto;

PHP Login Script


We receive login form data in a PHP page as the post requests. In this
script, we generate a SELECT query to validate user data with the database.
If the user is authenticated successfully, then we add user logged-in status
in a session and show a success message with the logout option to the
user. The PHP login script is,

<?php

session_start();

$conn =
mysqli_connect("localhost","root","","phppot_examples");
$message="";

if(!empty($_POST["login"])) {

$result = mysqli_query($conn,"SELECT * FROM users


WHERE user_name='" . $_POST["user_name"] . "' and password =
'". $_POST["password"]."'");

$row = mysqli_fetch_array($result);

if(is_array($row)) {

$_SESSION["user_id"] = $row['user_id'];

} else {

$message = "Invalid Username or Password!";

?>

We can add this code on the same page above the HTML content or we
can save it as an individual PHP file like login.php and add it to form action.

The code to show success message to the user is in the else part and the
code is,

<?php

} else {

$result = mysqlI_query($conn,"SELECT * FROM users WHERE


user_id='" . $_SESSION["phppot_demopage_459_user_id"] .
"'");

$row = mysqli_fetch_array($result);

?>

<form action="" method="post" id="frmLogout">


<div class="member-dashboard">Welcome <?php echo
ucwords($row['display_name']); ?>, You have successfully
logged in!<br>

Click to <input type="submit" name="logout" value="Logout"


class="logout-button">.</div>

</form>

</div>

</div>

<?php } ?>

The welcome message will be displayed with the logged in user by their
name and a link to logout to clear user login session.

And the code to logout is,

<?php

if(!empty($_POST["logout"])) {

$_SESSION["user_id"] = "";

session_destroy();

?>

download

PHP Login with OTP Authentication


Login with an OTP code is a secure method for the user authentication
process. In this method, a one-time password is generated dynamically and
sent to the user who attempts login. OTP can be sent to the users email or
his mobile phone. When the user enters the OTP code then the application
will authenticate the user via this code.

In this tutorial, we are going to see an example to authenticate user login


via an OTP code using email. In a previous tutorial, we have already seen a
PHP code for login with username and password. In this example, when the
registered user enters email to login, an OTP code is sent to the email
address. Using this OTP code the user will be validated. Once the user uses
this code then it will be invalid, meaning it cannot be used again. Also, this
token will be valid for a day, then it will be expired.
Login form with OTP
The following code shows login form to the user to enter his email address.
On entering email, it shows an input to enter the OTP code sent to his
email address. After submitting OTP, PHP will validate the code and show
authentication result to the user.

<form name="frmUser" method="post" action="">

<div class="tblLogin">

<?php

if(!empty($success == 1)) {

?>

<div class="tableheader">Enter OTP</div>

<p style="color:#31ab00;">Check your email for


the OTP</p>

<div class="tablerow">

<input type="text" name="otp"


placeholder="One Time Password" class="login-input"
required>

</div>

<div class="tableheader"><input type="submit"


name="submit_otp" value="Submit" class="btnSubmit"></div>

<?php

} else if ($success == 2) {

?>

<p style="color:#31ab00;">Welcome, You have


successfully loggedin!</p>

<?php
}

else {

?>

<div class="tableheader">Enter Your Login


Email</div>

<div class="tablerow"><input type="text"


name="email" placeholder="Email" class="login-input"
required></div>

<div class="tableheader"><input type="submit"


name="submit_email" value="Submit" class="btnSubmit"></div>

<?php

?>

</div>

</form>

PHP Code to Validate OTP Authentication


On submitting the email address, PHP script validates the user by checking
the user database whether it is registered email. If so, a 6 digit OTP code is
generated dynamically by using the PHP rand() function. You may choose
to substitute this random code generation logic using your preferred
mechanism. This code is sent to the users email by using PHPmailer.
When the user submits the OTP code to PHP, it validates the code by
checking its expiration. The code is valid for one day and it will be expired
once it is used. The PHP code is,

<?php

$success = "";

$error_message = "";

$conn =
mysqli_connect("localhost","root","","blog_samples");

if(!empty($_POST["submit_email"])) {

$result = mysqli_query($conn,"SELECT * FROM


registered_users WHERE email='" . $_POST["email"] . "'");

$count = mysqli_num_rows($result);

if($count>0) {

// generate OTP

$otp = rand(100000,999999);

// Send OTP

require_once("mail_function.php");
$mail_status = sendOTP($_POST["email"],$otp);

if($mail_status == 1) {

$result = mysqli_query($conn,"INSERT INTO


otp_expiry(otp,is_expired,create_at) VALUES ('" . $otp . "',
0, '" . date("Y-m-d H:i:s"). "')");

$current_id = mysqli_insert_id($conn);

if(!empty($current_id)) {

$success=1;

} else {

$error_message = "Email not exists!";

if(!empty($_POST["submit_otp"])) {

$result = mysqli_query($conn,"SELECT * FROM otp_expiry


WHERE otp='" . $_POST["otp"] . "' AND is_expired!=1 AND
NOW() <= DATE_ADD(create_at, INTERVAL 24 HOUR)");

$count = mysqli_num_rows($result);

if(!empty($count)) {

$result = mysqli_query($conn,"UPDATE otp_expiry


SET is_expired = 1 WHERE otp = '" . $_POST["otp"] . "'");

$success = 2;

} else {

$success =1;
$error_message = "Invalid OTP!";

?>

download

PHP Change Password Script


Change password feature in a web application is to let the user change


their old password at some periodic interval. It makes the user protect the
sensitive pages from hackers.

Some web application fixes some expiration period for users password. It
forces the user to change the password once the expiration period is
elapsed. For example, some banking applications force users to change the
password for security.

We are going to see an example to change the password with Javascript


validation by, accessing MySQL table.
HTML Code for Change Password Form
This HTML code shows the change password.

<html>

<head>

<title>Change Password</title>

<link rel="stylesheet" type="text/css" href="styles.css" />

</head>

<body>

<form name="frmChange" method="post" action=""


onSubmit="return validatePassword()">

<div style="width:500px;">

<div class="message"><?php if(isset($message)) { echo


$message; } ?></div>

<table border="0" cellpadding="10" cellspacing="0"


width="500" align="center" class="tblSaveForm">

<tr class="tableheader">

<td colspan="2">Change Password</td>

</tr>

<tr>

<td width="40%"><label>Current Password</label></td>


<td width="60%"><input type="password"
name="currentPassword" class="txtField"/><span
id="currentPassword" class="required"></span></td>

</tr>

<tr>

<td><label>New Password</label></td>

<td><input type="password" name="newPassword"


class="txtField"/><span id="newPassword"
class="required"></span></td>

</tr>

<td><label>Confirm Password</label></td>

<td><input type="password" name="confirmPassword"


class="txtField"/><span id="confirmPassword"
class="required"></span></td>

</tr>

<tr>

<td colspan="2"><input type="submit" name="submit"


value="Submit" class="btnSubmit"></td>

</tr>

</table>

</div>

</form>

</body></html>

All the fields are mandatory and the newPassword and confirmPassword
should be same. We are using Javascript validation. The validation function
is,

<script>
function validatePassword() {

var currentPassword,newPassword,confirmPassword,output =
true;

currentPassword = document.frmChange.currentPassword;

newPassword = document.frmChange.newPassword;

confirmPassword = document.frmChange.confirmPassword;

if(!currentPassword.value) {

currentPassword.focus();

document.getElementById("currentPassword").innerHTML =
"required";

output = false;

else if(!newPassword.value) {

newPassword.focus();

document.getElementById("newPassword").innerHTML =
"required";

output = false;

else if(!confirmPassword.value) {

confirmPassword.focus();

document.getElementById("confirmPassword").innerHTML =
"required";

output = false;
}

if(newPassword.value != confirmPassword.value) {

newPassword.value="";

confirmPassword.value="";

newPassword.focus();

document.getElementById("confirmPassword").innerHTML = "not
same";

output = false;

return output;

</script>

PHP Change Password Script


After successful form submits, the PHP code will access MySQL to get
current password. If this database value is matched with the forms current
password value, then the password will be changed. The PHP code is,

<?php

$_SESSION["userId"] = "24";

$conn = mysql_connect("localhost","root","");

mysql_select_db("phppot_examples",$conn);

if(count($_POST)>0) {

$result = mysql_query("SELECT *from users WHERE userId='" .


$_SESSION["userId"] . "'");

$row=mysql_fetch_array($result);

if($_POST["currentPassword"] == $row["password"]) {
mysql_query("UPDATE users set password='" .
$_POST["newPassword"] . "' WHERE userId='" .
$_SESSION["userId"] . "'");

$message = "Password Changed";

} else $message = "Current Password is not correct";

?>

download

PHP Forgot Password Recover Code


In this post, we are going to see an example to learn how to recover the
forgot password. In this example we have a forgot password form to get
the username or email to recover the password. After form submits, we are
sending password recovery email to the user.

The Password recovery email has a link to the page where we can reset the
password. In a previous post, we have seen how to change password.
Forgot Password Code
This HTML code shows the forgot password form.

<form name="frmForgot" id="frmForgot" method="post"


onSubmit="return validate_forgot();">

<h1>Forgot Password?</h1>

<?php if(!empty($success_message)) { ?>

<div class="success_message"><?php echo


$success_message; ?></div>

<?php } ?>

<div id="validation-message">

<?php if(!empty($error_message)) { ?>

<?php echo $error_message; ?>

<?php } ?>

</div>

<div class="field-group">
<div><label
for="username">Username</label></div>

<div><input type="text" name="user-login-name"


id="user-login-name" class="input-field"> Or</div>

</div>

<div class="field-group">

<div><label for="email">Email</label></div>

<div><input type="text" name="user-email"


id="user-email" class="input-field"></div>

</div>

<div class="field-group">

<div><input type="submit" name="forgot-password"


id="forgot-password" value="Submit" class="form-submit-
button"></div>

</div>

</form>

Once this form is submitted, then the PHP code get the user details from
the database.

<?php

if(!empty($_POST["forgot-password"])){

$conn = mysqli_connect("localhost", "root", "",


"blog_samples");

$condition = "";
if(!empty($_POST["user-login-name"]))

$condition = " member_name = '" .


$_POST["user-login-name"] . "'";

if(!empty($_POST["user-email"])) {

if(!empty($condition)) {

$condition = " and ";

$condition = " member_email = '" .


$_POST["user-email"] . "'";

if(!empty($condition)) {

$condition = " where " . $condition;

$sql = "Select * from members " . $condition;

$result = mysqli_query($conn,$sql);

$user = mysqli_fetch_array($result);

if(!empty($user)) {

require_once("forgot-password-recovery-
mail.php");

} else {

$error_message = 'No User Found';

}
}

?>

Forgot Password Mail Sending script


If the user information is found in the database, then the password recovery
mail sending script will be executed. We are using phpmailer for sending
email. The mail script is,

<?php

if(!class_exists('PHPMailer')) {

require('phpmailer/class.phpmailer.php');

require('phpmailer/class.smtp.php');

require_once("mail_configuration.php");

$mail = new PHPMailer();

$emailBody = "<div>" . $user["member_name"] .


",<br><br><p>Click this link to recover your password<br><a
href='" . PROJECT_HOME . "php-forgot-password-recover-
code/reset_password.php?name=" . $user["member_name"] . "'>"
. PROJECT_HOME . "php-forgot-password-recover-
code/reset_password.php?name=" . $user["member_name"] .
"</a><br><br></p>Regards,<br> Admin.</div>";

$mail->IsSMTP();

$mail->SMTPDebug = 0;

$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "tls";

$mail->Port = PORT;

$mail->Username = MAIL_USERNAME;

$mail->Password = MAIL_PASSWORD;

$mail->Host = MAIL_HOST;

$mail->Mailer = MAILER;

$mail->SetFrom(SERDER_EMAIL, SENDER_NAME);

$mail->AddReplyTo(SERDER_EMAIL, SENDER_NAME);

$mail->ReturnPath=SERDER_EMAIL;

$mail->AddAddress($user["member_email"]);

$mail->Subject = "Forgot Password Recovery";

$mail->MsgHTML($emailBody);

$mail->IsHTML(true);

if(!$mail->Send()) {

$error_message = 'Problem in Sending Password Recovery


Email';

} else {

$success_message = 'Please check your email to reset


password!';

?>
Note:

<?php

define("PROJECT_HOME","http://localhost/phpsamples/");

define("PORT", ""); // port number

define("MAIL_USERNAME", ""); // smtp usernmae

define("MAIL_PASSWORD", ""); // smtp password

define("MAIL_HOST", ""); // smtp host

define("MAILER", "smtp");

define("SENDER_NAME", "Admin");

define("SERDER_EMAIL", "admin@admin.com");

?>

download

Send Email in PHP using Gmail SMTP


In this tutorial, let us see how to send email in PHP using PHPMailer library
via Gmail SMTP. Sending email in PHP can be done with various mail
transfer libraries available. For example, PHPMailer, PEAR::Mail interface.
These libraries provide advanced features like SMTP authentication and
more.

Sending an email with PHPs core function mail() is simpler. This function is
too simple and lacks advanced features for sending an email. For example,
we cannot send attachments using PHPs mail().

In this tutorial, lets use PHPMailer class for sending emails by using Gmail
SMTP server. This library is popular because of its advanced features. Some
of those features are,

Allows both plain text and HTML content as email body.


Allows array of email addresses for to|cc|bcc|reply-to.
It provides Secure/MIME encryption.
It supports various encoding techniques binary, base64 and etc.
It has multiple language support (English by default).
It provides email validation, SMTP authentication, word wrapping and
more.

PHP Script for Sending Email using Gmail SMTP


For sending email using SMTP we need not have entire PHPMailer library. It
is sufficient to have only class.phpmailer.php and class.smtp.php of this
library.

We should set subject, content and header information. When we send


email using Gmail SMTP make sure to set SMTPAuth as TRUE and
SMTPSecure as tls/ssl. Use your Gmail Username and Password to send an
email.
<?php

require('phpmailer/class.phpmailer.php');

$mail = new PHPMailer();

$mail->IsSMTP();

$mail->SMTPDebug = 0;

$mail->SMTPAuth = TRUE;

$mail->SMTPSecure = "tls";

$mail->Port = 587;

$mail->Username = "your gmail username";

$mail->Password = "your gmail password";

$mail->Host = "smtp.gmail.com";

$mail->Mailer = "smtp";

$mail->SetFrom("Your from email", "from name");

$mail->AddReplyTo("from email", "PHPPot");

$mail->AddAddress("recipient email");

$mail->Subject = "Test email using PHP mailer";

$mail->WordWrap = 80;

$content = "<b>This is a test email using PHP mailer


class.</b>"; $mail->MsgHTML($content);

$mail->IsHTML(true);

if(!$mail->Send())

echo "Problem sending email.";

else

echo "email sent.";


?>

For setting FromEmail and FromName, we can either use SetFrom() function
or use PHPMailer properties PHPMailer::From and PHPMailer::FromName.
For example,

$mail->From = "from email address";

$mail->FromName = "from name";

AddReplyTo(), AddAddress() functions will accept array of email addresses,


and name is optional.

If we have HTML content as mail body, we need to set content


body text/HTML by using,

$mail->IsHTML(true);

After setting all properties and mailer information with the PHPMailer
object, PHPMailer::send() function returns TRUE on successful mail transfer
and FALSE on failure.

Download Email Script using GMAIL SMTP

This PHP code tutorial was published on December 5, 2013.

PHP Mail

PHP provides mail() function for sending simple mail using PHP scripts. For
that, the mail() function requires three arguments compulsorily and also
two optional arguments, so totally five possible arguments as shown below.

Recipient Email Address (Mandatory).


Email Subject (Mandatory)
Email Context or Message Body (Mandatory)
Additional Header Information (Optional)
Additional Parameters (Optional)

First three arguments are obvious and more clear about their purpose.
aHeader and Additional Parameters are needed to set values like From
Addressto avoid error while sending an mail. This From Address is by default
set with php.ini file. But in some rare cases of having custom php.ini file and
no value is set for From Address, at that time Additional Parameters of this
mail() function is used. And then, Additional Header argument that includes
more header information like CC, BCC and etc.

Note: Not only FromAddress as sendmail_from, php.ini also holds set of


other mail related settings like smtp, smtp_port, sendmail_path and etc.

Example: PHP mail()


The following PHP program is for sending simple mail using PHP mail
function. It starts with the initialization of mail() functions five parameters
discussed above. For additional headers, CC and BCC are specified with
email addresses for which copy of this email content will be sent. And,
finally From Address is set as an additional parameter.
All the arguments are used for the PHP mail() function in the following
program. This function will return boolean value TRUE, if the mail is
accepted for delivery and print success message to the browser . Otherwise,
it returns false with failure notice.

<?php

$recipientEmail = "Enter Recipient Email Here!";

$emailSubject = "PHP Mailing Function";

$emailContext = "Sending content using PHP mail function";

$emailHeaders = "Cc: Replace email address" . "\r\n";

$emailHeaders .= "Bcc: Replace email address" . "\r\n";

$fromAddress = "-fpostmaster@localhost";

$emailStatus = mail($recipientEmail, $emailSubject,


$emailContext, $emailHeaders, $fromAddress);

if($emailStatus) {

echo "EMail Sent Successfully!";

} else {

echo "No Email is sent";

?>

But this mail() function is not efficient method to send email using PHP
program. Because, we can not transfer bulk data using this function. And
also, it has poor performance on sending email to more than one recipient
and not secure enough. To send email for each recipient, PHP mail()
function attempts to open the SMTP socket every time which leads poor
performance. To get rid of such inconvenience with this function, we can
better go with other alternative email packages, for example PEAR::Mail
package.

This PHP code tutorial was published on June 4, 2013.

PHP Login Script with Remember Me


In a login script, remember me feature is used to preserve the login name


and password entered by the user. And it can be populated in the login
form at the time of login. It minimizes the user effort by preventing to enter
login details for each time.

Some days before, we have seen PHP login script with session. Now we are
going to see an example for login script with remember me feature. In this
example, we are using PHP cookies for preserving user login and password.
PHP Login Form
This code shows login form with the PHP code to pre-populate user login
and password. This form has a remember me check box. If it is set then the
login details entered by the user will be preserved for future login attempts.

<form action="" method="post" id="frmLogin">

<div class="error-message"><?php if(isset($message)) {


echo $message; } ?></div>

<div class="field-group">

<div><label for="login">Username</label></div>

<div><input name="member_name" type="text"


value="<?php if(isset($_COOKIE["member_login"])) { echo
$_COOKIE["member_login"]; } ?>" class="input-field">

</div>

<div class="field-group">

<div><label
for="password">Password</label></div>

<div><input name="member_password"
type="password" value="<?php
if(isset($_COOKIE["member_password"])) { echo
$_COOKIE["member_password"]; } ?>" class="input-field">
</div>

<div class="field-group">

<div><input type="checkbox" name="remember"


id="remember" <?php if(isset($_COOKIE["member_login"])) { ?>
checked <?php } ?> />

<label for="remember-me">Remember me</label>

</div>

<div class="field-group">

<div><input type="submit" name="login"


value="Login" class="form-submit-button"></span></div>

</div>

</form>

PHP Cookie to Remember Login


This PHP code validates the login details entered by the user while
submitting the form. And it checks whether the remember me is checked. If
so, it stores the user login and password in PHP $_COOKIE array. If these
array variables are not empty then it will be populated in the login form
fields.

<?php

session_start();

if(!empty($_POST["login"])) {

$conn = mysqli_connect("localhost", "root", "",


"blog_samples");

$sql = "Select * from members where member_name = '" .


$_POST["member_name"] . "' and member_password = '" .
md5($_POST["member_password"]) . "'";

$result = mysqli_query($conn,$sql);
$user = mysqli_fetch_array($result);

if($user) {

$_SESSION["member_id"] =
$user["member_id"];

if(!empty($_POST["remember"])) {

setcookie
("member_login",$_POST["member_name"],time()+ (10 * 365 * 24
* 60 * 60));

setcookie
("member_password",$_POST["member_password"],time()+ (10 *
365 * 24 * 60 * 60));

} else {

if(isset($_COOKIE["member_login"]))
{

setcookie
("member_login","");

if(isset($_COOKIE["member_password"])) {

setcookie
("member_password","");

} else {

$message = "Invalid Login";

}
?>

download

This PHP code tutorial was published on March 23, 2016.

Show PHP Captcha on Failed Login


Attempts

In this tutorial, we are going to show captcha code if a user tried more than
3 failed login attempts. In the previous tutorial, we have seen user
login and PHP captcha. So, we are going to combine this two tutorial to
add captcha control for invalid login.

In this example, we have a MySQL table to add failed login entries. We are
calculating a number of failed attempts based on the client IP Address. If
this count exceeds 3, then the captcha code will be displayed to the user.

download
HTML Code for Login with Captcha
This code contains login form with the captcha code. The captcha code will
be displayed when the user tried more than 3 invalid attempts.

<form name="frmUser" method="post" action="">

<div class="message"><?php if($message!="") { echo


$message; } ?></div>

<table border="0" cellpadding="10"


cellspacing="1" width="500" align="center">

<tr class="tableheader">

<td align="center" colspan="2">Enter Login


Details</td>

</tr>

<tr class="tablerow">

<td align="right">Username</td>

<td><input type="text" name="user_name"></td>

</tr>

<tr class="tablerow">
<td align="right">Password</td>

<td><input type="password" name="password"></td>

</tr>

<?php if (isset($failed_login_attempt) &&


$failed_login_attempt >= 3) { ?>

<tr class="tablerow">

<td align="right"></td>

<td><input name="captcha_code"
type="text"><br><br><img src="captcha_code.php" /></td>

</tr>

<?php } ?>

<tr class="tableheader">

<td align="center" colspan="2"><input


type="submit" name="submit" value="Submit"></td>

</tr>

</table>

</form>

PHP Code for Calculating Failed Login Count


This code is used to calculate the number of invalid login attempts based
on the IP address.

$mysqli = new
mysqli('localhost','root','','blog_examples');

$ip = $_SERVER['REMOTE_ADDR'];

$result = $mysqli->query("SELECT count(ip_address) AS


failed_login_attempt FROM failed_login WHERE ip_address =
'$ip' AND date BETWEEN DATE_SUB( NOW() , INTERVAL 1 DAY )
AND NOW()");
$row = $result->fetch_assoc();

$failed_login_attempt = $row['failed_login_attempt'];

$result->free();

Insert Invalid Login Entries


This code validates user credentials and if the credentials are invalid then an
entry with ip_address and date will be added to the database.

session_start();

$message="";

$captcha = true;

if(count($_POST)>0 && isset($_POST["captcha_code"]) &&


$_POST["captcha_code"]!=$_SESSION["captcha_code"]) {

$captcha = false;

$message = "Enter Correct Captcha Code";

if(count($_POST)>0 && $captcha == true) {

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


user_name='" . $_POST["user_name"] . "' and password = '".
$_POST["password"]."'");

$row = $result->fetch_assoc();

$result->free();

if(is_array($row)) {

$_SESSION["user_id"] = $row["id"];

$_SESSION["user_name"] = $row["user_name"];
$mysqli->query("DELETE FROM failed_login WHERE
ip_address = '$ip'");

} else {

$message = "Invalid Username or Password!";

if ($failed_login_attempt < 3) {

$mysqli->query("INSERT INTO failed_login


(ip_address,date) VALUES ('$ip', NOW())");

} else {

$message = "You have tried more than 3


invalid attempts. Enter captcha code.";

download

This PHP code tutorial was published on February 2, 2015.

PHP CRUD with Search and Pagination


In this tutorial, we will see about a simple PHP application for database
create, read, update and delete (CRUD) operations. With these CRUD
operations, we will also have search and pagination features integrated to
it.

Earlier, we saw about CRUD with AJAX and CRUD without AJAX (both did
not have search and pagination). Now in this tutorial, we will directly jump
into the search and pagination part. The download code contains the
complete CRUD operations, search and pagination features.

download

Search Data by Keyword using PHP and MySQL


We have search options for searching the Name and Code columns by the
given keywords posted via the search form. The search keyword is used to
find the match with the values of corresponding columns by using
MySQL LIKE clause. If match found then the results will be read and
displayed on the list page with pagination.

The code for the search form is,

<form name="frmSearch" method="post" action="index.php">


<div class="search-box">

<p>

<input type="text" placeholder="Name"


name="search[name]" class="demoInputBox" value="<?php echo
$name; ?>" />

<input type="text" placeholder="Code"


name="search[code]" class="demoInputBox" value="<?php echo
$code; ?>" />

<input type="submit" name="go" class="btnSearch"


value="Search">

<input type="reset" class="btnSearch" value="Reset"


onclick="window.location='index.php'">

</p>

</div>

</form>

After submitting the search form, we are accessing the keywords from a
PHP script to create search conditions for the select query. We have switch
case to create query conditions with LIKE clause. The code is,

<?php

require_once("perpage.php");

require_once("dbcontroller.php");

$db_handle = new DBController();

$name = "";

$code = "";

$queryCondition = "";

if(!empty($_POST["search"])) {
foreach($_POST["search"] as $k=>$v){

if(!empty($v)) {

$queryCases = array("name","code");

if(in_array($k,$queryCases)) {

if(!empty($queryCondition)) {

$queryCondition .= "
AND ";

} else {

$queryCondition .= "
WHERE ";

switch($k) {

case "name":

$name = $v;

$queryCondition .=
"name LIKE '" . $v . "%'";

break;

case "code":

$code = $v;

$queryCondition .=
"code LIKE '" . $v . "%'";

break;

}
}

$orderby = " ORDER BY id desc";

$sql = "SELECT * FROM toy " . $queryCondition;

$href = 'index.php';

$perPage = 2;

$page = 1;

if(isset($_POST['page'])) $page = $_POST['page'];

$start = ($page-1)*$perPage;

if($start < 0) $start = 0;

$query = $sql . $orderby . " limit " . $start . ","


. $perPage;

$result = $db_handle->runQuery($query);

if(!empty($result)) $result["perpage"] =
showperpage($sql, $perPage, $href);

?>

PHP Pagination by Preserving Search Results


If you have paginated search results by Name or Code and want to
navigate through the pages, the search query condition should be
preserved. If we have the pagination links for page navigation then it will
redirect to different URL and the search conditions will be reset. So, we are
using submit buttons for the page navigation.
function perpage($count, $per_page = '10',$href) {

$output = '';

$paging_id = "link_perpage_box";

if(!isset($_POST["page"])) $_POST["page"] = 1;

if($per_page != 0)

$pages = ceil($count/$per_page);

if($pages>1) {

if(($_POST["page"]-3)>0) {

if($_POST["page"] == 1) $output = $output


. '<span id=1 class="current-page">1</span>';

else $output = $output . '<input


type="submit" name="page" class="perpage-link" value="1"
/>';

if(($_POST["page"]-3)>1) $output = $output .


'...';

for($i=($_POST["page"]-2);
$i<=($_POST["page"]+2); $i++) {

if($i<1) continue;

if($i>$pages) break;

if($_POST["page"] == $i) $output = $output


. '<span id='.$i.' class="current-page" >'.$i.'</span>';

else $output = $output . '<input


type="submit" name="page" class="perpage-link" value="' . $i
. '" />';

if(($pages-($_POST["page"]+2))>1) $output =
$output . '...';
if(($pages-($_POST["page"]+2))>0) {

if($_POST["page"] == $pages)

$output = $output . '<span id=' .


($pages) .' class="current-page">' . ($pages) .'</span>';

else

$output = $output . '<input


type="submit" name="page" class="perpage-link" value="' .
$pages . '" />';

return $output;

MySQL Database Script


CREATE TABLE IF NOT EXISTS `toy` (

`id` int(8) NOT NULL AUTO_INCREMENT,

`name` varchar(255) NOT NULL,

`code` varchar(20) NOT NULL,

`category` varchar(255) NOT NULL,

`price` double NOT NULL,

`stock_count` bigint(16) NOT NULL,

PRIMARY KEY (`id`)

download
This PHP code tutorial was published on November 2, 2014.

PHP MySQL Date Range Search with


jQuery DatePicker

In this tutorial, we are going to see how to search database records date
between two given ranges. It will return the filtered results from the
database based on these dates input.
In this tutorial, we are using jQuery DatePicker to choose the dates for the
search options. These date inputs are used to form a database query to
read rows within two dates by the use of BETWEEN clause.

view demo download

HTML Date Range Search Form


This code shows the HTML code for displaying database records and the
search input controls. These controls are having a DatePicker to select date
input.

<form name="frmSearch" method="post" action="">

<p class="search_input">

<input type="text" placeholder="From Date"


id="post_at" name="search[post_at]" value="<?php echo
$post_at; ?>" class="input-control" />

<input type="text" placeholder="To Date"


id="post_at_to_date" name="search[post_at_to_date]"
style="margin-left:10px" value="<?php echo
$post_at_to_date; ?>" class="input-control"
/>
<input type="submit" name="go" value="Search" >

</p>

</form>

PHP MySQL Date Range Search Filter


This code reads dates from the user for the search form controls and
creates a database query to filter records based on the date fields.

<?php

$conn = mysqli_connect("localhost", "root", "",


"blog_samples");

$post_at = "";

$post_at_to_date = "";

$queryCondition = "";

if(!empty($_POST["search"]["post_at"]))
{

$post_at = $_POST["search"]["post_at"];

list($fid,$fim,$fiy) = explode("-",$post_at);

$post_at_todate = date('Y-m-d');

if(!empty($_POST["search"]["post_at_to_date"]))
{

$post_at_to_date =
$_POST["search"]["post_at_to_date"];

list($tid,$tim,$tiy) = explode("-
",$_POST["search"]["post_at_to_date"]);
$post_at_todate = "$tiy-$tim-$tid";

$queryCondition .= "WHERE post_at BETWEEN '$fiy-


$fim-$fid' AND '" . $post_at_todate . "'";

$sql = "SELECT * from posts " . $queryCondition . "


ORDER BY post_at desc";

$result = mysqli_query($conn,$sql);

?>

view demo download

This PHP code tutorial was published on February 14, 2016.

Advanced Search using PHP



In PHP advance search we have many options to filter MySQL data. Using
these options we are creating database query condition to make an
advanced search. In a previous tutorial, we have seen simple PHP search to
filter MySQL records which have only one field to enter the search keyword.

In the advanced search form, we have inputs to search with respect to the
exact or any one of a word from given phrase, to exclude given string and
to search results that start with given word. And also we can also choose
database column in which the search should be happening.

HTML Advance Search Form


This code contains HTML form inputs for the advanced search option.

<form name="frmSearch" method="post" action="index.php">

<input type="hidden" id="advance_search_submit"


name="advance_search_submit" value="<?php echo
$advance_search_submit; ?>">
<div class="search-box">

<label class="search-label">With Any One of the


Words:</label>

<div>

<input type="text"
name="search[with_any_one_of]" class="demoInputBox"
value="<?php echo $with_any_one_of; ?>" />

<span id="advance_search_link"
onClick="showHideAdvanceSearch()">Advance Search</span>

</div>

<div id="advanced-search-box" <?php


if(empty($advance_search_submit)) {
?>style="display:none;"<?php } ?>>

<label class="search-label">With the Exact


String:</label>

<div>

<input type="text"
name="search[with_the_exact_of]" id="with_the_exact_of"
class="demoInputBox" value="<?php echo $with_the_exact_of;
?>" />

</div>

<label class="search-
label">Without:</label>

<div>

<input type="text"
name="search[without]" id="without" class="demoInputBox"
value="<?php echo $without; ?>" />

</div>

<label class="search-label">Starts
With:</label>
<div>

<input type="text"
name="search[starts_with]" id="starts_with"
class="demoInputBox" value="<?php echo $starts_with;
?>" />

</div>

<label class="search-label">Search
Keywords in:</label>

<div>

<select name="search[search_in]"
id="search_in" class="demoInputBox">

<option value="">Select
Column</option>

<option value="title" <?php


if($search_in=="title") { echo "selected"; }
?>>Title</option>

<option value="description"
<?php if($search_in=="description") { echo "selected"; }
?>>Description</option>

</select>

</div>

</div>

<div>

<input type="submit" name="go"


class="btnSearch" value="Search">

</div>

</div>

</form>
Creating Advance Search Condition in PHP
This code receives form inputs and forms MySQL query with the advanced
search condition. If the user prefers database columns to search then the
search will apply on that column. Otherwise, we will search in all the
columns. The code is,

<php

$conn = mysqli_connect("localhost", "root", "",


"blog_samples");

$with_any_one_of = "";

$with_the_exact_of = "";

$without = "";

$starts_with = "";

$search_in = "";

$advance_search_submit = "";

$queryCondition = "";

if(!empty($_POST["search"])) {

$advance_search_submit =
$_POST["advance_search_submit"];

foreach($_POST["search"] as $k=>$v){

if(!empty($v)) {

$queryCases =
array("with_any_one_of","with_the_exact_of","without","start
s_with");

if(in_array($k,$queryCases)) {
if(!empty($queryCondition)) {

$queryCondition .= "
AND ";

} else {

$queryCondition .= "
WHERE ";

switch($k) {

case "with_any_one_of":

$with_any_one_of = $v;

$wordsAry = explode("
", $v);

$wordsCount =
count($wordsAry);

for($i=0;$i<$wordsCount;$i++) {

if(!empty($_POST["search"]["search_in"])) {

$queryCondition .= $_POST["search"]["search_in"] . "


LIKE '%" . $wordsAry[$i] . "%'";

} else {

$queryCondition .= "title LIKE '" . $wordsAry[$i] .


"%' OR description LIKE '" . $wordsAry[$i] . "%'";

if($i!=$wordsCount-1) {
$queryCondition .= " OR ";

break;

case "with_the_exact_of":

$with_the_exact_of =
$v;

if(!empty($_POST["search"]["search_in"])) {

$queryCondition
.= $_POST["search"]["search_in"] . " LIKE '%" . $v . "%'";

} else {

$queryCondition
.= "title LIKE '%" . $v . "%' OR description LIKE '%" . $v .
"%'";

break;

case "without":

$without = $v;

if(!empty($_POST["search"]["search_in"])) {

$queryCondition
.= $_POST["search"]["search_in"] . " NOT LIKE '%" . $v .
"%'";

} else {

$queryCondition
.= "title NOT LIKE '%" . $v . "%' AND description NOT LIKE
'%" . $v . "%'";
}

break;

case "starts_with":

$starts_with = $v;

if(!empty($_POST["search"]["search_in"])) {

$queryCondition
.= $_POST["search"]["search_in"] . " LIKE '" . $v . "%'";

} else {

$queryCondition
.= "title LIKE '" . $v . "%' OR description LIKE '" . $v .
"%'";

break;

case "search_in":

$search_in =
$_POST["search"]["search_in"];

break;

$orderby = " ORDER BY id desc";

$sql = "SELECT * FROM links " . $queryCondition;

$result = mysqli_query($conn,$sql);

?>
download

This PHP code tutorial was published on May 30, 2016.

User Login Session Timeout Logout in


PHP

This PHP tutorial is used for setting user login session expiration time for
the logged-in user. Once, this time is elapsed then the user no longer
access the authenticated pages of the application. In the previous tutorial,
we have created session variables once a user logged in to our application.

In this tutorial, we are going to add the current logged-in timestamp to a


session. Using this timestamp we are checking if the login session
expiration time is reached. If so, the user will be logged out.

view demo download


HTML code for User Login
This code is for showing login form to the user.

<form name="frmUser" method="post" action="">

<?php if($message!="") { ?>

<div class="message"><?php echo $message; ?></div>

<?php } ?>

<table border="0" cellpadding="10" cellspacing="1"


width="100%" class="tblLogin">

<tr class="tableheader">

<td align="center" colspan="2">Enter Login Details</td>

</tr>

<tr class="tablerow">

<td align="right">Username</td>

<td><input type="text" name="user_name"></td>

</tr>

<tr class="tablerow">

<td align="right">Password</td>

<td><input type="password" name="password"></td>

</tr>
<tr class="tableheader">

<td align="center" colspan="2"><input type="submit"


name="submit" value="Submit"></td>

</tr>

</table>

</form>

Creating User Login Session


In this code, we are adding logged-in user id and logged-in time to a
session variable. Then, we are invoking a PHP function to check if the login
session expiration time is elapsed. If it is not reached, then the user will be
redirected to the dashboard.

if(count($_POST)>0) {

if( $_POST["user_name"] == "admin" and


$_POST["password"] == "admin") {

$_SESSION["user_id"] = 1001;

$_SESSION["user_name"] = $_POST["user_name"];

$_SESSION['loggedin_time'] = time();

} else {

$message = "Invalid Username or Password!";

if(isset($_SESSION["user_id"])) {

if(!isLoginSessionExpired()) {

header("Location:user_dashboard.php");
} else {

header("Location:logout.php?session_expired=1");

PHP Function for Checking Login Session Timeout


This function will be invoked at the beginning of all authenticated pages.
This function returns TRUE if the user login session is expired, FALSE
otherwise.

function isLoginSessionExpired() {

$login_session_duration = 10;

$current_time = time();

if(isset($_SESSION['loggedin_time']) and
isset($_SESSION["user_id"])){

if(((time() - $_SESSION['loggedin_time']) >


$login_session_duration)){

return true;

return false;

User Login Session Expiration Logout


This logout.php page will unset logged-in user session and check for the
status of the session_expired flag. If it is set, then the login session timeout
message will be displayed to the user.

session_start();
unset($_SESSION["user_id"]);

unset($_SESSION["user_name"]);

$url = "index.php";

if(isset($_GET["session_expired"])) {

$url .= "?session_expired=" .
$_GET["session_expired"];

header("Location:$url");

view demo download

This PHP code tutorial was published on November 24, 2014.

PHP cURL

cURL Client URL library is used to communicate with different type of


servers with protocols FTP, HTTP, telnet, gopher and more. In PHP, we have
to install libcurl library for using cURL function. If we used any one of AMP
bundle like XAMPP, to create PHP environment, then the cURL library will
come up with this bundle.
After cURL installation, we should enable this extension in PHP
configuration file.

//Remove semi colon (;) to enable

;extension=php_curl.dll

cURL Supported Operations


For handling remote file access, the cURL as an intermediary is used for,

Form submitting
Authentication
File upload
File transfer

Without cURL, we can use PHP file system functionsallow_url_fopen


configuration directive which is not preferable because of security reasons.
For example, file_get_contents() returns remote data including some
untrusted internet content.

PHP cURL Delimiters


In a PHP program, the cURL portion should be enclosed within this two pair
of functions.

$ch = curl_init(URL Syntax);

...

curl_close($ch);

The curl_init() function returns cURL session handle with respect to the
given file URL. And then, curl_close() function will be an end delimiter to
close cURL session with respect to its handle.

cURL Options
PHP curl_setopt() function is used to set options. It receives cURL handle,
options name and value as its parameters.
We can use another cURL function curl_setopt_array() to set an array of
multiple options at a push.

curl_setopt ($ch, CURLOPT_HEADER, 1);

cURL Option Constants


CURLOPT_FILE target file to write cURL result.
CURLOPT_URL URL from where we need to get data. If this URL is
specified with curl_init(), then no need to set this option
CURLOPT_RETURNTRANSFER to return the result in string format
into a variable instead of printing it to the browser.
CURLOPT_HTTPHEADER to set header fields as an array.
CURLOPT_POST set to TRUE to perform HTTP POST.
CURLOPT_USERPWD to set username/password if required to
connect remote server.

PHP cURL Request


Like PHP, the GET and POST methods are used for sending cURL request
where GET is the default. The CURLOPT_POST constant is used for sending
POST request. And the parameters CURLOPT_POSTFIELDS is for sending
parameter array of the field: value pairs.

cURL Execution
After setting request methods and parameters, curl_exec() function is used
for executing cURL request.

$result = curl_exec($ch);
This function returns either boolean values or string data based on the
value of option CURLOPT_RETURNTRANSFER.

PHP cURL Example


This PHP example is to get the body content from the given remote URL.

<?php

$url = "http://php.net/";

$content = curlRequest($url);

print $content;

function curlRequest($url) {

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

$response = curl_exec($ch);

$body = substr( $response, $header_size );

fclose($ch);

return $content;

?>

This PHP code tutorial was published on October 18, 2013.

You might also like