SlideShare a Scribd company logo
Working with Data
Ms. Mohana Priya S
Department of computer Science[UG]
Validate input field in the HTML Form
• To validate the form using HTML, we will use the HTML
<input> required attribute.
• The <input> required attribute is a Boolean attribute
that is used to specify the input element that must be
filled out before submitting the Form.
Data validation ensures accurate and useful user input. It
checks for completed required fields, valid dates, and
appropriate data types.
• Required Fields: Users must fill in all mandatory fields
to avoid incomplete submissions.
• Date Validation: Ensures users enter dates in the correct
format.
• Numeric Field Text: Verifies users enter text in text
fields and numeric values in numeric fields.
Validation takes place either on the server side (after data
submission) or on the client side (prior to data submission).
• Server-side: Done by the web server for data integrity and
security.
• Client-side: Performed by the browser for instant user feedback.
<form action="#">
<label for="fname">First Name:</label>
<input type="text" name="fname" id="fname" required>
<br><br>
<label for="lname">Last Name:</label>
<input type="text" name="lname" id="lname" required>
<br><br>
<label for="email">Email Id:</label>
<input type="email" name="email" id="email" required>
<br><br>
<input type="submit" value="Submit">
</form>
<label for="phone">Phone:</label>
<input type="number" id="phone"
name="phone" pattern="[0-9]{10}"
placeholder="Enter 10-digit mobile number"
required><br>
Passing variables with data between pages
Pass values of variables between pages in site. These are
required in many different ways. Some time we collect some
value from a database and want to retain the value for the
particular user throughout the site as the user moves
between pages. There are different ways for passing such
values of the variables.
Passing variable values between pages using
session
This is one of the secured ways the variables are passed between
pages. The best example of such a system is when we see our user-
id inside a member area after we logged in. In a member login
system the user details are verified and once found correct, a new
session is created and with user id of the member and this value is
stored at server end. Every time a new page is opened by the
browser, the server checks the associated session value and display
the user id. This system is more secure and the member doesn't get
any chance to change the values.
Passing variables between pages using cookies
Cookies are stored at the user or the client end and values can be
passed between pages using PHP. But here the client browser can
reject accepting cookies by changing the security settings of the
browser. So this system can fail to pass values between pages if user
or client end settings are changed. But cookies are quit useful in
handling user entered values and passing them between pages.
Passing variables between pages using URL
Pass variable values between pages through the URL ( in address bar
of the browser). Here values are visible to the user and others as
they appear in the address bar and also in the browser history. This
is not a secure way to transfer sensitive data like password, etc.
Advantage of using URL to pass variables
• The advantage is we can pass data to a different site even running
at different servers. Any scripting language like ASP, JSP, PHP
• Easy to save the URL or bookmark it for frequent use.
• Copy the URL and send it to a friend to refer.
Example of passing data through URL within a site.
<a href='page2.php?id=2489&user=tom'>link to page2</a>
When the above link is clicked, page2.php gets the
variables id and user with data 2489 and tom respectively.
Code to collect data in PHP.
echo $_GET['id']; // output 2489
echo $_GET['user']; // output tom
Passing data outside
<a href=https://www.sitename.com/index.php?id=2489&user=tom>Link to
another site</a>
Note that after the page name we are using question mark ( ? ) to start
the variable data pair and we are separating each variable data pair
with one ampersand ( & ) mark.
Submitting form values through GET method
A web form when the method is set to GET method, it submits the
values through URL. So we can use one form to generate an URL
with variables and data by taking inputs from the users. The form
will send the data to a page within the site or outside the site by
formatting a query string.
<form method=GET action='https://www.anysite.com/index.php'>
Submitting a form through POST method
By post method of form submission we can send more number or
length of data. Sensitive information like password does not get
exposed in URL by POST method, so our login forms we should use
POST method to submit data. This is how we collect data submitted
by POST method in PHP
$id=$_POST['id'];
$password=$_POST['password'];
Difference between GET and POST
Issues GET POST
Browser History Data remain in Browser History Data Not available in Browser
History
Bookmark URL with Data can be
bookmarked
No data is available in URL to
bookmark the page
Data Length Restriction The restriction (of URL ) is
applicable
No Restriction
cached Can be cached No meaningful caching
Sensitive Data Data like password , pin etc. are
exposed through URL so they
should not be passed using GET
method
Better than GET method as data
is not exposed through URL
Collecting data submitted by either GET or
POST method
If a page is receiving a data which can come in any one of the
method GET or POST then how to collect it ? Here we are not sure
how to collect the data. So we will use like this.
$id=$_REQUEST['id'];
$password=$_REQUEST['password'];
PHP - $_REQUEST
$_REQUEST
$_REQUEST is a PHP super global variable which contains submitted
form data, and all cookie data.
In other words, $_REQUEST is an array containing data from $_GET,
$_POST, and $_COOKIE.
You can access this data with the $_REQUEST keyword followed by
the name of the form field, or cookie, like this:
$_REQUEST['firstname']
String Function chr()
• It is used to return a character from a specified ASCII value
• The PHP chr() function is used to generate a single byte string
from a number. In another words we can say that it returns a
character from specified ASCII value.
• Syntax:
string chr ( int $bytevalue );
Example 1:
<?php
$char =52;
echo "Your character is :".$char;
echo "<br>"."By using 'chr()' function your value is: ".chr($char);// d
ecimal Value
?>
• Your character is : 52 By using 'chr()' function your value is: 4
Example 2:
<?php
$char =052;
echo "Your character is :".$char;
echo "<br>"."By using 'chr()' function your value is: ".chr($char); // O
ctal Value
?>
• Your character is :42 By using 'chr()' function your value is: *
<?php
echo "Your character is :0x52";
echo "<br>"."By using 'chr()' function your value is: ".chr(0x52); // H
ex value
?>
• Your character is :0x52
By using 'chr()' function your value is: R
ord()
• Returns the ASCII value of the first character of a string.
Definition and Usage
The ord() function returns the ASCII value of the first character of a
string.
Syntax:
ord(string)
<?php
echo ord("h")."<br>";
echo ord("hello")."<br>";
?>
O/P:
104
104
• strtolower()
hello world
PHP string functions
<?php
echo strtolower("HELLO WORLD.");
?>
• strtoupper()
• Convert all characters to uppercase:
<?php
echo strtoupper("Hello WORLD!");
?>
HELLO WORLD
• lcfirst() - converts the first character of a string
to lowercase
• ucfirst() - converts the first character of a string
to uppercase
• ucwords() - converts the first character of each
word in a string to uppercase
strrev()
Strlen()
lcfirst()
Ucwords()
ltrim() -
Removes whitespace or other characters from the
left side of a string
Definition and Usage
The ltrim() function removes whitespace or other predefined
characters from the left side of a string.
Related functions:
•rtrim() - Removes whitespace or other predefined characters
from the right side of a string
•trim() - Removes whitespace or other predefined characters
from both sides of a string
• Syntax
ltrim(string,charlist)
• string
Required. Specifies the string to check
• charlist
Optional. Specifies which characters to remove from the string. If
omitted, all of the following characters are remove
"0" - NULL
"t" - tab
"n" - new line
"x0B" - vertical tab
"r" - carriage return
" " - ordinary white space
• Remove newlines (n) from the left side of a string:
• <?php
$str = "nnnHello World!";
echo "Without ltrim: " . $str;
echo "<br>";
echo "With ltrim: " . ltrim($str);
?>
substr()
Syntax
substr(string,start,length)
<!DOCTYPE html>
<html>
<body>
<?php
// Positive numbers:
echo substr("Hello world",10)."<br>";
echo substr("Hello world",1)."<br>";
echo substr("Hello world",7)."<br>";
echo "<br>";
// Negative numbers:
echo substr("Hello world",-1)."<br>";
echo substr("Hello world",-10)."<br>";
echo substr("Hello world",-4)."<br>";
?>
</body>
</html>
O/p:
d
ello world
orld
d
ello world
orld
<!DOCTYPE html>
<html>
<body>
<?php
echo substr("Hello world",6);
?>
</body>
</html> O/p: world
The strcmp() function compares two strings.
• The strcmp() function compares two strings.
• Note: The strcmp() function is binary-safe and case-sensitive.
• Tip: This function is similar to the strncmp() function, with the
difference that you can specify the number of characters from
each string to be used in the comparison with strncmp().
Syntax
strcmp(string1,string2)
Return Value
<!DOCTYPE html>
<html>
<body>
<?php
echo strcmp("Hello world!","Hello world!")."<br>"; // the two strings are equal
echo strcmp("Hello world!","Hello")."<br>"; // string1 is greater than string2
echo strcmp("Hello world!","Hello world! Hello!")."<br>"; // string1 is less than
string2
?>
</body>
</html>
o/p:
0
7
-7
This function returns: 0 - if the two strings are equal
<0 - if string1 is less than string2
>0 - if string1 is greater than string2
strpos() - Search For a Text Within a String
• The PHP strpos() function searches for a specific text
within a string. If a match is found, the function returns
the character position of the first match. If no match is
found, it will return FALSE.
Example
Search for the text "world" in the string "Hello world!":
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
Replace Text Within a String
The PHP str_replace() function replaces some characters
with some other characters in a string.
Example
Replace the text "world" with "Dolly":
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs
Hello Dolly!
?>
str_word_count() - Count Words in a String
The PHP str_word_count() function counts the number of words in
a string.
Example
Count the number of word in the string "Hello world!":
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
Math functions
•PHP provides many predefined math
constants and functions that can be used to
perform mathematical operations.
Math functions in PHP
• abs()
• Ceil()
• Floor()
• Round()
• Fmod()
• Min()
• Max()
• Pow()
• Sqrt()
• Rand()
Abs()
• The abs() function returns the absolute (positive) value of a
number.
Syntax:
abs( value )
Parameters: The abs() function accepts single parameter value
which holds the number whose absolute value you want to find.
Return Value: It returns the absolute value of the number passed to it
as argument.
• number Required. Specifies a number. If the number is of type
float, the return type is also float, otherwise it is integer
• The abs() function in PHP is identical to what we call modulus in
mathematics. The modulus or absolute value of a negative number
is positive.
Example
• <?php
echo(abs(6.7) . "<br>");
echo(abs(-6.7) . "<br>");
echo(abs(-3) . "<br>");
echo(abs(3));
?>
Output
• 6.7
6.7
3
3
Ceil()
• The ceil() function rounds a number UP to the nearest integer.
Syntax:
float ceil(value)
• Parameters: The ceil() function accepts a single parameter value
which represents the number which you want to round up to the
nearest greater integer.
• Return Value: The return type of the ceil() function is float as
shown in the syntax. It returns the number which represents the
value rounded up to the next highest integer.
• number Required. Specifies the value to round up
Example
• Output
• 1
1
5
6
-5
-5
• <?php
echo(ceil(0.60) . "<br>");
echo(ceil(0.40) . "<br>");
echo(ceil(5) . "<br>");
echo(ceil(5.1) . "<br>");
echo(ceil(-5.1) . "<br>");
echo(ceil(-5.9));
?>
Floor()
• The floor() function rounds a number DOWN to the nearest
integer.
Syntax:
float floor(value)
• Parameters: This function accepts the single parameter value
which is rounded down to the next lowest integer.
• Return Value: The return type is a float value. It returns the next
lowest integer value as a float which is rounded down, only if
necessary.
• number Required. Specifies the value to round down
Example
• <?php
echo(floor(0.60) . "<br>");
echo(floor(0.40) . "<br>");
echo(floor(5) . "<br>");
echo(floor(5.1) . "<br>");
echo(floor(-5.1) . "<br>");
echo(floor(-5.9));
?>
Output
• 0
0
5
5
-6
-6
Round()
• The round() function rounds a floating-point number.
• Syntax:
round(number,precision,mode);
• Parameters: It accepts three parameters out of which one is compulsory
and two are optional. All of these parameters are described below:
• $number: It is the number which you want to round.
• $precision: It is an optional parameter. It specifies the number of
decimal digits to round to. The default value of this parameter is zero.
• $mode: It is an optional parameter. It specifies a constant to specify the
rounding mode.
• number Required. Specifies the value to round precision
• Optional. Specifies the number of decimal digits to round to. Default
is 0
Round()
• The round() function rounds a floating-point number.
• Syntax:
round(number,precision,mode);
• Parameters: It accepts three parameters out of which one is compulsory
and two are optional. All of these parameters are described below:
• $number: It is the number which you want to round.
• $precision: It is an optional parameter. It specifies the number of
decimal digits to round to. The default value of this parameter is zero.
• $mode: It is an optional parameter. It specifies a constant to specify the
rounding mode.
• number Required. Specifies the value to round precision
• Optional. Specifies the number of decimal digits to round to. Default
is 0
• mode Optional. Specifies a constant to specify the
rounding mode: PHP_ROUND_HALF_UP - Default. Rounds
number up to precision decimal, when it is half way
there. Rounds 1.5 to 2 and -1.5 to -2
• PHP_ROUND_HALF_DOWN - Round number down to
precision decimal places, when it is half way there.
Rounds 1.5 to 1 and -1.5 to -1
• PHP_ROUND_HALF_EVEN - Round number to precision
decimal places towards the next even value
• PHP_ROUND_HALF_ODD - Round number to precision
decimal places towards the next odd value
Example 1
• <?php
echo(round(0.60) . "<br>");
echo(round(0.50) . "<br>");
echo(round(0.49) . "<br>");
echo(round(-4.40) . "<br>");
echo(round(-4.60));
?>
• Output
• 1
1
0
-4
-5
Example 2
• <?php
echo(round(4.96754,2) . "<br>");
echo(round(7.045,2) . "<br>");
echo(round(7.055,2));
?>
• 4.97
7.05
7.06
• <?php
echo(round(1.5,0,PHP_ROUND_HALF_UP) . "<br>");
echo(round(-1.5,0,PHP_ROUND_HALF_UP) . "<br>");
echo(round(1.5,0,PHP_ROUND_HALF_DOWN). "<br>");
echo(round(-1.5,0,PHP_ROUND_HALF_DOWN). "<br>");
echo(round(1.5,0,PHP_ROUND_HALF_EVEN) . "<br>");
echo(round(-1.5,0,PHP_ROUND_HALF_EVEN) . "<br>");
echo(round(1.5,0,PHP_ROUND_HALF_ODD) . "<br>");
echo(round(-1.5,0,PHP_ROUND_HALF_ODD));
?>
Example 3
• Output
2
-2
1
-1
2
-2
1
-1
Fmod()
• The fmod() function returns the remainder (modulo) of x/y.
• In PHP the fmod() function is used to calculate the Modulo of any
division which may contain floats as both dividends and divisors.
Syntax:
float fmod ($dividend, $divisor)
• Parameters: The function takes two parameters as follows:
• $dividend: This parameter takes a float which is to be divided.
• $divisor: This parameter takes a float which is to be used as a
divisor.
• Return Type: This function returns a Floating-point remainder of
the division.
Example
• <?php
$x = 7;
$y = 2;
$result = fmod($x,$y);
echo $result;
?>
Output
1
Min ()
• The min() function returns the lowest value in an array, or the lowest
value of several specified values.
• The min() function can take an array or several numbers as an argument
and return the numerically minimum value among the passed
parameters. The return type is not fixed, it can be an integer value or a
float value based on input.
• Sytax:
min(array_values);
or
min(value1,value2,...);
• Parameters: This function accepts two different types of parameters
which are explained below:
• array_values : It specifies an array containing the values.
• value1, value2, … : It specifies two or more than two values to be
compared.
Example
• <?php
echo(min(2,4,6,8,10) . "<br>");
echo(min(22,14,68,18,15) . "<br>");
echo(min(array(4,6,8,10)) . "<br>");
echo(min(array(44,16,81,12)));
?>
Output
2
14
4
12
Max()
• The max() function returns the highest value in an array, or the highest value of
several specified values.
• The max() function of PHP is used to find the numerically maximum value in an
array or the numerically maximum value of several specified values.
• The max() function can take an array or several numbers as an argument and return
the numerically maximum value among the passed parameters. The return type is
not fixed, it can be an integer value or a float value based on input.
• Sytax:
max(array_values);
or
max(value1,value2,...);
•
Parameters: This function accepts two different types of arguments which are
explained below:
• array_values : It specifies an array containing the values.
• value1, value2, … : It specifies two or more than two values to be compared.
• <html>
<body>
<?php
echo(max(2,4,6,8,10) . "<br>");
echo(max(22,14,68,18,15) . "<br>");
echo(max(array(4,6,8,10)) . "<br>");
echo(max(array(44,16,81,12)));
?>
</body>
</html>
Pow()
• The pow() function returns ($base raised to the power of $exp.
• Syntax:
number pow($base, $exp);
• Parameters : The pow() function accepts two parameters as
shown in the above syntax:
• $base : It is used to specify the base.
• $exponent : It is used to specify the exponent.
• Return Value: It returns a number (integer or floating-point)
which is equal to $base raised to the power of $exponent.
<html>
<body>
<?php
echo(pow(2,4) . "<br>"); //16
echo(pow(-2,4) . "<br>");//16
echo(pow(-2,-4) . "<br>");//0.0625
?>
</body>
</html>
Input : pow(3, 2)
Output : 9
Input : pow(-3, 2)
Output : 9
Input : pow(-3, -3)
Output : 0.037037037037037
Input : pow(-3, -3.2)
Output : NaN
Sqrt()
• The sqrt() function returns the square root of a number.
• Syntax:
sqrt(number);
• number Required. Specifies a number
Example
<?php
echo(sqrt(0) . "<br>"); // 0
echo(sqrt(1) . "<br>"); // 1
echo(sqrt(9) . "<br>"); // 3
echo(sqrt(0.64) . "<br>"); // 0.8
?>
Rand()
• The rand() function generates a random integer.
• The rand() is an inbuilt function in PHP used to generate a random
number ie., it can generate a random integer value in the range [min,
max].
• rand();
or
rand(min,max);
• Parameter values:
• min: It is an optional parameter that specifies the lowest value that will
be returned. The default value is 0.
• max: It is an optional parameter that specifies the highest value to be
returned. The default value is getrandmax().
Examples:
Note: The output of the code may change every time it is run. So the
output may not match with the specified output.
<?php
// Generating a random number
$randomNumber= rand();
print_r($randomNumber);
print_r("n");
// Generating a random number in a
// Specified range.
$randomNumber= rand(15,35);
print_r($randomNumber);
?>
output:
1257424548
28
PHP Array Functions
• count,
• list,
• in_array,
• current,
• next,
• previous,
• end,
• each
Array()
• The array() function is used to create a PHP array. This function
can be used to create indexed arrays or associative arrays. PHP
arrays could be single dimensional or multi-dimensional.
Syntax
Syntax to create PHP indexed arrays:
$a = array(value1, value2, value3, ...)
Syntax to create PHP associative arrays:
$a = array(key1 => value1, key2 => value2...)
Example
• <?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and
" . $cars[2] . ".";
?>
• I like Volvo, BMW and Toyota.
Count()
• The count() function returns the number of elements in an
array.
Syntax
count(array, mode)
in_array — Checks if a value exists in an array
• Syntax:
• in_array(search, array, type)
in_array example
• <?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
if (in_array("Glenn", $people))
{
echo "Match found";
}
else
{
echo "Match not found";
}
?>
• o/p: Match found
list() function
• The list() function is used to assign values to a list of variables in
one operation.
• Syntax:
• list(var1, var2, ...)
Example
• <?php
$my_array = array("Dog","Cat","Horse");
list($a, , $c) = $my_array;
echo "Here I only use the $a and $c variables.";
?>
• o/p:
Here I only use the Dog and Horse variables.
current() function
• Definition and Usage
• The current() function returns the value of the current element
in an array.
• Every array has an internal pointer to its "current" element,
which is initialized to the first element inserted into the array.
Related current methods:
• end() - moves the internal pointer to, and outputs, the last element in
the array
• next() - moves the internal pointer to, and outputs, the next element in
the array
• prev() - moves the internal pointer to, and outputs, the previous
element in the array
• reset() - moves the internal pointer to the first element of the array
• each() - returns the current element key and value, and moves the
internal pointer forward
Syntax:
current(array)
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
echo current($people) . "<br>"; // The current element is Peter
echo next($people) . "<br>"; // The next element of Peter is Joe
echo current($people) . "<br>"; // Now the current element is Joe
echo prev($people) . "<br>"; // The previous element of Joe is Peter
echo end($people) . "<br>"; // The last element is Cleveland
echo prev($people) . "<br>"; // The previous element of Cleveland is
Glenn
echo current($people) . "<br>"; // Now the current element is Glenn
echo reset($people) . "<br>"; // Moves the internal pointer to the first
element of the array, which is Peter
echo next($people) . "<br>"; // The next element of Peter is Joe
print_r (each($people)); // Returns the key and value of the current
element (now Joe), and moves the internal pointer forward
?>
Peter
Joe
Joe
Peter
Cleveland
Glenn
Glenn
Peter
Joe
Array ( [1] => Joe [value] => Joe [0] => 1 [key] => 1 )
PHP Include File
• The include (or require) statement takes all the text/code/markup
that exists in the specified file and copies it into the file that uses the
include statement.
• Including files is very useful when you want to include the same
PHP, HTML, or text on multiple pages of a website.
• It is possible to insert the content of one PHP file into another PHP
file (before the server executes it), with the include or require
statement.
• The include and require statements are identical, except upon
failure:
• require will produce a fatal error (E_COMPILE_ERROR) and
stop the script
• include will only produce a warning (E_WARNING) and the
script will continue
PHP include and require
• Including files saves a lot of work. This means that you can create
a standard header, footer, or menu file for all your web pages.
Then, when the header needs to be updated, you can only update
the header include file.
Syntax
• include 'filename';
or
require 'filename';
Advantage
• Code Reusability: By the help of include and
require construct, we can reuse HTML code or
PHP script in many PHP scripts.
PHP include example
• PHP include is used to include file on the basis of given path. You
may use relative or absolute path of the file.
• Let's see a simple PHP include example.
Example 1
Assume we have a standard footer file called "footer.php", that looks like this:
<?php
echo "<p>Copyright &copy; 1999-" . date("Y") . " kristujayanti.edu.in </p>";
?>
To include the footer file in a page, use the include statement:
Example
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>
</body>
</html>
PHP Functions
• PHP function is a piece of code that can be reused many times.
• It can take input as argument list and return value.
• There are thousands of built-in functions in PHP.
Parameterized Function
• PHP Parameterized functions are the functions with
parameters. You can pass any number of parameters
inside a function. These passed parameters act as
variables inside your function.
• They are specified inside the parentheses, after the
function name.
• The output depends upon the dynamic values passed as
the parameters into the function.
Php default arguments
Recursive function
PHP Superglobals
PHP provides an additional set of predefined arrays
containing variables from the web server the
environment, and user input. These new arrays are
called superglobals.
$GLOBALS
Contains a reference to every variable which is
currently available within the global scope of the
script. The keys of this array are the names of the
global variables.
Example
• <?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
• OUTPUT: 100
$_SERVER
• This is an array containing information such as
headers, paths, and script locations.
• The entries in this array are created by the web
server.
• There is no guarantee that every web server will
provide any of these.
Example
• <?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
OUTPUT:
/demo/demo_global_server.php
35.194.26.41
35.194.26.41
https://tryphp.w3schools.com/showphp.php?filename=demo_global_server
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0
/demo/demo_global_server.php
$_GET
•An associative array of variables passed to
the current script via the HTTP GET method.
$_POST
• An associative array of variables passed to the
current script via the HTTP POST method.
$_REQUEST
• An associative array consisting of the contents of $_GET, $_POST, and $_COOKIE.
• <!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo
$_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = htmlspecialchars($_REQUEST['fname']);
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
$_PHP_SELF
• A string containing PHP script file name in which it is called.
$_SERVER['PHP_SELF']
• The filename of the currently executing script, relative to the
document root
$_SERVER['SERVER_NAME']
• The name of the server host under which the current script is
executing. If the script is running on a virtual host, this will be the
value defined for that virtual host.

More Related Content

Similar to Working with Data and built-in functions of PHP

Php forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligetiPhp forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligeti
Naveen Kumar Veligeti
 
SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2
Ben Abdallah Helmi
 
API_Testing_with_Postman
API_Testing_with_PostmanAPI_Testing_with_Postman
API_Testing_with_Postman
Mithilesh Singh
 
javascript.pptx
javascript.pptxjavascript.pptx
javascript.pptx
hasiny2
 
07 application security fundamentals - part 2 - security mechanisms - data ...
07   application security fundamentals - part 2 - security mechanisms - data ...07   application security fundamentals - part 2 - security mechanisms - data ...
07 application security fundamentals - part 2 - security mechanisms - data ...
appsec
 
WEB-MODULE 4.pdf
WEB-MODULE 4.pdfWEB-MODULE 4.pdf
WEB-MODULE 4.pdf
Deepika A B
 
SCWCD : The servlet model : CHAP : 2
SCWCD  : The servlet model : CHAP : 2SCWCD  : The servlet model : CHAP : 2
SCWCD : The servlet model : CHAP : 2
Ben Abdallah Helmi
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
Aren Zomorodian
 
SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6
Ben Abdallah Helmi
 
Implementing Ajax In ColdFusion 7
Implementing Ajax In ColdFusion 7Implementing Ajax In ColdFusion 7
Implementing Ajax In ColdFusion 7
Pranav Prakash
 
PHP Form Validation Technique
PHP Form Validation TechniquePHP Form Validation Technique
PHP Form Validation Technique
Morshedul Arefin
 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHP
Matthew Turland
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager
Jay Shirley
 
Security: Odoo Code Hardening
Security: Odoo Code HardeningSecurity: Odoo Code Hardening
Security: Odoo Code Hardening
Odoo
 
Common Gateway Interface
Common Gateway InterfaceCommon Gateway Interface
Common Gateway Interface
Balu Masulkar
 
GET and POST in PHP
GET and POST in PHPGET and POST in PHP
GET and POST in PHP
Vineet Kumar Saini
 
Data-Analytics using python (Module 4).pptx
Data-Analytics using python (Module 4).pptxData-Analytics using python (Module 4).pptx
Data-Analytics using python (Module 4).pptx
DRSHk10
 
Tutorial_Rest_API_For_Beginners_125.pptx
Tutorial_Rest_API_For_Beginners_125.pptxTutorial_Rest_API_For_Beginners_125.pptx
Tutorial_Rest_API_For_Beginners_125.pptx
T.Choithram & Sons Dubai
 
Security.ppt
Security.pptSecurity.ppt
Security.ppt
webhostingguy
 
12-security.ppt - PHP and Arabic Language - Index
12-security.ppt - PHP and Arabic Language - Index12-security.ppt - PHP and Arabic Language - Index
12-security.ppt - PHP and Arabic Language - Index
webhostingguy
 

Similar to Working with Data and built-in functions of PHP (20)

Php forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligetiPhp forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligeti
 
SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2
 
API_Testing_with_Postman
API_Testing_with_PostmanAPI_Testing_with_Postman
API_Testing_with_Postman
 
javascript.pptx
javascript.pptxjavascript.pptx
javascript.pptx
 
07 application security fundamentals - part 2 - security mechanisms - data ...
07   application security fundamentals - part 2 - security mechanisms - data ...07   application security fundamentals - part 2 - security mechanisms - data ...
07 application security fundamentals - part 2 - security mechanisms - data ...
 
WEB-MODULE 4.pdf
WEB-MODULE 4.pdfWEB-MODULE 4.pdf
WEB-MODULE 4.pdf
 
SCWCD : The servlet model : CHAP : 2
SCWCD  : The servlet model : CHAP : 2SCWCD  : The servlet model : CHAP : 2
SCWCD : The servlet model : CHAP : 2
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6
 
Implementing Ajax In ColdFusion 7
Implementing Ajax In ColdFusion 7Implementing Ajax In ColdFusion 7
Implementing Ajax In ColdFusion 7
 
PHP Form Validation Technique
PHP Form Validation TechniquePHP Form Validation Technique
PHP Form Validation Technique
 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHP
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager
 
Security: Odoo Code Hardening
Security: Odoo Code HardeningSecurity: Odoo Code Hardening
Security: Odoo Code Hardening
 
Common Gateway Interface
Common Gateway InterfaceCommon Gateway Interface
Common Gateway Interface
 
GET and POST in PHP
GET and POST in PHPGET and POST in PHP
GET and POST in PHP
 
Data-Analytics using python (Module 4).pptx
Data-Analytics using python (Module 4).pptxData-Analytics using python (Module 4).pptx
Data-Analytics using python (Module 4).pptx
 
Tutorial_Rest_API_For_Beginners_125.pptx
Tutorial_Rest_API_For_Beginners_125.pptxTutorial_Rest_API_For_Beginners_125.pptx
Tutorial_Rest_API_For_Beginners_125.pptx
 
Security.ppt
Security.pptSecurity.ppt
Security.ppt
 
12-security.ppt - PHP and Arabic Language - Index
12-security.ppt - PHP and Arabic Language - Index12-security.ppt - PHP and Arabic Language - Index
12-security.ppt - PHP and Arabic Language - Index
 

Recently uploaded

Simple-Present-Tense xxxxxxxxxxxxxxxxxxx
Simple-Present-Tense xxxxxxxxxxxxxxxxxxxSimple-Present-Tense xxxxxxxxxxxxxxxxxxx
Simple-Present-Tense xxxxxxxxxxxxxxxxxxx
RandolphRadicy
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
deepaannamalai16
 
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptxBIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
RidwanHassanYusuf
 
skeleton System.pdf (skeleton system wow)
skeleton System.pdf (skeleton system wow)skeleton System.pdf (skeleton system wow)
skeleton System.pdf (skeleton system wow)
Mohammad Al-Dhahabi
 
How to Setup Default Value for a Field in Odoo 17
How to Setup Default Value for a Field in Odoo 17How to Setup Default Value for a Field in Odoo 17
How to Setup Default Value for a Field in Odoo 17
Celine George
 
NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
Payaamvohra1
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
zuzanka
 
The basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptxThe basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptx
heathfieldcps1
 
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
Kalna College
 
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
Nguyen Thanh Tu Collection
 
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
ImMuslim
 
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
EduSkills OECD
 
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdfREASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
giancarloi8888
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
MJDuyan
 
Accounting for Restricted Grants When and How To Record Properly
Accounting for Restricted Grants  When and How To Record ProperlyAccounting for Restricted Grants  When and How To Record Properly
Accounting for Restricted Grants When and How To Record Properly
TechSoup
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
nitinpv4ai
 
MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025
khuleseema60
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
PsychoTech Services
 
Contiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptxContiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptx
Kalna College
 
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
220711130083 SUBHASHREE RAKSHIT  Internet resources for social science220711130083 SUBHASHREE RAKSHIT  Internet resources for social science
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
Kalna College
 

Recently uploaded (20)

Simple-Present-Tense xxxxxxxxxxxxxxxxxxx
Simple-Present-Tense xxxxxxxxxxxxxxxxxxxSimple-Present-Tense xxxxxxxxxxxxxxxxxxx
Simple-Present-Tense xxxxxxxxxxxxxxxxxxx
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
 
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptxBIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
 
skeleton System.pdf (skeleton system wow)
skeleton System.pdf (skeleton system wow)skeleton System.pdf (skeleton system wow)
skeleton System.pdf (skeleton system wow)
 
How to Setup Default Value for a Field in Odoo 17
How to Setup Default Value for a Field in Odoo 17How to Setup Default Value for a Field in Odoo 17
How to Setup Default Value for a Field in Odoo 17
 
NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
 
The basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptxThe basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptx
 
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
 
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
 
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
 
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
 
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdfREASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
 
Accounting for Restricted Grants When and How To Record Properly
Accounting for Restricted Grants  When and How To Record ProperlyAccounting for Restricted Grants  When and How To Record Properly
Accounting for Restricted Grants When and How To Record Properly
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
 
MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
 
Contiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptxContiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptx
 
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
220711130083 SUBHASHREE RAKSHIT  Internet resources for social science220711130083 SUBHASHREE RAKSHIT  Internet resources for social science
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
 

Working with Data and built-in functions of PHP

  • 1. Working with Data Ms. Mohana Priya S Department of computer Science[UG]
  • 2. Validate input field in the HTML Form • To validate the form using HTML, we will use the HTML <input> required attribute. • The <input> required attribute is a Boolean attribute that is used to specify the input element that must be filled out before submitting the Form.
  • 3. Data validation ensures accurate and useful user input. It checks for completed required fields, valid dates, and appropriate data types. • Required Fields: Users must fill in all mandatory fields to avoid incomplete submissions. • Date Validation: Ensures users enter dates in the correct format. • Numeric Field Text: Verifies users enter text in text fields and numeric values in numeric fields.
  • 4. Validation takes place either on the server side (after data submission) or on the client side (prior to data submission). • Server-side: Done by the web server for data integrity and security. • Client-side: Performed by the browser for instant user feedback.
  • 5. <form action="#"> <label for="fname">First Name:</label> <input type="text" name="fname" id="fname" required> <br><br> <label for="lname">Last Name:</label> <input type="text" name="lname" id="lname" required> <br><br> <label for="email">Email Id:</label> <input type="email" name="email" id="email" required> <br><br> <input type="submit" value="Submit"> </form>
  • 6. <label for="phone">Phone:</label> <input type="number" id="phone" name="phone" pattern="[0-9]{10}" placeholder="Enter 10-digit mobile number" required><br>
  • 7. Passing variables with data between pages
  • 8. Pass values of variables between pages in site. These are required in many different ways. Some time we collect some value from a database and want to retain the value for the particular user throughout the site as the user moves between pages. There are different ways for passing such values of the variables.
  • 9. Passing variable values between pages using session This is one of the secured ways the variables are passed between pages. The best example of such a system is when we see our user- id inside a member area after we logged in. In a member login system the user details are verified and once found correct, a new session is created and with user id of the member and this value is stored at server end. Every time a new page is opened by the browser, the server checks the associated session value and display the user id. This system is more secure and the member doesn't get any chance to change the values.
  • 10. Passing variables between pages using cookies Cookies are stored at the user or the client end and values can be passed between pages using PHP. But here the client browser can reject accepting cookies by changing the security settings of the browser. So this system can fail to pass values between pages if user or client end settings are changed. But cookies are quit useful in handling user entered values and passing them between pages.
  • 11. Passing variables between pages using URL Pass variable values between pages through the URL ( in address bar of the browser). Here values are visible to the user and others as they appear in the address bar and also in the browser history. This is not a secure way to transfer sensitive data like password, etc.
  • 12. Advantage of using URL to pass variables • The advantage is we can pass data to a different site even running at different servers. Any scripting language like ASP, JSP, PHP • Easy to save the URL or bookmark it for frequent use. • Copy the URL and send it to a friend to refer.
  • 13. Example of passing data through URL within a site. <a href='page2.php?id=2489&user=tom'>link to page2</a> When the above link is clicked, page2.php gets the variables id and user with data 2489 and tom respectively. Code to collect data in PHP. echo $_GET['id']; // output 2489 echo $_GET['user']; // output tom
  • 14. Passing data outside <a href=https://www.sitename.com/index.php?id=2489&user=tom>Link to another site</a> Note that after the page name we are using question mark ( ? ) to start the variable data pair and we are separating each variable data pair with one ampersand ( & ) mark.
  • 15. Submitting form values through GET method A web form when the method is set to GET method, it submits the values through URL. So we can use one form to generate an URL with variables and data by taking inputs from the users. The form will send the data to a page within the site or outside the site by formatting a query string. <form method=GET action='https://www.anysite.com/index.php'>
  • 16. Submitting a form through POST method By post method of form submission we can send more number or length of data. Sensitive information like password does not get exposed in URL by POST method, so our login forms we should use POST method to submit data. This is how we collect data submitted by POST method in PHP $id=$_POST['id']; $password=$_POST['password'];
  • 17. Difference between GET and POST Issues GET POST Browser History Data remain in Browser History Data Not available in Browser History Bookmark URL with Data can be bookmarked No data is available in URL to bookmark the page Data Length Restriction The restriction (of URL ) is applicable No Restriction cached Can be cached No meaningful caching Sensitive Data Data like password , pin etc. are exposed through URL so they should not be passed using GET method Better than GET method as data is not exposed through URL
  • 18. Collecting data submitted by either GET or POST method If a page is receiving a data which can come in any one of the method GET or POST then how to collect it ? Here we are not sure how to collect the data. So we will use like this. $id=$_REQUEST['id']; $password=$_REQUEST['password'];
  • 19. PHP - $_REQUEST $_REQUEST $_REQUEST is a PHP super global variable which contains submitted form data, and all cookie data. In other words, $_REQUEST is an array containing data from $_GET, $_POST, and $_COOKIE. You can access this data with the $_REQUEST keyword followed by the name of the form field, or cookie, like this: $_REQUEST['firstname']
  • 20. String Function chr() • It is used to return a character from a specified ASCII value • The PHP chr() function is used to generate a single byte string from a number. In another words we can say that it returns a character from specified ASCII value. • Syntax: string chr ( int $bytevalue );
  • 21. Example 1: <?php $char =52; echo "Your character is :".$char; echo "<br>"."By using 'chr()' function your value is: ".chr($char);// d ecimal Value ?> • Your character is : 52 By using 'chr()' function your value is: 4
  • 22. Example 2: <?php $char =052; echo "Your character is :".$char; echo "<br>"."By using 'chr()' function your value is: ".chr($char); // O ctal Value ?> • Your character is :42 By using 'chr()' function your value is: *
  • 23. <?php echo "Your character is :0x52"; echo "<br>"."By using 'chr()' function your value is: ".chr(0x52); // H ex value ?> • Your character is :0x52 By using 'chr()' function your value is: R
  • 24. ord() • Returns the ASCII value of the first character of a string. Definition and Usage The ord() function returns the ASCII value of the first character of a string. Syntax: ord(string) <?php echo ord("h")."<br>"; echo ord("hello")."<br>"; ?> O/P: 104 104
  • 25. • strtolower() hello world PHP string functions <?php echo strtolower("HELLO WORLD."); ?>
  • 26. • strtoupper() • Convert all characters to uppercase: <?php echo strtoupper("Hello WORLD!"); ?> HELLO WORLD
  • 27. • lcfirst() - converts the first character of a string to lowercase • ucfirst() - converts the first character of a string to uppercase • ucwords() - converts the first character of each word in a string to uppercase
  • 28.
  • 33. ltrim() - Removes whitespace or other characters from the left side of a string Definition and Usage The ltrim() function removes whitespace or other predefined characters from the left side of a string. Related functions: •rtrim() - Removes whitespace or other predefined characters from the right side of a string •trim() - Removes whitespace or other predefined characters from both sides of a string
  • 34. • Syntax ltrim(string,charlist) • string Required. Specifies the string to check • charlist Optional. Specifies which characters to remove from the string. If omitted, all of the following characters are remove "0" - NULL "t" - tab "n" - new line "x0B" - vertical tab "r" - carriage return " " - ordinary white space
  • 35. • Remove newlines (n) from the left side of a string: • <?php $str = "nnnHello World!"; echo "Without ltrim: " . $str; echo "<br>"; echo "With ltrim: " . ltrim($str); ?>
  • 37. <!DOCTYPE html> <html> <body> <?php // Positive numbers: echo substr("Hello world",10)."<br>"; echo substr("Hello world",1)."<br>"; echo substr("Hello world",7)."<br>"; echo "<br>"; // Negative numbers: echo substr("Hello world",-1)."<br>"; echo substr("Hello world",-10)."<br>"; echo substr("Hello world",-4)."<br>"; ?> </body> </html> O/p: d ello world orld d ello world orld <!DOCTYPE html> <html> <body> <?php echo substr("Hello world",6); ?> </body> </html> O/p: world
  • 38. The strcmp() function compares two strings. • The strcmp() function compares two strings. • Note: The strcmp() function is binary-safe and case-sensitive. • Tip: This function is similar to the strncmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncmp(). Syntax strcmp(string1,string2)
  • 39. Return Value <!DOCTYPE html> <html> <body> <?php echo strcmp("Hello world!","Hello world!")."<br>"; // the two strings are equal echo strcmp("Hello world!","Hello")."<br>"; // string1 is greater than string2 echo strcmp("Hello world!","Hello world! Hello!")."<br>"; // string1 is less than string2 ?> </body> </html> o/p: 0 7 -7 This function returns: 0 - if the two strings are equal <0 - if string1 is less than string2 >0 - if string1 is greater than string2
  • 40. strpos() - Search For a Text Within a String • The PHP strpos() function searches for a specific text within a string. If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE. Example Search for the text "world" in the string "Hello world!": <?php echo strpos("Hello world!", "world"); // outputs 6 ?>
  • 41. Replace Text Within a String The PHP str_replace() function replaces some characters with some other characters in a string. Example Replace the text "world" with "Dolly": <?php echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly! ?>
  • 42. str_word_count() - Count Words in a String The PHP str_word_count() function counts the number of words in a string. Example Count the number of word in the string "Hello world!": <?php echo str_word_count("Hello world!"); // outputs 2 ?>
  • 43. Math functions •PHP provides many predefined math constants and functions that can be used to perform mathematical operations.
  • 44. Math functions in PHP • abs() • Ceil() • Floor() • Round() • Fmod() • Min() • Max() • Pow() • Sqrt() • Rand()
  • 45. Abs() • The abs() function returns the absolute (positive) value of a number. Syntax: abs( value ) Parameters: The abs() function accepts single parameter value which holds the number whose absolute value you want to find. Return Value: It returns the absolute value of the number passed to it as argument. • number Required. Specifies a number. If the number is of type float, the return type is also float, otherwise it is integer
  • 46. • The abs() function in PHP is identical to what we call modulus in mathematics. The modulus or absolute value of a negative number is positive.
  • 47. Example • <?php echo(abs(6.7) . "<br>"); echo(abs(-6.7) . "<br>"); echo(abs(-3) . "<br>"); echo(abs(3)); ?> Output • 6.7 6.7 3 3
  • 48. Ceil() • The ceil() function rounds a number UP to the nearest integer. Syntax: float ceil(value) • Parameters: The ceil() function accepts a single parameter value which represents the number which you want to round up to the nearest greater integer. • Return Value: The return type of the ceil() function is float as shown in the syntax. It returns the number which represents the value rounded up to the next highest integer. • number Required. Specifies the value to round up
  • 49. Example • Output • 1 1 5 6 -5 -5 • <?php echo(ceil(0.60) . "<br>"); echo(ceil(0.40) . "<br>"); echo(ceil(5) . "<br>"); echo(ceil(5.1) . "<br>"); echo(ceil(-5.1) . "<br>"); echo(ceil(-5.9)); ?>
  • 50. Floor() • The floor() function rounds a number DOWN to the nearest integer. Syntax: float floor(value) • Parameters: This function accepts the single parameter value which is rounded down to the next lowest integer. • Return Value: The return type is a float value. It returns the next lowest integer value as a float which is rounded down, only if necessary. • number Required. Specifies the value to round down
  • 51. Example • <?php echo(floor(0.60) . "<br>"); echo(floor(0.40) . "<br>"); echo(floor(5) . "<br>"); echo(floor(5.1) . "<br>"); echo(floor(-5.1) . "<br>"); echo(floor(-5.9)); ?> Output • 0 0 5 5 -6 -6
  • 52. Round() • The round() function rounds a floating-point number. • Syntax: round(number,precision,mode); • Parameters: It accepts three parameters out of which one is compulsory and two are optional. All of these parameters are described below: • $number: It is the number which you want to round. • $precision: It is an optional parameter. It specifies the number of decimal digits to round to. The default value of this parameter is zero. • $mode: It is an optional parameter. It specifies a constant to specify the rounding mode. • number Required. Specifies the value to round precision • Optional. Specifies the number of decimal digits to round to. Default is 0
  • 53. Round() • The round() function rounds a floating-point number. • Syntax: round(number,precision,mode); • Parameters: It accepts three parameters out of which one is compulsory and two are optional. All of these parameters are described below: • $number: It is the number which you want to round. • $precision: It is an optional parameter. It specifies the number of decimal digits to round to. The default value of this parameter is zero. • $mode: It is an optional parameter. It specifies a constant to specify the rounding mode. • number Required. Specifies the value to round precision • Optional. Specifies the number of decimal digits to round to. Default is 0
  • 54. • mode Optional. Specifies a constant to specify the rounding mode: PHP_ROUND_HALF_UP - Default. Rounds number up to precision decimal, when it is half way there. Rounds 1.5 to 2 and -1.5 to -2 • PHP_ROUND_HALF_DOWN - Round number down to precision decimal places, when it is half way there. Rounds 1.5 to 1 and -1.5 to -1 • PHP_ROUND_HALF_EVEN - Round number to precision decimal places towards the next even value • PHP_ROUND_HALF_ODD - Round number to precision decimal places towards the next odd value
  • 55. Example 1 • <?php echo(round(0.60) . "<br>"); echo(round(0.50) . "<br>"); echo(round(0.49) . "<br>"); echo(round(-4.40) . "<br>"); echo(round(-4.60)); ?> • Output • 1 1 0 -4 -5
  • 56. Example 2 • <?php echo(round(4.96754,2) . "<br>"); echo(round(7.045,2) . "<br>"); echo(round(7.055,2)); ?> • 4.97 7.05 7.06
  • 57. • <?php echo(round(1.5,0,PHP_ROUND_HALF_UP) . "<br>"); echo(round(-1.5,0,PHP_ROUND_HALF_UP) . "<br>"); echo(round(1.5,0,PHP_ROUND_HALF_DOWN). "<br>"); echo(round(-1.5,0,PHP_ROUND_HALF_DOWN). "<br>"); echo(round(1.5,0,PHP_ROUND_HALF_EVEN) . "<br>"); echo(round(-1.5,0,PHP_ROUND_HALF_EVEN) . "<br>"); echo(round(1.5,0,PHP_ROUND_HALF_ODD) . "<br>"); echo(round(-1.5,0,PHP_ROUND_HALF_ODD)); ?> Example 3 • Output 2 -2 1 -1 2 -2 1 -1
  • 58. Fmod() • The fmod() function returns the remainder (modulo) of x/y. • In PHP the fmod() function is used to calculate the Modulo of any division which may contain floats as both dividends and divisors. Syntax: float fmod ($dividend, $divisor) • Parameters: The function takes two parameters as follows: • $dividend: This parameter takes a float which is to be divided. • $divisor: This parameter takes a float which is to be used as a divisor. • Return Type: This function returns a Floating-point remainder of the division.
  • 59. Example • <?php $x = 7; $y = 2; $result = fmod($x,$y); echo $result; ?> Output 1
  • 60. Min () • The min() function returns the lowest value in an array, or the lowest value of several specified values. • The min() function can take an array or several numbers as an argument and return the numerically minimum value among the passed parameters. The return type is not fixed, it can be an integer value or a float value based on input. • Sytax: min(array_values); or min(value1,value2,...); • Parameters: This function accepts two different types of parameters which are explained below: • array_values : It specifies an array containing the values. • value1, value2, … : It specifies two or more than two values to be compared.
  • 61. Example • <?php echo(min(2,4,6,8,10) . "<br>"); echo(min(22,14,68,18,15) . "<br>"); echo(min(array(4,6,8,10)) . "<br>"); echo(min(array(44,16,81,12))); ?> Output 2 14 4 12
  • 62. Max() • The max() function returns the highest value in an array, or the highest value of several specified values. • The max() function of PHP is used to find the numerically maximum value in an array or the numerically maximum value of several specified values. • The max() function can take an array or several numbers as an argument and return the numerically maximum value among the passed parameters. The return type is not fixed, it can be an integer value or a float value based on input. • Sytax: max(array_values); or max(value1,value2,...); • Parameters: This function accepts two different types of arguments which are explained below: • array_values : It specifies an array containing the values. • value1, value2, … : It specifies two or more than two values to be compared.
  • 63. • <html> <body> <?php echo(max(2,4,6,8,10) . "<br>"); echo(max(22,14,68,18,15) . "<br>"); echo(max(array(4,6,8,10)) . "<br>"); echo(max(array(44,16,81,12))); ?> </body> </html>
  • 64. Pow() • The pow() function returns ($base raised to the power of $exp. • Syntax: number pow($base, $exp); • Parameters : The pow() function accepts two parameters as shown in the above syntax: • $base : It is used to specify the base. • $exponent : It is used to specify the exponent. • Return Value: It returns a number (integer or floating-point) which is equal to $base raised to the power of $exponent.
  • 65. <html> <body> <?php echo(pow(2,4) . "<br>"); //16 echo(pow(-2,4) . "<br>");//16 echo(pow(-2,-4) . "<br>");//0.0625 ?> </body> </html> Input : pow(3, 2) Output : 9 Input : pow(-3, 2) Output : 9 Input : pow(-3, -3) Output : 0.037037037037037 Input : pow(-3, -3.2) Output : NaN
  • 66. Sqrt() • The sqrt() function returns the square root of a number. • Syntax: sqrt(number); • number Required. Specifies a number
  • 67. Example <?php echo(sqrt(0) . "<br>"); // 0 echo(sqrt(1) . "<br>"); // 1 echo(sqrt(9) . "<br>"); // 3 echo(sqrt(0.64) . "<br>"); // 0.8 ?>
  • 68. Rand() • The rand() function generates a random integer. • The rand() is an inbuilt function in PHP used to generate a random number ie., it can generate a random integer value in the range [min, max]. • rand(); or rand(min,max); • Parameter values: • min: It is an optional parameter that specifies the lowest value that will be returned. The default value is 0. • max: It is an optional parameter that specifies the highest value to be returned. The default value is getrandmax().
  • 69. Examples: Note: The output of the code may change every time it is run. So the output may not match with the specified output. <?php // Generating a random number $randomNumber= rand(); print_r($randomNumber); print_r("n"); // Generating a random number in a // Specified range. $randomNumber= rand(15,35); print_r($randomNumber); ?> output: 1257424548 28
  • 70. PHP Array Functions • count, • list, • in_array, • current, • next, • previous, • end, • each
  • 71. Array() • The array() function is used to create a PHP array. This function can be used to create indexed arrays or associative arrays. PHP arrays could be single dimensional or multi-dimensional. Syntax Syntax to create PHP indexed arrays: $a = array(value1, value2, value3, ...) Syntax to create PHP associative arrays: $a = array(key1 => value1, key2 => value2...)
  • 72. Example • <?php $cars=array("Volvo","BMW","Toyota"); echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; ?> • I like Volvo, BMW and Toyota.
  • 73. Count() • The count() function returns the number of elements in an array. Syntax count(array, mode)
  • 74.
  • 75. in_array — Checks if a value exists in an array • Syntax: • in_array(search, array, type)
  • 76. in_array example • <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); if (in_array("Glenn", $people)) { echo "Match found"; } else { echo "Match not found"; } ?> • o/p: Match found
  • 77. list() function • The list() function is used to assign values to a list of variables in one operation. • Syntax: • list(var1, var2, ...)
  • 78. Example • <?php $my_array = array("Dog","Cat","Horse"); list($a, , $c) = $my_array; echo "Here I only use the $a and $c variables."; ?> • o/p: Here I only use the Dog and Horse variables.
  • 79. current() function • Definition and Usage • The current() function returns the value of the current element in an array. • Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array.
  • 80. Related current methods: • end() - moves the internal pointer to, and outputs, the last element in the array • next() - moves the internal pointer to, and outputs, the next element in the array • prev() - moves the internal pointer to, and outputs, the previous element in the array • reset() - moves the internal pointer to the first element of the array • each() - returns the current element key and value, and moves the internal pointer forward Syntax: current(array)
  • 81. <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo current($people) . "<br>"; // The current element is Peter echo next($people) . "<br>"; // The next element of Peter is Joe echo current($people) . "<br>"; // Now the current element is Joe echo prev($people) . "<br>"; // The previous element of Joe is Peter echo end($people) . "<br>"; // The last element is Cleveland echo prev($people) . "<br>"; // The previous element of Cleveland is Glenn echo current($people) . "<br>"; // Now the current element is Glenn echo reset($people) . "<br>"; // Moves the internal pointer to the first element of the array, which is Peter echo next($people) . "<br>"; // The next element of Peter is Joe print_r (each($people)); // Returns the key and value of the current element (now Joe), and moves the internal pointer forward ?> Peter Joe Joe Peter Cleveland Glenn Glenn Peter Joe Array ( [1] => Joe [value] => Joe [0] => 1 [key] => 1 )
  • 82. PHP Include File • The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. • Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website. • It is possible to insert the content of one PHP file into another PHP file (before the server executes it), with the include or require statement. • The include and require statements are identical, except upon failure: • require will produce a fatal error (E_COMPILE_ERROR) and stop the script • include will only produce a warning (E_WARNING) and the script will continue
  • 83. PHP include and require • Including files saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. Then, when the header needs to be updated, you can only update the header include file. Syntax • include 'filename'; or require 'filename';
  • 84. Advantage • Code Reusability: By the help of include and require construct, we can reuse HTML code or PHP script in many PHP scripts.
  • 85. PHP include example • PHP include is used to include file on the basis of given path. You may use relative or absolute path of the file. • Let's see a simple PHP include example. Example 1 Assume we have a standard footer file called "footer.php", that looks like this: <?php echo "<p>Copyright &copy; 1999-" . date("Y") . " kristujayanti.edu.in </p>"; ?> To include the footer file in a page, use the include statement: Example <html> <body> <h1>Welcome to my home page!</h1> <p>Some text.</p> <p>Some more text.</p> <?php include 'footer.php';?> </body> </html>
  • 86. PHP Functions • PHP function is a piece of code that can be reused many times. • It can take input as argument list and return value. • There are thousands of built-in functions in PHP.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91. Parameterized Function • PHP Parameterized functions are the functions with parameters. You can pass any number of parameters inside a function. These passed parameters act as variables inside your function. • They are specified inside the parentheses, after the function name. • The output depends upon the dynamic values passed as the parameters into the function.
  • 92.
  • 93.
  • 96. PHP Superglobals PHP provides an additional set of predefined arrays containing variables from the web server the environment, and user input. These new arrays are called superglobals.
  • 97. $GLOBALS Contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables.
  • 98. Example • <?php $x = 75; $y = 25; function addition() { $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; } addition(); echo $z; ?> • OUTPUT: 100
  • 99. $_SERVER • This is an array containing information such as headers, paths, and script locations. • The entries in this array are created by the web server. • There is no guarantee that every web server will provide any of these.
  • 100. Example • <?php echo $_SERVER['PHP_SELF']; echo "<br>"; echo $_SERVER['SERVER_NAME']; echo "<br>"; echo $_SERVER['HTTP_HOST']; echo "<br>"; echo $_SERVER['HTTP_REFERER']; echo "<br>"; echo $_SERVER['HTTP_USER_AGENT']; echo "<br>"; echo $_SERVER['SCRIPT_NAME']; ?> OUTPUT: /demo/demo_global_server.php 35.194.26.41 35.194.26.41 https://tryphp.w3schools.com/showphp.php?filename=demo_global_server Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0 /demo/demo_global_server.php
  • 101. $_GET •An associative array of variables passed to the current script via the HTTP GET method.
  • 102. $_POST • An associative array of variables passed to the current script via the HTTP POST method.
  • 103. $_REQUEST • An associative array consisting of the contents of $_GET, $_POST, and $_COOKIE. • <!DOCTYPE html> <html> <body> <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> Name: <input type="text" name="fname"> <input type="submit"> </form> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // collect value of input field $name = htmlspecialchars($_REQUEST['fname']); if (empty($name)) { echo "Name is empty"; } else { echo $name; } } ?> </body>
  • 104. $_PHP_SELF • A string containing PHP script file name in which it is called. $_SERVER['PHP_SELF'] • The filename of the currently executing script, relative to the document root $_SERVER['SERVER_NAME'] • The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.