MySQL is a popular choice as a backend database for PHP powered web applications. In this chapter, we shall learn to develop a login page for a PHP application that authenticates the given username and password.
You should have a web server having PHP and MySQL installed for experimenting with the example discussed in this chapter. The bundled binaries of Apache, PHP and MySQL (MariaDB) in the form of XAMPP for your operating system can be easily installed.
Before running the example code, you should have a MySQL database called mydb in which there must be a table called admin. You can use following SQL script to create the table and insert a test data
The first part of PHP login application is to establish database connection object. We use myqli API to obtain connection object. Save following code as “config.php”
This PHP script is called inside the login script. It presents the user with a HTML form to enter username and password. In case the form is submitted, PHP runs a SELECT query to retrieve a row in the admin table where the username and passcode matches with the user inputs.
$myusername=mysqli_real_escape_string($db,$_POST['username']);$mypassword=mysqli_real_escape_string($db,$_POST['password']);$sql="SELECT * FROM admin WHERE username = '$myusername' and passcode = '$mypassword'";$result=mysqli_query($db,$sql);$row=mysqli_num_rows($result);
If the row count is one, it indicates that the username and the password entered matches. The username is save to the $_SESSION variable and the browser is directed to welcome.php script.
Login.php
Save the following code as “login.php” −
<?php
include("config.php");
session_start();
$error='';
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT * FROM admin WHERE username = '$myusername' and passcode = '$mypassword'";
$result = mysqli_query($db,$sql);
$row = mysqli_num_rows($result);
$count = mysqli_num_rows($result);
if($count == 1) {
// session_register("myusername");
$_SESSION['login_user'] = $myusername;
header("location: welcome.php");
} else {
$error = "Your Login Name or Password is invalid";
}
}
?><html><head><title>Login Page</title><style type = "text/css">
body {
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
}
label {
font-weight:bold;
width:100px;
font-size:14px;
}
.box {
border:#666666 solid 1px;
}
</style></head><body bgcolor = "#FFFFFF"><div align = "center"><div style = "width:300px; border: solid 1px #333333; " align = "left"><div style = "background-color:#333333; color:#FFFFFF; padding:3px;"><b>Login</b></div><div style = "margin:30px"><form action = "" method = "post"><label>UserName :</label><input type = "text" name = "username" class = "box"/><br /><br /><label>Password :</label><input type = "password" name = "password" class = "box" /><br/><br /><input type = "submit" value = " Submit "/><br /></form><div style = "font-size:11px; color:#cc0000; margin-top:10px"><?php echo $error; ?></div></div></div></div></body></html>
Session.php
The following is thesession.phpcode file. It checks if the session variable is set; then the user credentials will be assigned to the$login_sessionvariable. If not, the user is redirected back to thelogin.phpfile.
To start the login application, visit “http://localhost/login.php”
Enter the username and password. On pressing the submit button, these inputs are checked against the rows in admin table. On success, you get the following message −
If the query doesnt fetch any matching row, the error message is displayed as follows −
PayPal is a payment processing system. We can integrate PayPal with websites by using with PHP.
PayPal Integration File System
PayPal integration file system included four files as shown below −
constants.php − This file includes the API user name, password and signature.
CallerService.php − This file includes the PayPal Services, which are used to call PayPal services.
confirmation.php − This file includes a form with minimum fields required to make payment process and it will return payment success or failure.
PayPal_entry.php − This page has used to send the user the data to PayPal. It acts as an adapter between PayPal and user form.
The user has to download a PayPal SDK file from here and exact a zip file. The zip file contains four PHP files. We don’t need to change any file except “constants.php”.
constants.php
The “constants.php” file contains code as shown below −
<?php
define('API_USERNAME', 'YOUR USER NAME HERE');
define('API_PASSWORD', 'YOUR PASSWORD HERE');
define('API_SIGNATURE', 'YOUR API SIGNATURE HERE');
define('API_ENDPOINT', 'https://api-3t.paypal.com/nvp');
define('USE_PROXY',FALSE);
define('PROXY_HOST', '127.0.0.1');
define('PROXY_PORT', '808');
define('PAYPAL_URL', 'https://www.PayPal.com/webscr&cmd=_express-checkout&token=');
define('VERSION', '53.0');
?>
The user will declare the username, password and signature in the above syntax which are placed in “constants.php”.
This is an experimental example so the last amount will be added to sandbox’s account.
Users can be asked to log into a web application with the help of Social media login, also called SSO. This way users need not create a new account. Instead, users can use their existing social media account information to log in. Some examples of social media login include: Google, Facebook, LinkedIn, Apple.
In this chapter, we shall explain how to activate logging into a PHP application with Facebook credentials.
Next, enter the name of the Facebook app you want to create −
Go in the App settings and obtain Application ID and secret code −
Select platform as website −
Next, you need to set Up Facebook SDK in PHP. Download the Facebook SDK for PHP from “https://packagist.org/packages/facebook/php-sdk” or use composer: composer require “facebook/graph-sdk-v5”. Extract the SDK files to a directory accessible by your PHP application.
To configure Facebook SDK in PHP Code, include the Facebook SDK autoloader in your PHP file: require_once __DIR__ . ‘/vendor/autoload.php’;
Create a PHP script to handle the Facebook login callback −
<?php
session_start();
$fb = new Facebook\Facebook([
'app_id' => $app_id,
'app_secret' => $app_secret,
'default_graph_version' => 'v13.0',
]);
$helper = $fb->getRedirectLoginHelper();
$accessToken = $helper->getAccessToken();
if ($accessToken) {
// User is logged in, handle their data
$user = $fb->get('/me', ['fields' => 'id,name,email']);
$_SESSION['user_data'] = $user;
header('Location: profile.php');
} else {
// User is not logged in, redirect to login page
$loginUrl = $helper->getLoginUrl(['scope' => 'public_profile,email']);
header('Location: ' . $loginUrl);
}
?>
After successful login, store user data in the session and redirect to a protected page. On protected pages, check the session for user data to verify access.
A typical PHP web application authenticates the user before logging in, by asking his credentials such as username and password. The credentials are then checked against the user data available with the server. In this example, the user data is available in the form of an associative array. The following PHP Login script is explained below −
HTML Form
The HTML part of the code presents a simple HTML form, that accepts username and password, and posts the data to itself.
The PHP script parses the POST data, and checks if the username is present in the users array. If found, it further checks whether the password corresponds to the registered user in the array
<?php
if (array_key_exists($user, $users)) {
if ($users[$_POST['username']]==$_POST['password']) {
$_SESSION['valid'] = true;
$_SESSION['timeout'] = time();
$_SESSION['username'] = $_POST['username'];
$msg = "You have entered correct username and password";
} else {
$msg = "You have entered wrong Password";
}
} else {
$msg = "You have entered wrong user name";
}
?>
The username and the appropriate message is added to the $_SESSION array. The user is prompted with a respective message, whether the credentials entered by him are correct or not.
The Complete Code
Here is the complete code −
Login.php
<?php
ob_start();
session_start();
?><html lang = "en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="stylesheet" href="loginstyle.css"><title>Login</title></head><body><h2 style="margin-left:10rem; margin-top:5rem;">Enter Username and Password</h2><?php
$msg = '';
$users = ['user'=>"test", "manager"=>"secret", "guest"=>"abc123"];
if (isset($_POST['login']) && !empty($_POST['username'])
&& !empty($_POST['password'])) {
$user=$_POST['username'];
if (array_key_exists($user, $users)){
if ($users[$_POST['username']]==$_POST['password']){
$_SESSION['valid'] = true;
$_SESSION['timeout'] = time();
$_SESSION['username'] = $_POST['username'];
$msg = "You have entered correct username and password";
}
else {
$msg = "You have entered wrong Password";
}
}
else {
$msg = "You have entered wrong user name";
}
}
?><h4 style="margin-left:10rem; color:red;"><?php echo $msg; ?></h4><br/><br/><form action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post"><div><label for="username">Username:</label><input type="text" name="username" id="name"></div><div><label for="password">Password:</label><input type="password" name="password" id="password"></div><section style="margin-left:2rem;"><button type="submit" name="login">Login</button></section></form><p style="margin-left: 2rem;"><a href = "logout.php" tite = "Logout">Click here to clean Session.</a></p></div></body></html>
Logout.php
To logout, the user clicks on the link to logout.php
Message flashing in a PHP web application refers to the technique that makes certain messages popup on the browser window for the user to receive applications feedback. To be able to give the user a meaningful feedback to his interactions is an important design principle, that gives a better user experience.
In a PHP web application, we can use the session data to flash messages regarding success or failure of a certain action, notifications or warnings, etc., from time to time to keep the user informed.
A flash message allows you to create a message on one page and display it once on another page. To transfer a message from one page to another, you use the $_SESSION superglobal variable.
To start with, you add a variable to the $_SESSION array as follows −
Later, navigate to another page, and retrieve the flashed message from the $_SESSION variable and assign it to a variable. Then, you can display the message and then delete the message from the $_SESSION −
To generalize the basic idea of handling the flashed messages, we shall write a function that adds a message to the $_SESSION −
session_start();functioncreate_flash_message(string$name,string$message):void{// remove existing message with the nameif(isset($_SESSION[FLASH][$name])){unset($_SESSION[FLASH][$name]);}// add the message to the session$_SESSION[FLASH][$name]=['message'=>$message];}
Let us also have another function that reads back a message, flashes it on the browser, and removes it from the $_SESSION.
functiondisplay_flash_message(string$name):void{if(!isset($_SESSION[FLASH][$name])){return;}// get message from the session$flash_message=$_SESSION[FLASH][$name];// delete the flash messageunset($_SESSION[FLASH][$name]);// display the flash messageechoformat_flash_message($flash_message);}
The format_flash_message() function applies desired formatting to the obtained string with appropriate CSS rules.
If there are more than messages that have been flashed by the application, all of them can be retrieved and flashed with the following example −
functiondisplay_all_flash_messages():void{if(!isset($_SESSION[FLASH])){return;}// get flash messages$flash_messages=$_SESSION[FLASH];// remove all the flash messagesunset($_SESSION[FLASH]);// show all flash messagesforeach($flash_messagesas$flash_message){echoformat_flash_message($flash_message);}}
Use the following flash() function to create, format and flash the messages
functionflash(string$name='',string$message=''):void{if($name!==''&&$message!==''){create_flash_message($name,$message);}elseif($name!==''&&$message===''){display_flash_message($name);// display a flash message}elseif($name===''&&$message===''){display_all_flash_messages();// display all flash message}}
To implement the above method, call the flash() function on the first page.
flash('first','Hello World');
Navigate to another page and call the flash() function to retrieve and display the message −
flash('first');
Mechanism of using the flash messages is usually employed on a signup page to redirect users to the login page with a welcome message after they sign up.
In PHP, PRG stands for “Post/Redirect/Get”. It is a commonly used technique that is designed to prevent the resubmission of a form after it’s been submitted. You can easily implement this technique in PHP to avoid duplicate form submissions.
Usually a HTML form sends data to the server with the POST method. The server script fetches the data for further processing like adding a new record in a backend database, or running a query to fetch data. If the user accidentally refreshes the browser, there is a possibility of the same form data being resubmitted again, possibly leading to loss of data integrity. The PRG approach in PHP helps you avoid this pitfall.
Example
To start with, let us consider the following PHP script that renders a simple HTML form, and submits it back to itself with POST method. When the user fills the data and submits, the backend script fetches the data, renders the result, and comes back to show the blank form again.
Assuming that the server is running, the above script is placed in the document root folder and visited in the browser.
Fill the data and submit. The browser echoes the result, and re-renders the form. Now if you try to refresh the browser page, a warning pops up as shown below −
If you press Continue, the same data is posted again.
The problem can be understood with the following figure −
Following steps are taken in the PHP script to avoid the problem −
The PHP script before the HTML form starts a new session.
Check if the form has been submitted with POST method.
If so, store the form data in session variables
Redirect the browser to a result page. In our case, it is the same page. With the exit command, to terminate this script to make sure no more code gets executed.
If PHP finds that the REQUEST method is not POST, it checks if the session variables are set. If so, they are rendered along with the fresh copy of form.
Now even if the form is refreshed, you have successfully averted the possibility of resubmission.
Example
Here is the PHP code that uses the PRG technique −
In PHP, it is important to ensure that the input data is sanitized properly by removed any undesired characters before it is processed by the server side code. Usually, the users input their data to a PHP web application through a HTML form. If the form data consists of any undesired characters, it may prove to be harmful, hence an appropriate cleansing operation must be performed.
Input sanitization can be done with the help of one or more of the following functions in PHP.
What is Input Sanitization?
Input sanitization is the process of cleaning up data provided by users before it is used in an application. This prevents other characters or code from being executed. Cleaning input reduces the probability of security issues like SQL injection and cross-site scripting (XSS) attacks.
Here is why the Input Sanitization important −
Security: The main objective of sanitization is to keep your application safe from threats. Malicious users can try to harm your application by transmitting dangerous data.
Data Integrity: Sanitizing input makes sure the stored information is correct and consistent. This helps to maintain the quality of information in your application.
User Experience: Sanitized input can reduce errors and provide a more consistent user experience.
The htmlspecialchars() Function
This function converts special characters to HTML entities.
In HTML, certain characters have special significance. This htmlspecialchars() function is used to encode special characters in HTML entities. This is useful when you want to display user input as HTML and want to prevent script injection attacks.
The following special characters are translated as shown −
Character
Replaced by
& (ampersand)
&
” (double quote)
", unless ENT_NOQUOTES is set
‘ (single quote)
' (for ENT_HTML401) or ' (for ENT_XML1, ENT_XHTML or ENT_HTML5), but only when ENT_QUOTES is set
< (less than)
<
> (greater than)
>
Flag Constants
The flags parameter is a bitmask of one or more of the following flags, which specify how to handle quotes, invalid code unit sequences and the used document type.
Sr.No
Constant & Description
1
ENT_COMPATWill convert double-quotes and leave single-quotes alone.
2
ENT_QUOTESWill convert both double and single quotes.
3
ENT_NOQUOTESWill leave both double and single quotes unconverted.
4
ENT_IGNOREdiscard invalid code unit sequences instead of returning an empty string.
5
ENT_SUBSTITUTEReplace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or �
6
ENT_DISALLOWEDReplace invalid code points for the given document type with a Unicode Replacement Character U+FFFD (UTF-8) or � (otherwise) instead of leaving them as is. This may be useful.
7
ENT_HTML401Handle code as HTML 4.01.
8
ENT_XML1Handle code as XML 1.
9
ENT_XHTMLHandle code as XHTML.
10
ENT_HTML5Handle code as HTML 5.
Example
Take a look at the following example −
<?php
$str = 'Welcome To "PHP Tutorial" by <b>TutorialsPoint</b>';
echo htmlspecialchars($str);
?>
It will produce the following output −
Welcome To "PHP Tutorial" by <b>TutorialsPoint</b>
The strip_tags() Function
The strip_tags() function removes all the HTML and PHP tags from a given string.
This function is very useful when you want ensure that the user input doesnât contain any potentially malicious tags.
The allowed_tags parameter is an optional second parameter to specify tags which should not be stripped. These are either given as string, or as an array.
The $value parameter is a variable whose value needs to be sanitized. The $filter parameter is any of the predefined filter constants.
Sr.No
ID & Description
1
FILTER_SANITIZE_EMAILRemove all characters except letters, digits and !#$%&’*+-=?^_`{|}~@.[].
2
FILTER_SANITIZE_ENCODEDURL-encode string, optionally strip or encode special characters.
3
FILTER_SANITIZE_ADD_SLASHESApply addslashes(). (Available as of PHP 7.3.0).
4
FILTER_SANITIZE_NUMBER_FLOATRemove all characters except digits, +- and optionally .,eE.
5
FILTER_SANITIZE_NUMBER_INTRemove all characters except digits, plus and minus sign.
6
FILTER_SANITIZE_SPECIAL_CHARSHTML-encode ‘”<>& and characters with ASCII value less than 32, optionally strip or encode other special characters.
7
FILTER_SANITIZE_FULL_SPECIAL_CHARSEquivalent to calling htmlspecialchars() with ENT_QUOTES set. Encoding quotes can be disabled by setting FILTER_FLAG_NO_ ENCODE_QUOTES.td>
8
FILTER_SANITIZE_URLRemove all characters except letters, digits and $-_.+!*'(),{}|\\^~[]`<>#%”;/?:@&=.
9
FILTER_UNSAFE_RAW
Example
The following code shows how you can sanitize Email data −
When working with databases, it is important to escape special characters in strings before you use them in SQL queries to prevent SQL injection.
$conn=newmysqli("localhost","username","password","database");$user_input="O'Reilly";$safe_input=$conn->real_escape_string($user_input);$query="SELECT * FROM users WHERE last_name = '$safe_input'"
The provision of sending emails is one the commonly required features of a typical PHP powered web application. You would like to send emails containing notifications, updates and other communications to your registered users, through your PHP application itself, instead of a different mail service. You can add this capability to your PHP application by adopting the techniques described in this chapter.
PHP has a built-in mail() function to send an email. However, you need configure properly the “php.ini” settings to be able to do so. First, you must know the SMTP domain of the web hosting platform that you are using. For example, if your website is being hosted on GoDaddy hosting service, the SMTP domain is “smtp.secureserver.net”, which you should use in the configuration.
If you use Windows based hosting of GoDaddy, you should ensure that two directives are enabled in php.ini file. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address.
Configuration for Windows
The configuration for Windows should look something like this −
Linux users simply need to let PHP know the location of their sendmail application. The path and any desired switches should be specified to the sendmail_path directive.
The configuration for Linux should look something like this −
[mail function];For Win32 only.SMTP=;For win32 only
sendmail_from =;For Unix only
sendmail_path =/usr/sbin/sendmail -t -i
The mail() Function
The mail() function in PHP requires three mandatory arguments that specify the recipient’s email address, the subject of the message and the actual message additionally there are other two optional parameters.
Syntax
Below is the syntax of the PHP mail() function −
mail( to, subject, message, headers, parameters );
Parameters
Below are the parameters of the mail() function −
to − Required. Specifies the receiver / receivers of the email
subject − Required. Specifies the subject of the email. This parameter cannot contain any newline characters
message − Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
headers − Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
parameters − Optional. Specifies an additional parameter to the send mail program
Multiple recipients can be specified as the first argument to the mail() function in a comma separated list.
Sending HTML Email
When you send a text message using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML message.
While sending an email message you can specify a Mime version, content type and character set to send an HTML email.
Example
The following example shows how to send an HTML email message to “[email protected]” copying it to “[email protected]”. You can code this program in such a way that it should receive all content from the user and then it should send an email.
It should receive all content from the user and then it should send an email.
<?php
$to = "[email protected]";
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$message .= "<h1>This is headline.</h1>";
$header = "From:[email protected] \r\n";
$header .= "Cc:[email protected] \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
?>
It will produce the following output −
Message could not be sent...
sh: 1: /usr/sbin/sendmail: not found
Sending Email from Localhost
The above method of calling PHP mail() may not work on your localhost. In that case, there is an alternate solution to sending email. You can use PHPMailer to send email using SMTP from localhost.
PHPMailer is an open-source library to connect SMTP to send emails. You can download it from PEAR or Composer repositories, or download it from https://github.com/PHPMailer/PHPMailer. Download the ZIP file from here, and copy the contents of the PHPMailer folder into one of the include_path directories specified in your PHP configuration and load each class file manually.
Using PHPMailer for Advanced Features
Use the following PHP script to send email with PHPMailer library −
Phpmailer.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once __DIR__ . '/vendor/phpmailer/src/Exception.php';
require_once __DIR__ . '/vendor/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/vendor/phpmailer/src/SMTP.php';
require 'vendor/autoload.php';
$mail = new PHPMailer;
if(isset($_POST['send'])){
// getting post values
$fname=$_POST['fname'];
$toemail=$_POST['toemail'];
$subject=$_POST['subject'];
$message=$_POST['message'];
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]'; // SMTP username
$mail->Password = 'mypassword'; // SMTP password
// Enable TLS encryption, 'ssl' also accepted
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom([email protected]', 'My_Name');
$mail->addReplyTo([email protected]', 'My_Name');
$mail->addAddress($toemail); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$bodyContent=$message;
$mail->Subject =$subject;
$body = 'Dear'.$fname;
$body .='<p>'.$message.'</p>';
$mail->Body = $body;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
}
?>
Use the following HTML form to compose the mail message. The form is submitted to the above phpmail.php script
To send an email with mixed content you should set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries.
A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email’s final section must also end with two hyphens.
Example
Take a look at the following example −
<?php
// request variables
$from = $_REQUEST["from"];
$emaila = $_REQUEST["emaila"];
$filea = $_REQUEST["filea"];
if ($filea) {
function mail_attachment ($from , $to, $subject, $message, $attachment){
$fileatt = $attachment; // Path to the file
$fileatt_type = "application/octet-stream"; // File Type
$start = strrpos($attachment, '/') == -1 ?
strrpos($attachment, '//') : strrpos($attachment, '/')+1;
// Filename that will be used for the file as the attachment
$fileatt_name = substr($attachment, $start,
strlen($attachment));
$email_from = $from; // Who the email is from
$subject = "New Attachment Message";
$email_subject = $subject; // The Subject of the email
$email_txt = $message; // Message that the email has in it
$email_to = $to; // Who the email is to
$headers = "From: ".$email_from;
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$msg_txt="\n\n You have recieved a new attachment message from $from";
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . "
boundary=\"{$mime_boundary}\"";
$email_txt .= $msg_txt;
$email_message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" . "Content-Type:text/html;
charset = \"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" .
$email_txt . "\n\n";
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" .
" name = \"{$fileatt_name}\"\n" . //"Content-Disposition: attachment;\n" .
//" filename = \"{$fileatt_name}\"\n" . "Content-Transfer-Encoding:
"base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n";
$ok = mail($email_to, $email_subject, $email_message, $headers);
if($ok) {
echo "File Sent Successfully.";
// delete a file after attachment sent.
unlink($attachment);
} else {
die("Sorry but the email could not be sent. Please go back and try again!");
}
}
move_uploaded_file($_FILES["filea"]["tmp_name"],
'temp/'.basename($_FILES['filea']['name']));
mail_attachment("$from", "[email protected]",
"subject", "message", ("temp/".$_FILES["filea"]["name"]));
}
?><html><head><script language = "javascript" type = "text/javascript">
function CheckData45() {
with(document.filepost) {
if(filea.value ! = "") {
document.getElementById('one').innerText = "Attaching File ... Please Wait";
}
}
}
</script></head><body><table width = "100%" height = "100%" border = "0"
cellpadding = "0" cellspacing = "0"><tr><td align = "center"><form name = "filepost" method = "post"
action = "file.php" enctype = "multipart/form-data" id = "file"><table width = "300" border = "0" cellspacing = "0"
cellpadding = "0"><tr valign = "bottom"><td height = "20">Your Name:</td></tr><tr><td><input name = "from" type = "text" id = "from" size = "30"></td></tr><tr valign = "bottom"><td height = "20">Your Email Address:</td></tr><tr><td class = "frmtxt2"><input name = "emaila" type = "text" id = "emaila" size = "30"></td></tr><tr><td height = "20" valign = "bottom">Attach File:</td></tr><tr valign = "bottom"><td valign = "bottom"><input name = "filea" type = "file" id = "filea" size = "16"></td></tr><tr><td height = "40" valign = "middle"><input name = "Reset2" type = "reset" id = "Reset2" value = "Reset"><input name = "Submit2" type = "submit" value = "Submit" onClick = "return CheckData45()"></td></tr></table></form><center><table width = "400"><tr><td id = "one"></td></tr></table></center></td></tr></table></body></html>
From PHP version 7 onwards, the session_start() function accepts an array of options to override the session configuration directives set in “php.ini”. The [session] session in “php.ini” defines the default values of various options.
The options, if provided, are in the form of an associative array of options that will override the currently set session configuration directives. The keys should not include the “session.” prefix.
Start an HTTP session
For example, you may start the HTTP session with the two session options defined as the parameters of session_start() function −
It specifies the cache control method used for session pages. It may be one of the following values: nocache, private, private_no_expire, or public. Defaults to nocache.
PHP session options provide extensive control over user sessions. Understanding and using these options allows you to design more secure and versatile web apps. To secure user information, always start your session with session_start() and handle session data properly.
A web session is the time duration between the time a user establishes connection with a server and the time the connection is terminated. Along with the cookies, the session variables make the data accessible across the various pages of an entire website.
During a session, the website maintains information about the user’s actions and preferences. The session data is populated in a super-global associative array $_SESSION.
To start a new session in PHP, you need to call the session_start() function.
Starting a Session
In order to enable access to session data, session_start() function must be invoked. session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
session_start(array$options=[]):bool
This function returns true if a session was successfully started, otherwise false.
PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers.
The session_id() function sets or retrieves a unique session ID.
session_id(?string$id=null):string|false
PHP will generate a random session ID, if the $id parameter is not given. You may specify your own ID instead. The function returns the session id for the current session or the empty string if there is no current session. On failure, it returns false.
The browser will show a random string as the output −
Session Id: mi3976f8ssethe9f04vq1ag6it
A cookie called PHPSESSID is automatically sent to the user’s computer to store unique session identification string.
A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.
The location of the temporary file is determined by a setting in the “php.ini” file called “session.save_path”.
Handling Session Variables
Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.
To create a new session variable, add a key-value pair in the $_SESSION array −
$_SESSION["var"]=value;
To read back the value of a session variable, you can use echo/print statements, or var_dump() or print_r() functions.
echo$_SESSION["var"];
To obtain the list of all the session variables in the current session, you can use a foreach loop to traverse the $_SESSION −
foreach($_SESSIONas$key=>$val)echo$key."=>".$val;
Example
The following example starts a session then register a variable called counter that is incremented each time the page is visited during the session.
Use the isset() function to check if a session variable is already set or not.
The following PHP script starts a session when it runs for the first time, and sets a session variable named counter. When the client revisits the same URL again, since the session variable is already set, the counter is incremented.
Refresh the browser multiple times to simulate repeated visits. The browser displays the counter −
Number of visits in this session: 5
Destroying a PHP Session
A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.
Here is an example to unset a single variable −
<?php
unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables −
<?php
session_destroy();
?>
You don’t need to call start_session() function to start a session when a user visits your site if you can set session.auto_start variable to 1 in php.ini file.
Example
The following PHP script renders a HTML form. The form data is used to create three session variables. A hyperlink takes the browser to another page, which reads back the session variables.