Professional Documents
Culture Documents
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.
<tr class="tableheader">
</tr>
<tr class="tablerow">
<td>
</tr>
<tr class="tablerow">
<td>
</tr>
<tr class="tableheader">
</tr>
</table>
</form>
body{
font-family: calibri;
.tblLogin {
background: #d1e8ff;
border-radius: 4px;
}
.tablerow td { text-align:center; }
.message {
color: #FF0000;
font-weight: bold;
text-align: center;
width: 100%;
.login-input {
.btnSubmit {
background: #2c7ac5;
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");
$count = mysqli_num_rows($result);
if($count==0) {
?>
download
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.
<div class="field-group">
<div><label for="login">Username</label></div>
</div>
<div class="field-group">
<div><label
for="password">Password</label></div>
</div>
<div class="field-group">
</div>
</form>
#frmLogin {
background: #B6E0FF;
color: #555;
display: inline-block;
border-radius: 4px;
}
.field-group {
margin:15px 0px;
.input-field {
border-radius: 4px;
.form-submit-button {
background: #65C370;
border: 0;
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
session_start();
$conn =
mysqli_connect("localhost","root","","phppot_examples");
$message="";
if(!empty($_POST["login"])) {
$row = mysqli_fetch_array($result);
if(is_array($row)) {
$_SESSION["user_id"] = $row['user_id'];
} else {
?>
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 {
$row = mysqli_fetch_array($result);
?>
</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.
<?php
if(!empty($_POST["logout"])) {
$_SESSION["user_id"] = "";
session_destroy();
?>
download
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.
<div class="tblLogin">
<?php
if(!empty($success == 1)) {
?>
<div class="tablerow">
</div>
<?php
} else if ($success == 2) {
?>
<?php
}
else {
?>
<?php
?>
</div>
</form>
<?php
$success = "";
$error_message = "";
$conn =
mysqli_connect("localhost","root","","blog_samples");
if(!empty($_POST["submit_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) {
$current_id = mysqli_insert_id($conn);
if(!empty($current_id)) {
$success=1;
} else {
if(!empty($_POST["submit_otp"])) {
$count = mysqli_num_rows($result);
if(!empty($count)) {
$success = 2;
} else {
$success =1;
$error_message = "Invalid OTP!";
?>
download
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.
<html>
<head>
<title>Change Password</title>
</head>
<body>
<div style="width:500px;">
<tr class="tableheader">
</tr>
<tr>
</tr>
<tr>
<td><label>New Password</label></td>
</tr>
<td><label>Confirm Password</label></td>
</tr>
<tr>
</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
$_SESSION["userId"] = "24";
$conn = mysql_connect("localhost","root","");
mysql_select_db("phppot_examples",$conn);
if(count($_POST)>0) {
$row=mysql_fetch_array($result);
if($_POST["currentPassword"] == $row["password"]) {
mysql_query("UPDATE users set password='" .
$_POST["newPassword"] . "' WHERE userId='" .
$_SESSION["userId"] . "'");
?>
download
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.
<h1>Forgot Password?</h1>
<?php } ?>
<div id="validation-message">
<?php } ?>
</div>
<div class="field-group">
<div><label
for="username">Username</label></div>
</div>
<div class="field-group">
<div><label for="email">Email</label></div>
</div>
<div class="field-group">
</div>
</form>
Once this form is submitted, then the PHP code get the user details from
the database.
<?php
if(!empty($_POST["forgot-password"])){
$condition = "";
if(!empty($_POST["user-login-name"]))
if(!empty($_POST["user-email"])) {
if(!empty($condition)) {
if(!empty($condition)) {
$result = mysqli_query($conn,$sql);
$user = mysqli_fetch_array($result);
if(!empty($user)) {
require_once("forgot-password-recovery-
mail.php");
} else {
}
}
?>
<?php
if(!class_exists('PHPMailer')) {
require('phpmailer/class.phpmailer.php');
require('phpmailer/class.smtp.php');
require_once("mail_configuration.php");
$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->MsgHTML($emailBody);
$mail->IsHTML(true);
if(!$mail->Send()) {
} else {
?>
Note:
<?php
define("PROJECT_HOME","http://localhost/phpsamples/");
define("MAILER", "smtp");
define("SENDER_NAME", "Admin");
define("SERDER_EMAIL", "admin@admin.com");
?>
download
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,
require('phpmailer/class.phpmailer.php');
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->Host = "smtp.gmail.com";
$mail->Mailer = "smtp";
$mail->AddAddress("recipient email");
$mail->WordWrap = 80;
$mail->IsHTML(true);
if(!$mail->Send())
else
For setting FromEmail and FromName, we can either use SetFrom() function
or use PHPMailer properties PHPMailer::From and PHPMailer::FromName.
For example,
$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.
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.
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.
<?php
$fromAddress = "-fpostmaster@localhost";
if($emailStatus) {
} else {
?>
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.
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.
<div class="field-group">
<div><label for="login">Username</label></div>
</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>
<div class="field-group">
</div>
</form>
<?php
session_start();
if(!empty($_POST["login"])) {
$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 {
}
?>
download
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.
<tr class="tableheader">
</tr>
<tr class="tablerow">
<td align="right">Username</td>
</tr>
<tr class="tablerow">
<td align="right">Password</td>
</tr>
<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">
</tr>
</table>
</form>
$mysqli = new
mysqli('localhost','root','','blog_examples');
$ip = $_SERVER['REMOTE_ADDR'];
$failed_login_attempt = $row['failed_login_attempt'];
$result->free();
session_start();
$message="";
$captcha = true;
$captcha = false;
$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 {
if ($failed_login_attempt < 3) {
} else {
download
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
<p>
</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");
$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;
}
}
$href = 'index.php';
$perPage = 2;
$page = 1;
$start = ($page-1)*$perPage;
$result = $db_handle->runQuery($query);
if(!empty($result)) $result["perpage"] =
showperpage($sql, $perPage, $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) {
for($i=($_POST["page"]-2);
$i<=($_POST["page"]+2); $i++) {
if($i<1) continue;
if($i>$pages) break;
if(($pages-($_POST["page"]+2))>1) $output =
$output . '...';
if(($pages-($_POST["page"]+2))>0) {
if($_POST["page"] == $pages)
else
return $output;
download
This PHP code tutorial was published on November 2, 2014.
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.
<p class="search_input">
</p>
</form>
<?php
$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";
$result = mysqli_query($conn,$sql);
?>
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.
<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>
<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="description"
<?php if($search_in=="description") { echo "selected"; }
?>>Description</option>
</select>
</div>
</div>
<div>
</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
$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"])) {
} else {
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;
$result = mysqli_query($conn,$sql);
?>
download
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.
<?php } ?>
<tr class="tableheader">
</tr>
<tr class="tablerow">
<td align="right">Username</td>
</tr>
<tr class="tablerow">
<td align="right">Password</td>
</tr>
<tr class="tableheader">
</tr>
</table>
</form>
if(count($_POST)>0) {
$_SESSION["user_id"] = 1001;
$_SESSION["user_name"] = $_POST["user_name"];
$_SESSION['loggedin_time'] = time();
} else {
if(isset($_SESSION["user_id"])) {
if(!isLoginSessionExpired()) {
header("Location:user_dashboard.php");
} else {
header("Location:logout.php?session_expired=1");
function isLoginSessionExpired() {
$login_session_duration = 10;
$current_time = time();
if(isset($_SESSION['loggedin_time']) and
isset($_SESSION["user_id"])){
return true;
return false;
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");
PHP cURL
;extension=php_curl.dll
Form submitting
Authentication
File upload
File transfer
...
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 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
$url = "http://php.net/";
$content = curlRequest($url);
print $content;
function curlRequest($url) {
$ch = curl_init();
$response = curl_exec($ch);
fclose($ch);
return $content;
?>