Sessions in PHP
Basis
Sessions are used to store information which can be used through-out the application for the entire time the user is logged in or running the application. Each time a user visits your website, you can create a session for that user to store information pertaining to that user.
In web applications, all the stored variables and objects are not globally available throughout all pages, so to tackle this problem sessions are utilized.
1.Starting Sessions-In PHP, information is stored in session variables. Before you can store any information in session variables, you must first start up the session using the session_start() function.
Ex
<?php
session_start();
?>
<html>
<body>
</body>
</html>
Outline
When you start a session a unique session id (PHPSESSID) for each visitor/user is created. You can access the session id using the PHP predefined constant PHPSESSID.
The code above starts a session for the user on the server, and assign a session id for that user’s session.
2.Storing information in a session-To store information is a session variable, you must use the predefined session variable $_SESSION.
Ex
<?php
session_start();
$_SESSION[“username”] = “gopal”;
$_SESSION[“password”] = “gopi123”;
?>
Outline
Here in this example we have store user’s name and their password in a session.
3.Retrieving stored session information-you can access the stored session information on any page.
Ex
<?php
session_start();
echo $_SESSION[“username”];
echo “<br />”;
echo $_SESSION[“password”];
?>
Output
gopal
gopi123
4.Destroying/deleting session information-Remember sessions are destroyed automatically after user leaves website or closes the browser, but if you wish to clear a session variable , you can simple use the unset() function to clean the session variable.
Ex
<?php
session_start();
unset($_SESSION[“username”]);
unset($_SESSION[“password”]);
?>
To completely destroy all session variables in one go, you can use the session_destroy() function.
Ex
<?php
session_destroy();
?>
Retrieving Cookie
Basis
If your cookie hasn’t expired yet, let’s retrieve it from the user’s PC using the aptly named $_COOKIE associative array. The name of your stored cookie is the key and will let you retrieve your stored cookie value!
Ex
<?php
if(isset($_COOKIE[‘lastVisit’]))
$visit = $_COOKIE[‘lastVisit’];
echo “Your last visit was – “. $visit;
?>
Outline
Here we have used isset function to be sure that our “lastVisit” cookie still exists on the user’s PC, if it does, then the user’s last visit is displayed.
Creating PHP Cookies
Basis
When you create a cookie, using the function setcookie, you must specify three arguments. These arguments are setcookie(name, value, expiration):
1. name: The name of your cookie. You will use this name to later retrieve your cookie.
2. value: The value that is stored in your cookie. Common values are username(string) and last visit(date).
3. expiration: The date when the cookie will expire and be deleted. If you do not set this expiration date, then it will be treated as a session cookie and be removed when the browser is restarted.
Ex
<?php
//Calculate 60 days in the future
//seconds * minutes * hours * days + current time
$inTwoMonths = 60 * 60 * 24 * 60 + time();
setcookie(‘lastVisit’, date(“G:i – m/d/y”), $inTwoMonths);
?>
Outline
In this example we will be creating a cookie that stores the user’s last visit to measure how often people return to visit our webpage. We want to ignore people that take longer than two months to return to the site, so we will set the cookie’s expiration date to two months in the future!
PHP Functions – Parameters
Basis
Another useful thing about functions is that you can send them information that the function can then use.
Ex
<?php
function greeting($name){
echo “Hello there “. $name . “!<br />”;
}
greeting(“arjun”);
greeting(“gopal”);
greeting(“sunil);
greeting(“rahul”);
?>
Output
Hello there arjun!
Hello there gopal!
Hello there sunil!
Hello there rahul!
Outline
However, if we were to use parameters, then we would be able to add some extra functionality! A parameter appears with the parentheses “( )” and looks just like a normal PHP variable.
Here we have created a function which creates a custom greeting based off of a person’s name.Our parameter will be the person’s name and our function will concatenate this name onto a greeting string.
When we use our greeting function we have to send it a string containing someone’s name, otherwise it will break.
PHP – Functions
Basis
A function is just a name we give to a block of code that can be executed whenever we need it.
Ex
<?php
function myfunction(){
echo “i am in function. <br />”;
}
echo “Hello world. <br />”;
myfunction();
myfunction();
?>
Output
Hello world.
i am in function.
i am in function.
Outline
– Always start your function with the keyword function.
– Remember that your function’s code must be between the “{” and the “}”.
– When you are using your function, be sure you spell the function name correctly.
Validating Form Input: Numbers
Basis
You want to make sure a number is entered in a form input box.
Ex
<?php
if (! ctype_digit($_POST[‘age’])) {
print ‘Your age must be a number bigger than or equal to zero.’;
}
?>
Outline
In this example age is checked to know whether the value entered by the user is a number or not.ctype_digit() is used to validate the form input.
Validate Email in PHP
Basis
Email id validation is the main part in HTML forms when a user enter an E-mail id.Here is a simple function to validate email.(To get full fledged option we should go for regular expression).
Ex
<?php
if(!filter_var(“subrat.cricket@gmail..com”, FILTER_VALIDATE_EMAIL))
{
echo(“Your E-mail id is not valid”);
}
else
{
echo(“Your E-mail id is valid”);
}
?>
Output
Your E-mail id is not valid
Outline
Here we used filter_var() to validate email with the filter mode FILTER_VALIDATE_EMAIL.
Deleting a file in PHP
Basis
If you wish to delete a file using PHP script,we can delete a file.
Ex
ex
<?php
$file = “file.php”;
if (unlink($file))
{
echo $file.”was deleted”;;
}
else
{
echo $file.”is not available”;
}
?>
Output
file.phpwas deleted
Outline
Here the unlink() function is used to delete the file.just we have to specify the file name under the parameter of the unlink() function. here the condition became true because the file was present and that was deleted successfully.
Date checkup in PHP
Basis
A particluar date can be checked whether the date is true or not.It returns true if the date is valid otherwise it returns false.
Ex
<?php
var_dump(checkdate(6,27,2010));
var_dump(checkdate(2,30,1977));
var_dump(checkdate(4,31,2009));
?>
Output
bool(true) bool(false) bool(false)
Outline
Here the checkdate function is used to find out the valid date.In the first parameter ‘6’ is given for month,’27’ is given for date,and ‘2010’ is the name of the year.For printing we have used var_dump because it often works on Boolean.
Spliting and combining an array
Basis
It is a simple example of spiting an arrya into number of new arrays.we can programme this using array_chunk function
Ex-1
<?php
$a=array(“Amit”=>”Songs”,”Santosh”=>”cooking”,”Nitesh”=>”Exercise”,”Rajesh”=>”Tv”);
print_r(array_chunk($a,2,true));
?>
Output
Array ( [0] => Array ( [Amit] => Songs [Santosh] => cooking ) [1] => Array ( [Nitesh] => Exercise [Rajesh] => Tv ) )
Outline
In the above example we have an array with 4 array elements with it’s respective keys.Here it was divided into two arrays.
in the array_chunk function,$a is the array name which is required to mention.Then the second parameter describes,how many array elements will be available under each array.true is given because the original array keys will be displayed.If false is given it won’t display.
Ex-2
<?php
$name =array(“Amit”,”Santosh”,”Nitesh”,”Rajesh”);
$hobby =array(“Singing”,”Cooking”,”Exercise”,”Tv”);
print_r(array_combine($name,$hobby));
?>
Output
Array ( [Amit] => Singing [Santosh] => Cooking [Nitesh] => Exercise [Rajesh] => Tv )
Outline
In the above example we haveĀ 2 arrays.Then it was combined with the help of array_combine function.This function takes the first array as key name and other arrays are the values.