SlideShare une entreprise Scribd logo
1  sur  114
UNIT IV
Regular Expressions, Session and Cookies
Contents
Transformation of Arrays – Stacks and Queues – Translating between
Variables and Arrays – Sorting – Printing Functions for Visualizing
Arrays – Tokenizing and Parsing Functions – Regular Expressions –
Advanced String Functions – Session – Session in PHP – Session
Functions – Cookies
Transformation of Arrays
PHP offers a host of functions for manipulating your data once you have it nicely stored in an array
1.Retrieving keys and values
● The array_keys() function returns the keys of its input array in the form of a new array where
the keys are the stored values.
● The keys of the new array are the usual automatically incremented integers, starting from 0.
● The array_values() Takes a single array argument and returns a new array where the new
values are the original values of the input array, and the new keys are the integers
incremented from zero.
● The array_count_values() Takes a single array argument and returns a new array where the
new keys are the old array’s values, and the new values are a count of how many times that
original value occurred in the input array.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$fruits = array("10"=>"Apple", "20"=>"Mango", "30"=>"Orange", "40"=>"Orange");
echo "array keys<br>";
print_r(array_keys($fruits));
echo "<br>";
echo "array values<br>";
print_r(array_values($fruits));
echo "<br>count values<br>";
print_r(array_count_values($fruits));
?>
</body>
</html>
Output
2.Flipping, reversing, and shuffling
● The array_flip() function flips/exchanges all keys with their
associated values in an array.
● array_reverse() takes a single array argument and changes the
internal ordering of the key/value pairs to reverse order.
Numerical keys will also be renumbered.
● The shuffle() function Takes a single array argument and
randomizes the internal ordering of key/value pairs. Also
renumbers integer keys to match the new ordering.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$fruits = array("0"=>"Apple", "1"=>"Mango", "2"=>"Orange");
echo "<b>Array Reverse<br></b>";
print_r(array_reverse($fruits));
echo "<b><br>Array flip<br></b>";
print_r(array_flip($fruits));
echo "<b><br>Array shuffle<br></b>";
shuffle($fruits);
print_r($fruits);
?>
</body>
</html>
Output
3.Merging, padding, slicing, and splicing
● The array_merge() function merges one or more arrays into one array.
○ Takes two array arguments, merges them, and returns the new array,
which has (in order) the first array’s elements and then the second
array’s elements
● array_pad() -Takes three arguments: an input array, a pad size, and a value to
pad with.
○ The array_pad() function inserts a specified number of elements, with a
specified value, to an array.
Example:(array merge)
<!DOCTYPE html>
<html>
<body>
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
</body>
</html>
Output
Example:(array pad)
<!DOCTYPE html>
<html>
<body>
<?php
$a=array("red","green");
print_r(array_pad($a,-5,"blue"));
echo "<br>";
$b=array("red","green");
print_r(array_pad($b,5,"blue"));
?>
</body>
</html>
Output
● The array_slice() function returns selected parts of an array.
○ array_slice(array, start, length, preserve)
■ array→Specifies an array
■ start→Numeric value. Specifies where the function will start the
slice.
■ length→Numeric value. Specifies the length of the returned array.
■ Preserve→optioal. Specifies if the function should preserve or reset
the keys.
Possible values:
● true - Preserve keys
● false - Default. Reset keys
Example:(array slice)
<!DOCTYPE html>
<html>
<body>
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
echo "<br>";
print_r(array_slice($a,0,3));
echo "<br>";
print_r(array_slice($a,-3,3));
echo "<br>";
print_r(array_slice($a,2,3,true));
?>
</body>
</html>
Output
The array_splice() function removes selected elements from an array and
replaces it with new elements. The function also returns an array with the
removed elements.
array_splice(array, start, length, array)
● array→Specifies an array
● Start→ Numeric value. Specifies where the function will start
removing elements.
● Length→ Specifies how many elements will be removed, and also
length of the returned array.
● Array→ Specifies an array with the elements that will be inserted
to the original array.
Example:(array splice)
<!DOCTYPE html>
<html>
<body>
<?php
$a1=array("red","green","blue","yellow");
$a2=array("purple","orange");
array_splice($a1,0,2,$a2);
print_r($a1);
echo "<br>";
print_r(array_splice($a1,0,2,$a2));
echo "<br>";
array_splice($a1,1,0,$a2);
print_r($a1);
?>
</body></html>
Output
Stacks and Queues
● Stacks and queues are abstract data structures, frequently used in computer
science
Stack:
● A stack is a container that stores values and supports last-in–first-out (LIFO)
behavior.
● This means that the stack maintains an order on the values you store, and the
only way you can get a value back is by retrieving (and removing) the most
recently stored value
● The act of adding into the stack is called pushing a value onto the stack,
whereas the act of taking off the top is called popping the stack
Stack functions:
● The stack functions are array_push() and array_pop().
● The array_push() function takes an initial array argument and then any
number of elements to push onto the stack.
● The elements will be inserted at the end of the array, in order from
left to right.
● The array_pop() function takes such an array and removes the element
at the end, returning it.
Queue:
A queue is similar to a stack, but its behavior is first in, first out (FIFO).
functions:
array_shift:
The array_shift() function removes the first element from an array, and
returns the value of the removed element.
array_unshift:
The array_unshift() function inserts new elements to an array. The new
array values will be inserted in the beginning of the array.
Example:(stack push and pop)
<!DOCTYPE html>
<html>
<body>
<?php
$a=array();
echo "push operation<br>";
array_push($a,"blue","yellow","red");
print_r($a);
echo "<br> pop operation<br>";
array_pop($a);
array_pop($a);
print_r($a);
?></body>
</html>
Output
Example:(queue array insert and delete)
<html>
<body>
<?php
$a=array();
echo "queue insertion<br>";
array_unshift($a,"blue");
array_unshift($a,"red");
array_unshift($a,"yellow");
print_r($a);
echo "<br>pop operation<br>";
array_pop($a);
print_r($a);
?>
</body></html>
Output
Example:(queue array insert and delete)
<html>
<body>
<?php
$a=array();
echo "queue insertion<br>";
array_push($a,"blue");
array_push($a,"red");
array_push($a,"yellow");
print_r($a);
echo "<br>pop operation<br>";
array_shift($a);
print_r($a);
?>
</body></html>
Output
Translating between Variables and Arrays
● PHP offers a couple of unusual functions for mapping between the name/value
pairs of regular variable bindings and the key/value pairs of an array.
● The compact() function translates from variable bindings to an array, and the
extract() function goes in the opposite direction
compact()
● Takes a specified set of strings, looks up bound variables (if any) in the current
environment that are named by those strings, and returns an array where the
keys are the variable names, and the values are the corresponding values of
those variables.
● It takes any number of arguments
extract()
● Takes an array and imports the key/value pairs into the current variable-binding
context.
● The array keys become the variable names, and the corresponding array values
become the values of the variables.
● Any keys that do not correspond to a legal variable name will not produce an
assignment.
Example:(compact)
<?php
$firstname = "arun";
$lastname = "karthik";
$age = "41";
$result = compact("firstname", "lastname", "age");
print_r($result);
?>
Output
Example:(extract)
<!DOCTYPE html>
<html>
<body>
<?php
$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($my_array);
echo $a."<br>";
echo $b."<br>";
echo $c."<br>";
?></body></html>
Output
Sorting
● PHP offers a host of functions for sorting arrays
● PHP offers variants of the sorting functions for each of these behaviors and
also allows sorting in ascending or descending order and by user-supplied
ordering functions
Sorting functions:
● asort()
● arsort()
● ksort()
● krsort()
● sort()
● rsort()
● uasort()
● uksort()
● usort()
Sorting functions
● asort() (associative array)
The asort() function sorts an associative array in ascending order, according to
the value.
● arsort()(associative array)
arsort() function sorts an associative array in descending order, according to
the value.
● ksort()(associative array)
The ksort() function sorts an associative array in ascending order, according to
the key.
● krsort()(associative array)
The krsort() function sorts an associative array in descending order, according
to the key.
Example:asort() and arsort()
<!DOCTYPE html>
<html>
<body>
<?php
$age=array("Peter"=>"35","Ben"=>"47","Joe"=>"43");
echo "asort<br>";
asort($age);
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
echo "<br>arsort<br>";
arsort($age);
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?></body>
</html>
Output
Example:ksort() and krsort()
<!DOCTYPE html>
<html>
<body>
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "ksort<br>";
ksort($age);
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
echo "<br>krsort<br>";
krsort($age);
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
</body>
</html>
Output
Sorting functions
● sort()
The sort() function sorts an indexed array in ascending order.
● rsort()
The rsort() function sorts an indexed array in descending order.
● usort()
The usort() function sorts an array using a user-defined comparison function.
● uasort() (associative array)
The uasort() function sorts an array by values using a user-defined comparison
function.
● uksort()(associative array)
The uksort() function sorts an array by keys using a user-defined comparison
function.
Example:sort() and rsort
<!DOCTYPE html>
<html>
<body>
<?php
$fruits=array("Mango","Orange","Apple","Banana");
echo "sort<br>";
sort($fruits);
for($i=0;$i<count($fruits);$i++)
{
echo $fruits[$i];
echo "<br>";
}
echo "<br>rsort<br>";
rsort($fruits);
for($i=0;$i<count($fruits);$i++)
{
echo $fruits[$i];
echo "<br>";
}
?>
</body>
</html>
Output
Example:usort()
<?php
$arr=array(6,20,10,18);
echo "Ascending order<br>";
function sorting($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
usort($arr,"sorting");
print_r($arr);
echo "<br>Descending order<br>";
function mysort($a,$b)
{
if ($a==$b) return 0;
return ($a>$b)?-1:1;
}
usort($arr,"mysort");
print_r($arr);
Output
Note:
ascending order:1 when a>b or -1 when a<b
descending order: -1 when a>b or 1 when a<b
Example:uasort()
<?php
$arr=array("a"=>4,"b"=>2,"g"=>8,"d"=>6,"e"=>1,"f"=>9);
echo "Ascending order<br>";
function sorting($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
uasort($arr,"sorting");
print_r($arr);
echo "<br>Descending order<br>";
function mysort($a,$b)
{
if ($a==$b) return 0;
return ($a>$b)?-1:1;
}
uasort($arr,"mysort");
print_r($arr);
?>
Output
Note:
ascending order:1 when a>b or -1 when a<b
descending order: -1 when a>b or 1 when a<b
Example:uksort()
<?php
$arr=array("a"=>4,"b"=>2,"g"=>8,"d"=>6,"e"=>1,"f"=>9);
echo "Ascending order<br>";
function sorting($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
uksort($arr,"sorting");
print_r($arr);
echo "<br>Descending order<br>";
function mysort($a,$b)
{
if ($a==$b) return 0;
return ($a>$b)?-1:1;
}
uksort($arr,"mysort");
print_r($arr);
?>
Output
Note:
ascending order:1 when a>b or -1 when a<b
descending order: -1 when a>b or 1 when a<b
Printing Functions for Visualizing Arrays
● PHP offers a couple of printing functions that are very useful for visualizing and
debugging arrays, especially multidimensional arrays
● The first function is print_r(), which is short for print recursive.
○ This takes an argument of any type and prints it out, which includes printing
all its parts recursively.
● The var_dump() function is similar, except that it prints additional information
about the size and type of the values it discovers.
Example:(print_r and var_dump())
<html>
<body>
<?php
$my_array = array("10" =>"apple",“20” => array("30" => "banana"));
echo "print_r function<br>";
print_r($my_array);
echo "<br>var_dump function<br>";
var_dump($my_array);
?>
</body>
</html>
Output
Tokenizing and Parsing Functions
● The process of breaking up a long string into words is called tokenizing
● PHP offers a special function for this purpose, called strtok().
● strtok() function takes two arguments:
○ the string to be broken up into tokens and
○ a string containing all the delimiters
● The explode() function breaks a string into an array.
● The explode() function takes two arguments:
○ a separator string and the string to be separated.
○ It returns an array where each element is a substring between instances of the
separator in the string to be separated
● The implode() method joins array elements with a string segment
that works as a glue
● It takes two arguments:
○ a “glue”
○ string
● string implode (glue ,pieces)
Example:(token)
<!DOCTYPE html>
<html>
<body>
<?php
$string = "Hello world. Beautiful day today.";
$token = strtok($string, " ");
while ($token)
{
echo "$token<br>";
$token = strtok(" ");
}
?>
</body></html>
Output
Example:(explode)
<!DOCTYPE html>
<html>
<body>
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
</body>
</html>
Output
Example:(implode)
<!DOCTYPE html>
<html>
<body>
<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
?>
</body>
</html>
Output
Why Regular Expressions? Regex in PHP
● Regular expressions (or regex) are patterns for string matching, with
special wildcards that can match entire portions of the target string.
● There are two broad classes of regular expression that PHP works
with:
○ POSIX(extended) regex and
○ Perl-compatible regex
POSIX regex
● POSIX→Portable Operating System Interface for Unix
● Some regular expressions in PHP are like arithmetic expressions which
are called POSIX regular expressions.
● Some times, complex expression are created by combining various
elements or operators in regular expressions.
Example:
● [0-9]-->It matches any decimal digit from 0 through 9.
● [a-z]-->It matches any character from lower-case a through lowercase z.
● [A-Z]-->It matches any character from uppercase A through uppercase
Z.
POSIX Regular Expression Functions
● ereg()-->Takes two string arguments and an optional third-array
argument. The first string is the POSIX-style regular expression
pattern, and the second string is the target string that is being matched
● ereg_replace()--> Takes three arguments: a POSIX regular expression
pattern, a string to do replacement with, and a string to replace into
● eregi()-->Identical to ereg(), except that letters in regular expressions
are matched in a case-independent way.
● eregi_replace()-->Identical to ereg_replace(), except that letters in
regular expressions are matched in a case-independent way.
Example(ereg())
<?php
$str = "www.gmail.com";
$pattern = "^www.[a-z]+.com$";
if(ereg($pattern, $str))
echo “match found”;
else
echo “not found”;
?>
Example(ereg_replace())
<?php
$copy_date = "Copyright 1999";
$copy_date = ereg_replace("([0-9]+)", "2000", $copy_date);
print $copy_date;
?>
Output:
Match found
Output:
Copyright2000
● split()-->
○ The split() function will divide a string into various elements,
the boundaries of each element based on the occurrence of
pattern in string.
○ Returns an array of strings after splitting up a string.
● spliti()
○ Case-independent version of split().
Example(ereg())
<?php
$str = "www.gmail.com";
$pattern = "^www.[a-z]+.com$";
if(ereg($pattern, $str))
echo “match found”;
else
echo “not found”;
?>
Example(ereg_replace())
<?php
$copy_date = "Copyright 1999";
$copy_date = ereg_replace("([0-9]+)", "2000", $copy_date);
print $copy_date;
?>
Output:
Match found
Output:
Copyright2000
Example(split())
<?php
$ip = "123.456.789.000"; // some IP address
$iparr = split (".", $ip);
print "$iparr[0] <br />";
print "$iparr[1] <br />" ;
print "$iparr[2] <br />" ;
print "$iparr[3] <br />" ;
?>
Output:
123
456
789
000
Perl-Compatible Regular Expressions
● Perl-compatible regex in PHP has a completely distinct set of
functions and a slightly different set of rules for patterns.
● Perl-compatible regex patterns are always bookended by one
particular character, which must be the same at beginning and end,
indicating the beginning and end of the pattern
● The Perl compatible pattern:
● /pattern/
● Example: $my_pattern = ‘/pattern/‘;
● preg_match()-->Takes a regex pattern as first argument, a string to
match against as second argument, and an optional array variable for
returned matches. Returns 0 if no matches are found, and 1 if a match is
found
● preg_match_all()--> Like preg_match(), except that it makes all possible
successive matches of the pattern in the string, rather than just the
first. The return value is the number of matches successfully made.
● preg_split()-->Takes a pattern as first argument and a string to match as
second argument. Returns an array containing the string divided into
substrings, split along boundary strings matching the pattern
● preg_replace()-->Takes a pattern, a replacement string, and a string to
modify. Returns the result of replacing every matching portion of the
Example(preg_match())
<?php
$str = "www.gmail.com";
$pattern = "/www.[a-z]/";
if(preg_match($pattern, $str))
echo "match found";
else
echo "match not found";
?>
Output
Example(preg_match_all())
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
if(preg_match_all($pattern, $str, $matches)) {
print_r($matches);
}
?>
Output
Example(preg_split())
<?php
$date = "1970-01-01 00:00:00";
$pattern = "/[-s:]/";
$components = preg_split($pattern, $date);
print_r($components);
?>
Output
Example(preg_replace())
<?php
$str = 'hai welcome!';
$pattern = '/hai/i';
echo preg_replace($pattern, 'hello', $str);
?>
Output
● preg_replace_callback()
Like preg_replace(), except that the second argument is the name of a
callback function, rather than a replacement string. This function should return
the string that is to be used as a replacement.
● preg_grep()
The preg_grep() function returns an array containing only elements from the
input that match the given pattern.
● preg_quote()
The preg_quote() function adds a backslash to characters that have a special
meaning in regular expressions so that searches for the literal characters can
be done.
Example(preg_replace_callback())
<?php
function countLetters($matches) {
return $matches[0] . '(' . strlen($matches[0]) . ')';
}
$input = "Welcome 2023";
$pattern = '/[a-z]/';
$result = preg_replace_callback($pattern, 'countLetters', $input);
echo $result;
?>
Output
Example(preg_grep())
<?php
$input = array("Red", "Pink", "Green", "Blue", "purple");
$result = preg_grep("/^p/i", $input);
print_r($result);
?>
Output
Example(preg_quote())
<?php
$keywords = '$40 for a mobile phone';
$keywords = preg_quote($keywords);
echo $keywords;
?>
Output
$40 for a mobile phone
Sample Program(Validation for Aadhar, Email and Pan card)
<html>
<body>
<?php
function isValidAdhaar($s){
$pattern = '/^[2-9]{1}[0-9]{3}s[0-9]{4}s[0-9]{4}$/';
return preg_match($pattern,$s);
}
function isValidEmail($s){
$pattern = '/^([a-z0-9.]+@+[a-z]+(.)+[a-z]{2,3})$/';
return preg_match($pattern,$s);
}
function isValidPan($s){
$pattern = '/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/';
return preg_match($pattern,$s);
}
echo isValidAdhaar('3555 0143 1289')."<BR>";
echo isValidAdhaar('0556 013 1289')."<BR>";
echo isValidEmail('avicky@gmail.com')."<BR>";
echo isValidEmail('vickygmail@com')."<BR>";
echo isValidPan('BZIPY1430V')."<BR>";
echo isValidPan('BZIPY14370V')."<BR>";
?>
</body></html>
Output
Sample Program(replace)
<!DOCTYPE html>
<html>
<body>
<?php
function toKecMail($s){
$pattern = '/@+[a-z]{2,}.{1}/i';
return preg_replace($pattern,'@kongu.',$s);
}
echo toKecMail('avicky@gmail.com')."<BR>";
echo toKecMail('vickygmail@com')."<BR>";
?>
</body>
</html>
Output
Advanced String Functions
HTML functions→PHP offers a number of web-specific functions for string manipulation
htmlspecialchars()
The htmlspecialchars() function converts some predefined characters to HTML entities.
The predefined characters are:
● & (ampersand) becomes &amp;
● " (double quote) becomes &quot;
● ' (single quote) becomes &#039;
● < (less than) becomes &lt;
● > (greater than) becomes &gt;
htmlentities()
Goes further than htmlspecialchars(), in that it replaces all characters that have a
corresponding HTML entity with that HTML entity.
get_html_translation_table()
The get_html_translation_table() function returns the translation table used by
the htmlentities() and htmlspecialchars() functions.
nl2br()
The nl2br() function inserts HTML line breaks (<br> or <br />) in front of each
newline (n) in a string.
strip_tags()
The strip_tags() function strips a string from HTML, XML, and PHP tags.
Example: (htmlspecialchars)
<!DOCTYPE html>
<html>
<body>
<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
?>
</body>
</html>
Output
Example: (htmlentities)
<!DOCTYPE html>
<html>
<body>
<?php
$str = '<a href="https://www.w3schools.com">Go to w3schools.com</a>';
echo htmlentities($str);
?>
</body>
</html>
Output
Example: (translation table)
// HTML_SPECIALCHARS is default.
<!DOCTYPE html>
<html>
<body>
<?php
print_r (get_html_translation_table());
?>
</body>
</html>
Output
Example: ( nl2br)
<!DOCTYPE html>
<html>
<body>
<?php
echo nl2br("One line.nAnother line.");
?>
</body>
</html>
Output
Example: ( strip_tags)
<!DOCTYPE html>
<html>
<body>
<?php
echo strip_tags("Hello <b>world!</b>");
?>
</body>
</html>
Output
Hashing using MD5
● The MD5 (message-digest algorithm) hashing algorithm is a one-way cryptographic function
that accepts a message of any length as input and returns as output a fixed-length digest
value to be used for authenticating the original message
● MD5 is a string-processing algorithm that is used to produce a digest or signature of whatever
string it is given.
● The algorithm boils its input string down into a fixed-length string of 32 hexadecimal values
(0,1,2, . . . 9,a,b, . . . f).
● MD5 has some very useful properties:
○ MD5 always produces the same output string for any given input string, so it is not
appropriate to use MD5 to store passwords.
○ The fixed-length results of applying MD5 are very evenly spread over the range of
possible values.
○ It may be possible produce an input string corresponding to a given MD5 output string or
to produce two inputs that yield the same output.
● PHP’s implementation of MD5 is available in the function md5(), which takes a string as
input and produces the 32-character digest as output
● Example:
<!DOCTYPE html>
<html>
<body>
<?php
$str = "Hello";
echo md5($str);
echo "<br>";
echo md5("Hai");
?>
</body>
</html>
Output:
Strings as character collections
● PHP offers some pretty specialized functions that treat strings more as collections of
characters than as sequences.
strspn()
The strspn() function returns the number of characters found in the string that contains
only characters from the charlist parameter.Takes two string arguments.
strcspn()
The strcspn() function returns the number of characters (including whitespaces) found in a
string before any part of the specified characters are found.
count_chars()
The count_chars() function returns information about characters used in a string
0 - an array with the ASCII value as key and number of occurrences as value
1 - an array with the ASCII value as key and number of occurrences as value, only lists
occurrences greater than zero
2 - an array with the ASCII value as key and number of occurrences as value, only lists
occurrences equal to zero are listed
3 - a string with all the different characters used
4 - a string with all the unused characters
● Example:
<!DOCTYPE html>
<html>
<body>
<?php
$twister = "Peter Piper picked a peck of pickled peppers";
$charset = "Peter picked a";
echo strspn($twister,$charset);
?>
</body>
</html>
Output: 26
● Example:
<!DOCTYPE html>
<html>
<body>
<?php
$t = "Welcome to our college";
$c = "t";
echo strcspn($t,$c);
?>
</body>
</html>
Output: 8
● Example:
<!DOCTYPE html>
<html>
<body>
<?php
$str = "Hello World!";
echo count_chars($str,3);
?>
</body>
</html>
Output: !HWdelor
String similarity functions
● The levenshtein() function is an inbuilt function in PHP.
● The levenshtein() function is used to calculate the levenshtein distance between two strings.
● The Levenshtein distance between two strings is defined as the minimum number of characters
needed to insert, delete or replace in a given string $string1 to transform it to a string $string2.
● Syntax:
○ levenshtein(string1,string2,insert,replace,delete)
■ String1 Required. First string to compare
■ String2 Required. Second string to compare
■ Insert Optional. The cost of inserting a character. Default is 1
■ Replace Optional. The cost of replacing a character. Default is 1
■ Delete Optional. The cost of deleting a character. Default is 1
Example:
<!DOCTYPE html>
<html>
<body>
<?php
echo levenshtein("Hello World","ello World");
echo "<br>";
echo levenshtein("Tim","Time");
echo "<br>";
echo levenshtein("boy","chefboyardee”);
echo "<br>";
echo levenshtein("never","clever");
?>
</body>
</html>
Output
Session
Session
● A session is a way to store information (in variables) to be used across
multiple pages.
● An alternative way to make data accessible across the various pages of an
entire website is to use a PHP Session.
● 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.
● In general, session refers to a frame of communication between two
medium.
Sessions in PHP
● A PHP session is used to store user information on the server for later
use (i.e. username, shopping cart items, etc).
● However, this session information is temporary and is usually deleted
very quickly after the user has left the website that uses sessions.
How Sessions Work in PHP?
● Session tracking (that is, detecting whether two separate script
invocations are, in fact, part of the same user session).
● Storing information in association with a session.
Session Mechanism
● A PHP session is used to store data on a server rather than the computer of the user.
● Session identifiers or SID is a unique number which is used to identify every user in a
session based environment.
● The SID is used to link the user with his information on the server like posts, emails
etc.
Where is the data really stored?
● There are two things that the session mechanism must hang onto:
○ the session ID itself and
○ any associated variable bindings.
● The session ID is either stored as a cookie on the browser's machine, or it is
incorporated into the GET/POST arguments submitted with page requests.
1.Starting a PHP Session
● The first step is to start up a session.
● After a session is started, session variables can be created to store
information.
● The PHP session_start() function is used to begin a new session.
● It also creates a new session ID for the user.
● Below is the PHP code to start a new session:
<?php
session_start();
?>
2.Storing Session Data
● Session data in key-value pairs using the $_SESSION[] superglobal
array.
● The stored data can be accessed during lifetime of a session.
3.Accessing Session Data
● Data stored in sessions can be easily accessed by firstly calling
session_start() and then by passing the corresponding key to the
$_SESSION associative array.
● Example:(start and set session variables)
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
$_SESSION["Name"] = "nithi";
$_SESSION["Rollno"] = "50";
echo "Session variables are set.";
?>
</body>
</html>
</html>
● Example:(Access session variables)
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Name is " . $_SESSION["Name"] . ".<br>";
echo "Rollnumber is " . $_SESSION["Rollno"] . ".";
?>
</body>
</html>
2.Destroying Certain Session Data:
● To delete only a certain session data,the unset feature can be used with
the corresponding session variable in the $_SESSION associative array.
3.Destroying Complete Session:
● The session_destroy() function is used to completely destroy a session.
The session_destroy() function does not require any argument.
● Example:(Delete certain session variables)
<?php
session_start();
if(isset($_SESSION["Name"]))
{
unset($_SESSION["Name"]);
echo "deleted sucessfully";
}
?>
● Example:(Delete complete session variables)
<?php
session_start();
session_destroy();
echo "deleted all the session variables";
?>
● PHP program to store page count:
<html>
<body>
<?php
session_start();
echo "<h1>welcome to our website</h1>";
if(isset($_SESSION['count']))
$_SESSION['count'] = $_SESSION['count']+1;
else
$_SESSION['count']=1;
echo"no of times visited = ".$_SESSION['count'];
?>
</body></html>
Session Functions
● session_start()
○ A session is started with the session_start() function.
○ Session variables are set with the PHP global variable: $_SESSION.
○ Takes no arguments
● session_register()($_SESSION)
○ session_register() accepts a variable number of arguments, any of which can be either a
string holding the name of a variable or an array consisting of variable names or other
arrays.
○ For each name, session_register() registers the global variable with that name in the
current session.
○ Example : session_register(‘username’)
○ Session variable can also be created by simply setting the appropriate member of the
$_SESSION array.
session_unregister()
○ Unregister a global variable from the current session
○ Takes a string variable name as argument and unregisters the corresponding
variable from the session
○ If $_SESSION is used, use unset() to unregister a session variable.
session_is_registered()
○ Find out whether a global variable is registered in a session
○ Takes a variable-name string and tests whether a variable with a given variable
name is registered in the current session, returning TRUE if so and FALSE if not
○ If $_SESSION is used, use isset() to check a variable is registered in
$_SESSION.
session_destroy()
○ session_destroy() destroys all of the data associated with the
current session.
○ It destroys the whole session rather destroying the variables.
session_unset()
○ The session_unset() function frees all session variables currently
registered.
○ It deletes only the variables from session and session still exists.
Only data is truncated.
session_write_close()
● Write session data and end session
● Manually close session and release write lock on data file.
Example:
<?php
session_start();
$_SESSION["A"] = "Hello";
session_write_close();
echo "<br>";
print("Value: ".$_SESSION["A"]);
?>
Session_name()
○ The session_name() function is used to name the current session or,
retrieve the name of the session.
<?php
//Starting the session
session_name("mysession");
session_start();
$name = session_name();
print("Session Name: ".$name);
?>
session_module_name()
● If given no arguments, returns the name of the module that is responsible for handling session
data.
● This name currently defaults to ‘files’, meaning that session bindings are serialized and then
written to files in the directory named by the function session_save_path().
session_save_path()
● session_save_path() returns the path of the current directory used to save session data.
<?php
session_save_path('E:KECSUBJECTS');
$res = session_save_path();
session_start();
echo "path: ".$res;
?>
session_id()
Takes no arguments and returns a string, which is the unique key corresponding to a
particular session. If given a string argument, will set the session ID to that string.
<?php
session_start();
$id = session_id();
print("Session Id: ".$id);
?>
session_regenerate_id()
● It generates a new session id and updates the current one with the newly created one.
<?php
session_id("my-id");
session_start();
print("Id: ".session_id());
session_regenerate_id();
echo "<br>";
print("New Session Id: ".session_id());
?>
session_encode()
This function encodes the data in the current session and returns it in the form of encoded
serialized string.
session_decode()
It accepts a of encoded serialized session string and decodes it and stores it in the $_SESSION
variable.
Example:
<?php
session_start();
$_SESSION['data'] = "This is sample";
$res = session_encode();
echo "Encoded Data: ". $res."<br>";
session_decode($res);
print_r($_SESSION);
?>
session_set_cookie_params()
It is used to set the session cookie parameters defined in the php.ini file
session_get_cookie_params()
It is used to retrieve the session cookie parameters and it returns an array which contains
the current session cookie parameter values.
<?php
session_set_cookie_params(30 * 60, "/", "mypage", );
$res = session_get_cookie_params();
session_start();
print_r($res);
?>
Configuration Issues
Sample Code
<?php
session_start();
?>
<HTML><HEAD><TITLE>Greetings</TITLE></HEAD>
<BODY>
<H2>Welcome to the Center for Content-free Hospitality</H2>
<?php
if (!IsSet($_SESSION['visit_count']))
{
echo "Hello, you must have just arrived.Welcome!<BR>";
$_SESSION['visit_count'] = 1;
}
else
{
$visit_count = $_SESSION['visit_count'] + 1;
echo "Back again are you? That makes $visit_count times now"."(not that anyone’s counting)<BR>";
$_SESSION['visit_count'] = $visit_count;
}
$self_url = $_SERVER['PHP_SELF'];
$session_id = SID;
if (IsSet($session_id) && $session_id)
{
$href = "$self_url?$session_id";
}
else {
$href = $self_url;
}
echo "<BR><A HREF=“$href“>Visit us again</A> sometime";
?>
</BODY></HTML>
Cookies
● A cookie is a small piece of information that is retained on the client machine,
either in the browser’s application memory or as a small file written to the
user’s hard disk.
● It contains a name/value pair setting a cookie means associating a value with a
name and storing that pairing on the client side.
● Getting or reading a cookie means using the name to retrieve the value.
● It is used to keep track of information such as a username that the site can
retrieve to personalize the page when the user visits the website next time.
● PHP cookie is a small piece of information which is stored at client browser.
It is used to recognize the user.
● Cookie is created at server side and saved to client browser. Each time when
client sends request to the server, cookie is embedded with request. Such
way, cookie can be received at the server side.
The setcookie() function
● In PHP, cookies are set using the setcookie() function
● Once cookie is set, you can access it by $_COOKIE superglobal variable.
Syntax: setcookie(name, value, expire, path, domain, secure, httponly);
Arguments to setcookie()
Argument Name Expected Type Meaning
name string The name of your cookie
value string The value you want to store in the cookie
expire int Specifies when this cookie should expire.
A value of 0 (the default)
means that it should last until the
browser is closed.
Argument Name Expected Type Meaning
path string In the default case, any page within the web root folder
would see this named cookie. Setting the path to a
subdirectory (for example, “/forum/”) allows
distinguishing cookies that have the same name but are
set by different sites or subareas of
the web server
httponly boolean Cookies set with this flag are only sent through HTTP
requests. Default is FALSE.
domain string In the default case, no check is made against the domain
requested by the client. If this argument is nonempty,
then the
domain must match.
secure boolean
(TRUE (1) or
FALSE (0))
Defaults to 0 (FALSE). If this argument is 1 or TRUE, the
cookie will only be sent over a secure socket (aka SSL or
HTTPS) connection.
Example: (PHP Create/Retrieve a Cookie)
<?php
$name = "user";
$value = "Nithi";
setcookie($name, $value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$name]))
{
echo "Cookie is not set!";
} else
{
echo "Cookie is created<br>";
echo "Value is: " . $_COOKIE[$name];
}
?>
</body>
</html>
Deleting Cookies
● Deleting a cookie is easy.
● Simply call setcookie(), with the exact same arguments as when you set
it, except the value, which should be set to an empty string.
● This does not set the cookie’s value to an empty string — it actually
removes the cookie
● Another method to clear cookies is to set the expiration time in the past.
Example: (Delete a Cookie)
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Cookie pitfalls
1.Sending something else first
● The single most common error in using cookies is trying to set a cookie after some regular
HTML content has already been generated
● Cookies must be sent before any output from your script (this is a protocol restriction).
● This requires that you place calls to this function prior to any output, including <html> and
<head> tags as well as any whitespace.
● As soon as any regular content is generated, PHP figures that it must already know about all
headers of interest, and so it sends them off and then begins the transmission of HTML
content.
● If it encounters a cookie later on, it is too late, and an error is generated.
2.Reverse-order interpretation
● As with most HTTP commands, calls to setcookie() may actually be executed in the opposite
order from the way that they appear in your PHP script, but this depends on the particular
browser your user is running and the version of PHP you’re using.
● This means that a pair of successive statements like the following probably have the counter
intutive result of leaving the “mycookie” cookie with no value, because the unsetting statement
is executed second.
○ setcookie(“mycookie”);// get rid of the old value (WRONG)
○ setcookie(“mycookie”, “newvalue”);// set the new value (WRONG)
● There is no need to remove a cookie before setting it to a different value — simply set it to
the desired new value. Among other things, this means that the confusing reverse order of
3.Cookie refusal
● Finally, be aware that setcookie() makes no guarantees that any cookie data will, in fact, be
accepted by the client browser
● The setcookie() function does not even return a value that indicates acceptance or refusal of
the cookie
● First, the script executes (including the setcookie() call), with the result that a page complete
with HTTP headers is sent to the client machine.
● At this point, the client browser decides how to react to the cookie-setting attempt.
● Not until the client generates another request can the server receive the cookie’s value and
detect whether the cookie-setting attempt was successful

Contenu connexe

Similaire à REGULAR EXPRESSIONS, SESSION AND COOKIES

PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & ArraysHenry Osborne
 
Array String - Web Programming
Array String - Web ProgrammingArray String - Web Programming
Array String - Web ProgrammingAmirul Azhar
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netProgrammer Blog
 
20220112 sac v1
20220112 sac v120220112 sac v1
20220112 sac v1Sharon Liu
 
New SPL Features in PHP 5.3
New SPL Features in PHP 5.3New SPL Features in PHP 5.3
New SPL Features in PHP 5.3Matthew Turland
 
Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvvLecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvvZahouAmel1
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressAlena Holligan
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128PrinceGuru MS
 
PHP and MySQL with snapshots
 PHP and MySQL with snapshots PHP and MySQL with snapshots
PHP and MySQL with snapshotsrichambra
 

Similaire à REGULAR EXPRESSIONS, SESSION AND COOKIES (20)

Php array
Php arrayPhp array
Php array
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
07-PHP.pptx
07-PHP.pptx07-PHP.pptx
07-PHP.pptx
 
07-PHP.pptx
07-PHP.pptx07-PHP.pptx
07-PHP.pptx
 
Array String - Web Programming
Array String - Web ProgrammingArray String - Web Programming
Array String - Web Programming
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.net
 
20220112 sac v1
20220112 sac v120220112 sac v1
20220112 sac v1
 
07 php
07 php07 php
07 php
 
Presentaion
PresentaionPresentaion
Presentaion
 
New SPL Features in PHP 5.3
New SPL Features in PHP 5.3New SPL Features in PHP 5.3
New SPL Features in PHP 5.3
 
SPL, not a bridge too far
SPL, not a bridge too farSPL, not a bridge too far
SPL, not a bridge too far
 
Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvvLecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
 
Php2
Php2Php2
Php2
 
Unit 2-Arrays.pptx
Unit 2-Arrays.pptxUnit 2-Arrays.pptx
Unit 2-Arrays.pptx
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPress
 
Sorting arrays in PHP
Sorting arrays in PHPSorting arrays in PHP
Sorting arrays in PHP
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
PHP and MySQL with snapshots
 PHP and MySQL with snapshots PHP and MySQL with snapshots
PHP and MySQL with snapshots
 

Plus de DrDhivyaaCRAssistant (13)

UNIT 1 (8).pptx
UNIT 1 (8).pptxUNIT 1 (8).pptx
UNIT 1 (8).pptx
 
Unit – II (1).pptx
Unit – II (1).pptxUnit – II (1).pptx
Unit – II (1).pptx
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
 
UNIT I (6).pptx
UNIT I (6).pptxUNIT I (6).pptx
UNIT I (6).pptx
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
 

Dernier

Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating SystemRashmi Bhat
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadaditya806802
 
Steel Structures - Building technology.pptx
Steel Structures - Building technology.pptxSteel Structures - Building technology.pptx
Steel Structures - Building technology.pptxNikhil Raut
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfRajuKanojiya4
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESNarmatha D
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingBootNeck1
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 

Dernier (20)

Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating System
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasad
 
Steel Structures - Building technology.pptx
Steel Structures - Building technology.pptxSteel Structures - Building technology.pptx
Steel Structures - Building technology.pptx
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdf
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIES
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event Scheduling
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 

REGULAR EXPRESSIONS, SESSION AND COOKIES

  • 1. UNIT IV Regular Expressions, Session and Cookies
  • 2. Contents Transformation of Arrays – Stacks and Queues – Translating between Variables and Arrays – Sorting – Printing Functions for Visualizing Arrays – Tokenizing and Parsing Functions – Regular Expressions – Advanced String Functions – Session – Session in PHP – Session Functions – Cookies
  • 3. Transformation of Arrays PHP offers a host of functions for manipulating your data once you have it nicely stored in an array 1.Retrieving keys and values ● The array_keys() function returns the keys of its input array in the form of a new array where the keys are the stored values. ● The keys of the new array are the usual automatically incremented integers, starting from 0. ● The array_values() Takes a single array argument and returns a new array where the new values are the original values of the input array, and the new keys are the integers incremented from zero. ● The array_count_values() Takes a single array argument and returns a new array where the new keys are the old array’s values, and the new values are a count of how many times that original value occurred in the input array.
  • 4. Example: <!DOCTYPE html> <html> <body> <?php $fruits = array("10"=>"Apple", "20"=>"Mango", "30"=>"Orange", "40"=>"Orange"); echo "array keys<br>"; print_r(array_keys($fruits)); echo "<br>"; echo "array values<br>"; print_r(array_values($fruits)); echo "<br>count values<br>"; print_r(array_count_values($fruits)); ?> </body> </html> Output
  • 5. 2.Flipping, reversing, and shuffling ● The array_flip() function flips/exchanges all keys with their associated values in an array. ● array_reverse() takes a single array argument and changes the internal ordering of the key/value pairs to reverse order. Numerical keys will also be renumbered. ● The shuffle() function Takes a single array argument and randomizes the internal ordering of key/value pairs. Also renumbers integer keys to match the new ordering.
  • 6. Example: <!DOCTYPE html> <html> <body> <?php $fruits = array("0"=>"Apple", "1"=>"Mango", "2"=>"Orange"); echo "<b>Array Reverse<br></b>"; print_r(array_reverse($fruits)); echo "<b><br>Array flip<br></b>"; print_r(array_flip($fruits)); echo "<b><br>Array shuffle<br></b>"; shuffle($fruits); print_r($fruits); ?> </body> </html> Output
  • 7. 3.Merging, padding, slicing, and splicing ● The array_merge() function merges one or more arrays into one array. ○ Takes two array arguments, merges them, and returns the new array, which has (in order) the first array’s elements and then the second array’s elements ● array_pad() -Takes three arguments: an input array, a pad size, and a value to pad with. ○ The array_pad() function inserts a specified number of elements, with a specified value, to an array.
  • 9. Example:(array pad) <!DOCTYPE html> <html> <body> <?php $a=array("red","green"); print_r(array_pad($a,-5,"blue")); echo "<br>"; $b=array("red","green"); print_r(array_pad($b,5,"blue")); ?> </body> </html> Output
  • 10. ● The array_slice() function returns selected parts of an array. ○ array_slice(array, start, length, preserve) ■ array→Specifies an array ■ start→Numeric value. Specifies where the function will start the slice. ■ length→Numeric value. Specifies the length of the returned array. ■ Preserve→optioal. Specifies if the function should preserve or reset the keys. Possible values: ● true - Preserve keys ● false - Default. Reset keys
  • 11. Example:(array slice) <!DOCTYPE html> <html> <body> <?php $a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,2)); echo "<br>"; print_r(array_slice($a,0,3)); echo "<br>"; print_r(array_slice($a,-3,3)); echo "<br>"; print_r(array_slice($a,2,3,true)); ?> </body> </html> Output
  • 12. The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. array_splice(array, start, length, array) ● array→Specifies an array ● Start→ Numeric value. Specifies where the function will start removing elements. ● Length→ Specifies how many elements will be removed, and also length of the returned array. ● Array→ Specifies an array with the elements that will be inserted to the original array.
  • 13. Example:(array splice) <!DOCTYPE html> <html> <body> <?php $a1=array("red","green","blue","yellow"); $a2=array("purple","orange"); array_splice($a1,0,2,$a2); print_r($a1); echo "<br>"; print_r(array_splice($a1,0,2,$a2)); echo "<br>"; array_splice($a1,1,0,$a2); print_r($a1); ?> </body></html> Output
  • 14. Stacks and Queues ● Stacks and queues are abstract data structures, frequently used in computer science Stack: ● A stack is a container that stores values and supports last-in–first-out (LIFO) behavior. ● This means that the stack maintains an order on the values you store, and the only way you can get a value back is by retrieving (and removing) the most recently stored value ● The act of adding into the stack is called pushing a value onto the stack, whereas the act of taking off the top is called popping the stack
  • 15. Stack functions: ● The stack functions are array_push() and array_pop(). ● The array_push() function takes an initial array argument and then any number of elements to push onto the stack. ● The elements will be inserted at the end of the array, in order from left to right. ● The array_pop() function takes such an array and removes the element at the end, returning it. Queue: A queue is similar to a stack, but its behavior is first in, first out (FIFO).
  • 16. functions: array_shift: The array_shift() function removes the first element from an array, and returns the value of the removed element. array_unshift: The array_unshift() function inserts new elements to an array. The new array values will be inserted in the beginning of the array.
  • 17.
  • 18. Example:(stack push and pop) <!DOCTYPE html> <html> <body> <?php $a=array(); echo "push operation<br>"; array_push($a,"blue","yellow","red"); print_r($a); echo "<br> pop operation<br>"; array_pop($a); array_pop($a); print_r($a); ?></body> </html> Output
  • 19. Example:(queue array insert and delete) <html> <body> <?php $a=array(); echo "queue insertion<br>"; array_unshift($a,"blue"); array_unshift($a,"red"); array_unshift($a,"yellow"); print_r($a); echo "<br>pop operation<br>"; array_pop($a); print_r($a); ?> </body></html> Output
  • 20. Example:(queue array insert and delete) <html> <body> <?php $a=array(); echo "queue insertion<br>"; array_push($a,"blue"); array_push($a,"red"); array_push($a,"yellow"); print_r($a); echo "<br>pop operation<br>"; array_shift($a); print_r($a); ?> </body></html> Output
  • 21. Translating between Variables and Arrays ● PHP offers a couple of unusual functions for mapping between the name/value pairs of regular variable bindings and the key/value pairs of an array. ● The compact() function translates from variable bindings to an array, and the extract() function goes in the opposite direction compact() ● Takes a specified set of strings, looks up bound variables (if any) in the current environment that are named by those strings, and returns an array where the keys are the variable names, and the values are the corresponding values of those variables. ● It takes any number of arguments
  • 22. extract() ● Takes an array and imports the key/value pairs into the current variable-binding context. ● The array keys become the variable names, and the corresponding array values become the values of the variables. ● Any keys that do not correspond to a legal variable name will not produce an assignment.
  • 23. Example:(compact) <?php $firstname = "arun"; $lastname = "karthik"; $age = "41"; $result = compact("firstname", "lastname", "age"); print_r($result); ?> Output Example:(extract) <!DOCTYPE html> <html> <body> <?php $my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse"); extract($my_array); echo $a."<br>"; echo $b."<br>"; echo $c."<br>"; ?></body></html> Output
  • 24. Sorting ● PHP offers a host of functions for sorting arrays ● PHP offers variants of the sorting functions for each of these behaviors and also allows sorting in ascending or descending order and by user-supplied ordering functions Sorting functions: ● asort() ● arsort() ● ksort() ● krsort() ● sort() ● rsort() ● uasort() ● uksort() ● usort()
  • 25. Sorting functions ● asort() (associative array) The asort() function sorts an associative array in ascending order, according to the value. ● arsort()(associative array) arsort() function sorts an associative array in descending order, according to the value. ● ksort()(associative array) The ksort() function sorts an associative array in ascending order, according to the key. ● krsort()(associative array) The krsort() function sorts an associative array in descending order, according to the key.
  • 26. Example:asort() and arsort() <!DOCTYPE html> <html> <body> <?php $age=array("Peter"=>"35","Ben"=>"47","Joe"=>"43"); echo "asort<br>"; asort($age); foreach($age as $x=>$x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; } echo "<br>arsort<br>"; arsort($age); foreach($age as $x=>$x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; } ?></body> </html> Output
  • 27. Example:ksort() and krsort() <!DOCTYPE html> <html> <body> <?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); echo "ksort<br>"; ksort($age); foreach($age as $x=>$x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; } echo "<br>krsort<br>"; krsort($age); foreach($age as $x=>$x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; } ?> </body> </html> Output
  • 28. Sorting functions ● sort() The sort() function sorts an indexed array in ascending order. ● rsort() The rsort() function sorts an indexed array in descending order. ● usort() The usort() function sorts an array using a user-defined comparison function. ● uasort() (associative array) The uasort() function sorts an array by values using a user-defined comparison function. ● uksort()(associative array) The uksort() function sorts an array by keys using a user-defined comparison function.
  • 29. Example:sort() and rsort <!DOCTYPE html> <html> <body> <?php $fruits=array("Mango","Orange","Apple","Banana"); echo "sort<br>"; sort($fruits); for($i=0;$i<count($fruits);$i++) { echo $fruits[$i]; echo "<br>"; } echo "<br>rsort<br>"; rsort($fruits); for($i=0;$i<count($fruits);$i++) { echo $fruits[$i]; echo "<br>"; } ?> </body> </html> Output
  • 30. Example:usort() <?php $arr=array(6,20,10,18); echo "Ascending order<br>"; function sorting($a,$b) { if ($a==$b) return 0; return ($a<$b)?-1:1; } usort($arr,"sorting"); print_r($arr); echo "<br>Descending order<br>"; function mysort($a,$b) { if ($a==$b) return 0; return ($a>$b)?-1:1; } usort($arr,"mysort"); print_r($arr); Output Note: ascending order:1 when a>b or -1 when a<b descending order: -1 when a>b or 1 when a<b
  • 31. Example:uasort() <?php $arr=array("a"=>4,"b"=>2,"g"=>8,"d"=>6,"e"=>1,"f"=>9); echo "Ascending order<br>"; function sorting($a,$b) { if ($a==$b) return 0; return ($a<$b)?-1:1; } uasort($arr,"sorting"); print_r($arr); echo "<br>Descending order<br>"; function mysort($a,$b) { if ($a==$b) return 0; return ($a>$b)?-1:1; } uasort($arr,"mysort"); print_r($arr); ?> Output Note: ascending order:1 when a>b or -1 when a<b descending order: -1 when a>b or 1 when a<b
  • 32. Example:uksort() <?php $arr=array("a"=>4,"b"=>2,"g"=>8,"d"=>6,"e"=>1,"f"=>9); echo "Ascending order<br>"; function sorting($a,$b) { if ($a==$b) return 0; return ($a<$b)?-1:1; } uksort($arr,"sorting"); print_r($arr); echo "<br>Descending order<br>"; function mysort($a,$b) { if ($a==$b) return 0; return ($a>$b)?-1:1; } uksort($arr,"mysort"); print_r($arr); ?> Output Note: ascending order:1 when a>b or -1 when a<b descending order: -1 when a>b or 1 when a<b
  • 33. Printing Functions for Visualizing Arrays ● PHP offers a couple of printing functions that are very useful for visualizing and debugging arrays, especially multidimensional arrays ● The first function is print_r(), which is short for print recursive. ○ This takes an argument of any type and prints it out, which includes printing all its parts recursively. ● The var_dump() function is similar, except that it prints additional information about the size and type of the values it discovers.
  • 34. Example:(print_r and var_dump()) <html> <body> <?php $my_array = array("10" =>"apple",“20” => array("30" => "banana")); echo "print_r function<br>"; print_r($my_array); echo "<br>var_dump function<br>"; var_dump($my_array); ?> </body> </html> Output
  • 35. Tokenizing and Parsing Functions ● The process of breaking up a long string into words is called tokenizing ● PHP offers a special function for this purpose, called strtok(). ● strtok() function takes two arguments: ○ the string to be broken up into tokens and ○ a string containing all the delimiters ● The explode() function breaks a string into an array. ● The explode() function takes two arguments: ○ a separator string and the string to be separated. ○ It returns an array where each element is a substring between instances of the separator in the string to be separated
  • 36. ● The implode() method joins array elements with a string segment that works as a glue ● It takes two arguments: ○ a “glue” ○ string ● string implode (glue ,pieces)
  • 37. Example:(token) <!DOCTYPE html> <html> <body> <?php $string = "Hello world. Beautiful day today."; $token = strtok($string, " "); while ($token) { echo "$token<br>"; $token = strtok(" "); } ?> </body></html> Output
  • 38. Example:(explode) <!DOCTYPE html> <html> <body> <?php $str = "Hello world. It's a beautiful day."; print_r (explode(" ",$str)); ?> </body> </html> Output
  • 39. Example:(implode) <!DOCTYPE html> <html> <body> <?php $arr = array('Hello','World!','Beautiful','Day!'); echo implode(" ",$arr); ?> </body> </html> Output
  • 40. Why Regular Expressions? Regex in PHP ● Regular expressions (or regex) are patterns for string matching, with special wildcards that can match entire portions of the target string. ● There are two broad classes of regular expression that PHP works with: ○ POSIX(extended) regex and ○ Perl-compatible regex
  • 41. POSIX regex ● POSIX→Portable Operating System Interface for Unix ● Some regular expressions in PHP are like arithmetic expressions which are called POSIX regular expressions. ● Some times, complex expression are created by combining various elements or operators in regular expressions. Example: ● [0-9]-->It matches any decimal digit from 0 through 9. ● [a-z]-->It matches any character from lower-case a through lowercase z. ● [A-Z]-->It matches any character from uppercase A through uppercase Z.
  • 42.
  • 43.
  • 44. POSIX Regular Expression Functions ● ereg()-->Takes two string arguments and an optional third-array argument. The first string is the POSIX-style regular expression pattern, and the second string is the target string that is being matched ● ereg_replace()--> Takes three arguments: a POSIX regular expression pattern, a string to do replacement with, and a string to replace into ● eregi()-->Identical to ereg(), except that letters in regular expressions are matched in a case-independent way. ● eregi_replace()-->Identical to ereg_replace(), except that letters in regular expressions are matched in a case-independent way.
  • 45. Example(ereg()) <?php $str = "www.gmail.com"; $pattern = "^www.[a-z]+.com$"; if(ereg($pattern, $str)) echo “match found”; else echo “not found”; ?> Example(ereg_replace()) <?php $copy_date = "Copyright 1999"; $copy_date = ereg_replace("([0-9]+)", "2000", $copy_date); print $copy_date; ?> Output: Match found Output: Copyright2000
  • 46. ● split()--> ○ The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string. ○ Returns an array of strings after splitting up a string. ● spliti() ○ Case-independent version of split().
  • 47. Example(ereg()) <?php $str = "www.gmail.com"; $pattern = "^www.[a-z]+.com$"; if(ereg($pattern, $str)) echo “match found”; else echo “not found”; ?> Example(ereg_replace()) <?php $copy_date = "Copyright 1999"; $copy_date = ereg_replace("([0-9]+)", "2000", $copy_date); print $copy_date; ?> Output: Match found Output: Copyright2000
  • 48. Example(split()) <?php $ip = "123.456.789.000"; // some IP address $iparr = split (".", $ip); print "$iparr[0] <br />"; print "$iparr[1] <br />" ; print "$iparr[2] <br />" ; print "$iparr[3] <br />" ; ?> Output: 123 456 789 000
  • 49. Perl-Compatible Regular Expressions ● Perl-compatible regex in PHP has a completely distinct set of functions and a slightly different set of rules for patterns. ● Perl-compatible regex patterns are always bookended by one particular character, which must be the same at beginning and end, indicating the beginning and end of the pattern ● The Perl compatible pattern: ● /pattern/ ● Example: $my_pattern = ‘/pattern/‘;
  • 50.
  • 51.
  • 52. ● preg_match()-->Takes a regex pattern as first argument, a string to match against as second argument, and an optional array variable for returned matches. Returns 0 if no matches are found, and 1 if a match is found ● preg_match_all()--> Like preg_match(), except that it makes all possible successive matches of the pattern in the string, rather than just the first. The return value is the number of matches successfully made. ● preg_split()-->Takes a pattern as first argument and a string to match as second argument. Returns an array containing the string divided into substrings, split along boundary strings matching the pattern ● preg_replace()-->Takes a pattern, a replacement string, and a string to modify. Returns the result of replacing every matching portion of the
  • 53. Example(preg_match()) <?php $str = "www.gmail.com"; $pattern = "/www.[a-z]/"; if(preg_match($pattern, $str)) echo "match found"; else echo "match not found"; ?> Output
  • 54. Example(preg_match_all()) <?php $str = "The rain in SPAIN falls mainly on the plains."; $pattern = "/ain/i"; if(preg_match_all($pattern, $str, $matches)) { print_r($matches); } ?> Output
  • 55. Example(preg_split()) <?php $date = "1970-01-01 00:00:00"; $pattern = "/[-s:]/"; $components = preg_split($pattern, $date); print_r($components); ?> Output
  • 56. Example(preg_replace()) <?php $str = 'hai welcome!'; $pattern = '/hai/i'; echo preg_replace($pattern, 'hello', $str); ?> Output
  • 57. ● preg_replace_callback() Like preg_replace(), except that the second argument is the name of a callback function, rather than a replacement string. This function should return the string that is to be used as a replacement. ● preg_grep() The preg_grep() function returns an array containing only elements from the input that match the given pattern. ● preg_quote() The preg_quote() function adds a backslash to characters that have a special meaning in regular expressions so that searches for the literal characters can be done.
  • 58. Example(preg_replace_callback()) <?php function countLetters($matches) { return $matches[0] . '(' . strlen($matches[0]) . ')'; } $input = "Welcome 2023"; $pattern = '/[a-z]/'; $result = preg_replace_callback($pattern, 'countLetters', $input); echo $result; ?> Output
  • 59. Example(preg_grep()) <?php $input = array("Red", "Pink", "Green", "Blue", "purple"); $result = preg_grep("/^p/i", $input); print_r($result); ?> Output
  • 60. Example(preg_quote()) <?php $keywords = '$40 for a mobile phone'; $keywords = preg_quote($keywords); echo $keywords; ?> Output $40 for a mobile phone
  • 61. Sample Program(Validation for Aadhar, Email and Pan card) <html> <body> <?php function isValidAdhaar($s){ $pattern = '/^[2-9]{1}[0-9]{3}s[0-9]{4}s[0-9]{4}$/'; return preg_match($pattern,$s); } function isValidEmail($s){ $pattern = '/^([a-z0-9.]+@+[a-z]+(.)+[a-z]{2,3})$/'; return preg_match($pattern,$s); } function isValidPan($s){ $pattern = '/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/'; return preg_match($pattern,$s); }
  • 62. echo isValidAdhaar('3555 0143 1289')."<BR>"; echo isValidAdhaar('0556 013 1289')."<BR>"; echo isValidEmail('avicky@gmail.com')."<BR>"; echo isValidEmail('vickygmail@com')."<BR>"; echo isValidPan('BZIPY1430V')."<BR>"; echo isValidPan('BZIPY14370V')."<BR>"; ?> </body></html> Output
  • 63. Sample Program(replace) <!DOCTYPE html> <html> <body> <?php function toKecMail($s){ $pattern = '/@+[a-z]{2,}.{1}/i'; return preg_replace($pattern,'@kongu.',$s); } echo toKecMail('avicky@gmail.com')."<BR>"; echo toKecMail('vickygmail@com')."<BR>"; ?> </body> </html> Output
  • 64. Advanced String Functions HTML functions→PHP offers a number of web-specific functions for string manipulation htmlspecialchars() The htmlspecialchars() function converts some predefined characters to HTML entities. The predefined characters are: ● & (ampersand) becomes &amp; ● " (double quote) becomes &quot; ● ' (single quote) becomes &#039; ● < (less than) becomes &lt; ● > (greater than) becomes &gt; htmlentities() Goes further than htmlspecialchars(), in that it replaces all characters that have a corresponding HTML entity with that HTML entity.
  • 65. get_html_translation_table() The get_html_translation_table() function returns the translation table used by the htmlentities() and htmlspecialchars() functions. nl2br() The nl2br() function inserts HTML line breaks (<br> or <br />) in front of each newline (n) in a string. strip_tags() The strip_tags() function strips a string from HTML, XML, and PHP tags.
  • 66. Example: (htmlspecialchars) <!DOCTYPE html> <html> <body> <?php $str = "This is some <b>bold</b> text."; echo htmlspecialchars($str); ?> </body> </html> Output
  • 67. Example: (htmlentities) <!DOCTYPE html> <html> <body> <?php $str = '<a href="https://www.w3schools.com">Go to w3schools.com</a>'; echo htmlentities($str); ?> </body> </html> Output
  • 68. Example: (translation table) // HTML_SPECIALCHARS is default. <!DOCTYPE html> <html> <body> <?php print_r (get_html_translation_table()); ?> </body> </html> Output
  • 69. Example: ( nl2br) <!DOCTYPE html> <html> <body> <?php echo nl2br("One line.nAnother line."); ?> </body> </html> Output
  • 70. Example: ( strip_tags) <!DOCTYPE html> <html> <body> <?php echo strip_tags("Hello <b>world!</b>"); ?> </body> </html> Output
  • 71. Hashing using MD5 ● The MD5 (message-digest algorithm) hashing algorithm is a one-way cryptographic function that accepts a message of any length as input and returns as output a fixed-length digest value to be used for authenticating the original message ● MD5 is a string-processing algorithm that is used to produce a digest or signature of whatever string it is given. ● The algorithm boils its input string down into a fixed-length string of 32 hexadecimal values (0,1,2, . . . 9,a,b, . . . f). ● MD5 has some very useful properties: ○ MD5 always produces the same output string for any given input string, so it is not appropriate to use MD5 to store passwords. ○ The fixed-length results of applying MD5 are very evenly spread over the range of possible values. ○ It may be possible produce an input string corresponding to a given MD5 output string or to produce two inputs that yield the same output.
  • 72. ● PHP’s implementation of MD5 is available in the function md5(), which takes a string as input and produces the 32-character digest as output ● Example: <!DOCTYPE html> <html> <body> <?php $str = "Hello"; echo md5($str); echo "<br>"; echo md5("Hai"); ?> </body> </html> Output:
  • 73. Strings as character collections ● PHP offers some pretty specialized functions that treat strings more as collections of characters than as sequences. strspn() The strspn() function returns the number of characters found in the string that contains only characters from the charlist parameter.Takes two string arguments. strcspn() The strcspn() function returns the number of characters (including whitespaces) found in a string before any part of the specified characters are found. count_chars() The count_chars() function returns information about characters used in a string
  • 74. 0 - an array with the ASCII value as key and number of occurrences as value 1 - an array with the ASCII value as key and number of occurrences as value, only lists occurrences greater than zero 2 - an array with the ASCII value as key and number of occurrences as value, only lists occurrences equal to zero are listed 3 - a string with all the different characters used 4 - a string with all the unused characters
  • 75. ● Example: <!DOCTYPE html> <html> <body> <?php $twister = "Peter Piper picked a peck of pickled peppers"; $charset = "Peter picked a"; echo strspn($twister,$charset); ?> </body> </html> Output: 26
  • 76. ● Example: <!DOCTYPE html> <html> <body> <?php $t = "Welcome to our college"; $c = "t"; echo strcspn($t,$c); ?> </body> </html> Output: 8
  • 77. ● Example: <!DOCTYPE html> <html> <body> <?php $str = "Hello World!"; echo count_chars($str,3); ?> </body> </html> Output: !HWdelor
  • 78. String similarity functions ● The levenshtein() function is an inbuilt function in PHP. ● The levenshtein() function is used to calculate the levenshtein distance between two strings. ● The Levenshtein distance between two strings is defined as the minimum number of characters needed to insert, delete or replace in a given string $string1 to transform it to a string $string2. ● Syntax: ○ levenshtein(string1,string2,insert,replace,delete) ■ String1 Required. First string to compare ■ String2 Required. Second string to compare ■ Insert Optional. The cost of inserting a character. Default is 1 ■ Replace Optional. The cost of replacing a character. Default is 1 ■ Delete Optional. The cost of deleting a character. Default is 1
  • 79. Example: <!DOCTYPE html> <html> <body> <?php echo levenshtein("Hello World","ello World"); echo "<br>"; echo levenshtein("Tim","Time"); echo "<br>"; echo levenshtein("boy","chefboyardee”); echo "<br>"; echo levenshtein("never","clever"); ?> </body> </html> Output
  • 80. Session Session ● A session is a way to store information (in variables) to be used across multiple pages. ● An alternative way to make data accessible across the various pages of an entire website is to use a PHP Session. ● 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. ● In general, session refers to a frame of communication between two medium.
  • 81. Sessions in PHP ● A PHP session is used to store user information on the server for later use (i.e. username, shopping cart items, etc). ● However, this session information is temporary and is usually deleted very quickly after the user has left the website that uses sessions. How Sessions Work in PHP? ● Session tracking (that is, detecting whether two separate script invocations are, in fact, part of the same user session). ● Storing information in association with a session.
  • 82. Session Mechanism ● A PHP session is used to store data on a server rather than the computer of the user. ● Session identifiers or SID is a unique number which is used to identify every user in a session based environment. ● The SID is used to link the user with his information on the server like posts, emails etc. Where is the data really stored? ● There are two things that the session mechanism must hang onto: ○ the session ID itself and ○ any associated variable bindings. ● The session ID is either stored as a cookie on the browser's machine, or it is incorporated into the GET/POST arguments submitted with page requests.
  • 83. 1.Starting a PHP Session ● The first step is to start up a session. ● After a session is started, session variables can be created to store information. ● The PHP session_start() function is used to begin a new session. ● It also creates a new session ID for the user. ● Below is the PHP code to start a new session: <?php session_start(); ?>
  • 84. 2.Storing Session Data ● Session data in key-value pairs using the $_SESSION[] superglobal array. ● The stored data can be accessed during lifetime of a session. 3.Accessing Session Data ● Data stored in sessions can be easily accessed by firstly calling session_start() and then by passing the corresponding key to the $_SESSION associative array.
  • 85. ● Example:(start and set session variables) <?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php $_SESSION["Name"] = "nithi"; $_SESSION["Rollno"] = "50"; echo "Session variables are set."; ?> </body> </html> </html>
  • 86. ● Example:(Access session variables) <?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // Echo session variables that were set on previous page echo "Name is " . $_SESSION["Name"] . ".<br>"; echo "Rollnumber is " . $_SESSION["Rollno"] . "."; ?> </body> </html>
  • 87. 2.Destroying Certain Session Data: ● To delete only a certain session data,the unset feature can be used with the corresponding session variable in the $_SESSION associative array. 3.Destroying Complete Session: ● The session_destroy() function is used to completely destroy a session. The session_destroy() function does not require any argument.
  • 88. ● Example:(Delete certain session variables) <?php session_start(); if(isset($_SESSION["Name"])) { unset($_SESSION["Name"]); echo "deleted sucessfully"; } ?>
  • 89. ● Example:(Delete complete session variables) <?php session_start(); session_destroy(); echo "deleted all the session variables"; ?>
  • 90. ● PHP program to store page count: <html> <body> <?php session_start(); echo "<h1>welcome to our website</h1>"; if(isset($_SESSION['count'])) $_SESSION['count'] = $_SESSION['count']+1; else $_SESSION['count']=1; echo"no of times visited = ".$_SESSION['count']; ?> </body></html>
  • 91. Session Functions ● session_start() ○ A session is started with the session_start() function. ○ Session variables are set with the PHP global variable: $_SESSION. ○ Takes no arguments ● session_register()($_SESSION) ○ session_register() accepts a variable number of arguments, any of which can be either a string holding the name of a variable or an array consisting of variable names or other arrays. ○ For each name, session_register() registers the global variable with that name in the current session. ○ Example : session_register(‘username’) ○ Session variable can also be created by simply setting the appropriate member of the $_SESSION array.
  • 92. session_unregister() ○ Unregister a global variable from the current session ○ Takes a string variable name as argument and unregisters the corresponding variable from the session ○ If $_SESSION is used, use unset() to unregister a session variable. session_is_registered() ○ Find out whether a global variable is registered in a session ○ Takes a variable-name string and tests whether a variable with a given variable name is registered in the current session, returning TRUE if so and FALSE if not ○ If $_SESSION is used, use isset() to check a variable is registered in $_SESSION.
  • 93. session_destroy() ○ session_destroy() destroys all of the data associated with the current session. ○ It destroys the whole session rather destroying the variables. session_unset() ○ The session_unset() function frees all session variables currently registered. ○ It deletes only the variables from session and session still exists. Only data is truncated.
  • 94. session_write_close() ● Write session data and end session ● Manually close session and release write lock on data file. Example: <?php session_start(); $_SESSION["A"] = "Hello"; session_write_close(); echo "<br>"; print("Value: ".$_SESSION["A"]); ?>
  • 95. Session_name() ○ The session_name() function is used to name the current session or, retrieve the name of the session. <?php //Starting the session session_name("mysession"); session_start(); $name = session_name(); print("Session Name: ".$name); ?>
  • 96. session_module_name() ● If given no arguments, returns the name of the module that is responsible for handling session data. ● This name currently defaults to ‘files’, meaning that session bindings are serialized and then written to files in the directory named by the function session_save_path(). session_save_path() ● session_save_path() returns the path of the current directory used to save session data. <?php session_save_path('E:KECSUBJECTS'); $res = session_save_path(); session_start(); echo "path: ".$res; ?>
  • 97. session_id() Takes no arguments and returns a string, which is the unique key corresponding to a particular session. If given a string argument, will set the session ID to that string. <?php session_start(); $id = session_id(); print("Session Id: ".$id); ?> session_regenerate_id() ● It generates a new session id and updates the current one with the newly created one. <?php session_id("my-id"); session_start(); print("Id: ".session_id()); session_regenerate_id(); echo "<br>"; print("New Session Id: ".session_id()); ?>
  • 98. session_encode() This function encodes the data in the current session and returns it in the form of encoded serialized string. session_decode() It accepts a of encoded serialized session string and decodes it and stores it in the $_SESSION variable. Example: <?php session_start(); $_SESSION['data'] = "This is sample"; $res = session_encode(); echo "Encoded Data: ". $res."<br>"; session_decode($res); print_r($_SESSION); ?>
  • 99. session_set_cookie_params() It is used to set the session cookie parameters defined in the php.ini file session_get_cookie_params() It is used to retrieve the session cookie parameters and it returns an array which contains the current session cookie parameter values. <?php session_set_cookie_params(30 * 60, "/", "mypage", ); $res = session_get_cookie_params(); session_start(); print_r($res); ?>
  • 101.
  • 102. Sample Code <?php session_start(); ?> <HTML><HEAD><TITLE>Greetings</TITLE></HEAD> <BODY> <H2>Welcome to the Center for Content-free Hospitality</H2> <?php if (!IsSet($_SESSION['visit_count'])) { echo "Hello, you must have just arrived.Welcome!<BR>"; $_SESSION['visit_count'] = 1; } else { $visit_count = $_SESSION['visit_count'] + 1; echo "Back again are you? That makes $visit_count times now"."(not that anyone’s counting)<BR>"; $_SESSION['visit_count'] = $visit_count; }
  • 103. $self_url = $_SERVER['PHP_SELF']; $session_id = SID; if (IsSet($session_id) && $session_id) { $href = "$self_url?$session_id"; } else { $href = $self_url; } echo "<BR><A HREF=“$href“>Visit us again</A> sometime"; ?> </BODY></HTML>
  • 104.
  • 105. Cookies ● A cookie is a small piece of information that is retained on the client machine, either in the browser’s application memory or as a small file written to the user’s hard disk. ● It contains a name/value pair setting a cookie means associating a value with a name and storing that pairing on the client side. ● Getting or reading a cookie means using the name to retrieve the value. ● It is used to keep track of information such as a username that the site can retrieve to personalize the page when the user visits the website next time.
  • 106. ● PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the user. ● Cookie is created at server side and saved to client browser. Each time when client sends request to the server, cookie is embedded with request. Such way, cookie can be received at the server side.
  • 107. The setcookie() function ● In PHP, cookies are set using the setcookie() function ● Once cookie is set, you can access it by $_COOKIE superglobal variable. Syntax: setcookie(name, value, expire, path, domain, secure, httponly); Arguments to setcookie() Argument Name Expected Type Meaning name string The name of your cookie value string The value you want to store in the cookie expire int Specifies when this cookie should expire. A value of 0 (the default) means that it should last until the browser is closed.
  • 108. Argument Name Expected Type Meaning path string In the default case, any page within the web root folder would see this named cookie. Setting the path to a subdirectory (for example, “/forum/”) allows distinguishing cookies that have the same name but are set by different sites or subareas of the web server httponly boolean Cookies set with this flag are only sent through HTTP requests. Default is FALSE. domain string In the default case, no check is made against the domain requested by the client. If this argument is nonempty, then the domain must match. secure boolean (TRUE (1) or FALSE (0)) Defaults to 0 (FALSE). If this argument is 1 or TRUE, the cookie will only be sent over a secure socket (aka SSL or HTTPS) connection.
  • 109. Example: (PHP Create/Retrieve a Cookie) <?php $name = "user"; $value = "Nithi"; setcookie($name, $value, time() + (86400 * 30), "/"); ?> <html> <body> <?php if(!isset($_COOKIE[$name])) { echo "Cookie is not set!"; } else { echo "Cookie is created<br>"; echo "Value is: " . $_COOKIE[$name]; } ?> </body> </html>
  • 110. Deleting Cookies ● Deleting a cookie is easy. ● Simply call setcookie(), with the exact same arguments as when you set it, except the value, which should be set to an empty string. ● This does not set the cookie’s value to an empty string — it actually removes the cookie ● Another method to clear cookies is to set the expiration time in the past.
  • 111. Example: (Delete a Cookie) <?php // set the expiration date to one hour ago setcookie("user", "", time() - 3600); ?> <html> <body> <?php echo "Cookie 'user' is deleted."; ?> </body> </html>
  • 112. Cookie pitfalls 1.Sending something else first ● The single most common error in using cookies is trying to set a cookie after some regular HTML content has already been generated ● Cookies must be sent before any output from your script (this is a protocol restriction). ● This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace. ● As soon as any regular content is generated, PHP figures that it must already know about all headers of interest, and so it sends them off and then begins the transmission of HTML content. ● If it encounters a cookie later on, it is too late, and an error is generated.
  • 113. 2.Reverse-order interpretation ● As with most HTTP commands, calls to setcookie() may actually be executed in the opposite order from the way that they appear in your PHP script, but this depends on the particular browser your user is running and the version of PHP you’re using. ● This means that a pair of successive statements like the following probably have the counter intutive result of leaving the “mycookie” cookie with no value, because the unsetting statement is executed second. ○ setcookie(“mycookie”);// get rid of the old value (WRONG) ○ setcookie(“mycookie”, “newvalue”);// set the new value (WRONG) ● There is no need to remove a cookie before setting it to a different value — simply set it to the desired new value. Among other things, this means that the confusing reverse order of
  • 114. 3.Cookie refusal ● Finally, be aware that setcookie() makes no guarantees that any cookie data will, in fact, be accepted by the client browser ● The setcookie() function does not even return a value that indicates acceptance or refusal of the cookie ● First, the script executes (including the setcookie() call), with the result that a page complete with HTTP headers is sent to the client machine. ● At this point, the client browser decides how to react to the cookie-setting attempt. ● Not until the client generates another request can the server receive the cookie’s value and detect whether the cookie-setting attempt was successful