ch9.pdf
Document Details
Uploaded by ProdigiousQuantum
null
2021
Tags
Full Transcript
JTO Phase-II IT PHP 9 PHP (PHP: HYPERTEXT PREPROCESSOR) 9.1 INTRODUCTION PHP chapter for beginners and professionals provides deep knowledge of PHP scrip...
JTO Phase-II IT PHP 9 PHP (PHP: HYPERTEXT PREPROCESSOR) 9.1 INTRODUCTION PHP chapter for beginners and professionals provides deep knowledge of PHP scripting language. Our PHP chapter will help you to learn PHP scripting language easily. This PHP chapter covers all the topics of PHP such as introduction, control statements, functions, array, string, file handling, form handling, regular expression, date and time, object- oriented programming in PHP, math, PHP mysql, PHP with ajax, PHP with jquery and PHP with XML. 9.2 WHAT IS PHP PHP stands for HyperText Preprocessor. PHP is an interpreted language, i.e. there is no need for compilation. PHP is a server side scripting language. PHP is faster than other scripting language e.g. asp and jsp. 9.3 PHP EXAMPLE In this chapter, you will get a lot of PHP examples to understand the topic well. The PHP file must be save with.php extension. Let's see a simple PHP example. File: hello.php Output: Hello by PHP 9.4 WEB DEVELOPMENT PHP is widely used in web development now a days. Dynamic websites can be easily developed by PHP. But you must have the basic the knowledge of following technologies for web development as well. HTML CSS JavaScript JTO Phase –II DNIT Version 1.0 Sep 2021 Page 95 of 167 For Restricted Circulation JTO Phase-II IT PHP AJAX XML and JSON JQuery Prerequisite Before learning PHP, you must have the basic knowledge of HTML. Install PHP To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software stack. It is available for all operating systems. There are many AMP options available in the market that are given below: WAMP for Windows LAMP for Linux MAMP for Mac SAMP for Solaris FAMP for FreeBSD XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some other components too such as FileZilla, OpenSSL, Webalizer, Mercury Mail etc. If you are on Windows and don't want Perl and other features of XAMPP, you should go for WAMP. In a similar way, you may use LAMP for Linux and MAMP for Macintosh. PHP Example It is very easy to create a simple PHP example. To do so, create a file and write HTML tags + PHP code and save this file with.php extension. All PHP code goes between php tag. A syntax of PHP tag is given below: Let's see a simple PHP example where we are writing some text using PHP echo command. File: first.php Output: Hello First PHP PHP Echo JTO Phase –II DNIT Version 1.0 Sep 2021 Page 96 of 167 For Restricted Circulation JTO Phase-II IT PHP PHP echo is a language construct not a function, so you don't need to use parenthesis with it. But if you want to use more than one parameters, it is required to use parenthesis. The syntax of PHP echo is given below: void echo ( string $arg1 [, string $... ] ) PHP echo statement can be used to print string, multi line strings, escaping characters, variable, array etc. PHP echo: printing string File: echo1.php Output: Hello by PHP echo PHP echo: printing multi line string File: echo2.php Output: Hello by PHP echo this is multi line text printed by PHP echo statement PHP echo: printing escaping characters File: echo3.php Output: Hello escape "sequence" characters PHP echo: printing variable value File: echo4.php JTO Phase –II DNIT Version 1.0 Sep 2021 Page 97 of 167 For Restricted Circulation JTO Phase-II IT PHP Output: Message is: Hello JavaTpoint PHP PHP Print Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with the argument list. Unlike echo, it always returns 1. The syntax of PHP print is given below: int print(string $arg) PHP print statement can be used to print string, multi line strings, escaping characters, variable, array etc. PHP print: printing string File: print1.php Output: Hello by PHP print Hello by PHP print() PHP print: printing multi line string File: print2.php Output: Hello by PHP print this is multi line text printed by PHP print statement PHP print: printing escaping characters File: print3.php Output: Hello escape "sequence" characters by PHP print PHP print: printing variable value JTO Phase –II DNIT Version 1.0 Sep 2021 Page 98 of 167 For Restricted Circulation JTO Phase-II IT PHP File: print4.php Output: Message is: Hello print() in PHP 9.5 PHP VARIABLES A variable in PHP is a name of memory location that holds data. A variable is a temporary storage that is used to store data temporarily. In PHP, a variable is declared using $ sign followed by variable name. Syntax of declaring a variable in PHP is given below: $variablename=value; PHP Variable: Declaring string, integer and float Let's see the example to store string, integer and float values in PHP variables. File: variable1.php Output: string is: hello string integer is: 200 float is: 44.6 PHP Variable: Sum of two variables File: variable2.php Output: JTO Phase –II DNIT Version 1.0 Sep 2021 Page 99 of 167 For Restricted Circulation JTO Phase-II IT PHP 11 PHP Variable: case sensitive In PHP, variable names are case sensitive. So variable name "color" is different from Color, COLOR, COLor etc. File: variable3.php Output: My car is red Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4 My house is Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5 My boat is PHP Variable: Rules PHP variables must start with letter or underscore only. PHP variable can't be start with numbers and special symbols. File: variablevalid.php Output: hello hello File: variableinvalid.php Output: JTO Phase –II DNIT Version 1.0 Sep 2021 Page 100 of 167 For Restricted Circulation JTO Phase-II IT PHP Parse error: syntax error, unexpected '4' (T_LNUMBER), expecting variable (T_VARIABLE) or '$' in C:\wamp\www\variableinvalid.php on line 2 9.6 PHP: LOOSELY TYPED LANGUAGE PHP is a loosely typed language, it means PHP automatically converts the variable to its correct data type. PHP $ and $$ Variables The $var (single dollar) is a normal variable with the name var that stores any value like string, integer, float, etc. The $$var (double dollar) is a reference variable that stores the value of the $variable inside it. To understand the difference better, let's see some examples. Example 1 Output: In the above example, we have assigned a value to the variable x as abc. Value of reference variable $$x is assigned as 200. Now we have printed the values $x, $$x and $abc. Example2 JTO Phase –II DNIT Version 1.0 Sep 2021 Page 101 of 167 For Restricted Circulation JTO Phase-II IT PHP Output: In the above example, we have assigned a value to the variable x as U.P. Value of reference variable $$x is assigned as Lucknow. Now we have printed the values $x, $$x and a string. Example3 Output: In the above example, we have assigned a value to the variable name Cat. Value of reference variable ${$name} is assigned as Dog and ${${$name}} as Monkey. Now we have printed the values as $name, ${$name}, $Cat, ${${$name}} and $Dog. 9.7 PHP CONSTANTS PHP constants are name or identifier that can't be changed during the execution of the script. PHP constants can be defined by 2 ways: 1 Using define() function JTO Phase –II DNIT Version 1.0 Sep 2021 Page 102 of 167 For Restricted Circulation JTO Phase-II IT PHP 2 Using const keyword PHP constants follow the same PHP variable rules. For example, it can be started with letter or underscore only. Conventionally, PHP constants should be defined in uppercase letters. PHP constant: define() Let's see the syntax of define() function in PHP. 1 define(name, value, case-insensitive) 2 name: specifies the constant name 3 value: specifies the constant value 4 case-insensitive: Default value is false. It means it is case sensitive by default. Let's see the example to define PHP constant using define(). File: constant1.php Output: Hello JavaTpoint PHP File: constant2.php Output: Hello JavaTpoint PHP File: constant3.php Output: Hello JavaTpoint PHP PHP constant: const keyword The const keyword defines constants at compile time. It is a language construct not a function. It is bit faster than define(). JTO Phase –II DNIT Version 1.0 Sep 2021 Page 103 of 167 For Restricted Circulation JTO Phase-II IT PHP It is always case sensitive. File: constant4.php Output: Hello const by JavaTpoint PHP 9.8 PHP DATA TYPES PHP data types are used to hold different types of data or values. PHP supports 8 primitive data types that can be categorized further in 3 types: 1 Scalar Types 2 Compound Types 3 Special Types PHP Data Types: Scalar Types There are 4 scalar data types in PHP. 1 boolean 2 integer 3 float 4 string PHP Data Types: Compound Types There are 2 compound data types in PHP. 1 array 2 object PHP Data Types: Special Types There are 2 special data types in PHP. 1 resource 2 NULL 9.9 PHP OPERATORS PHP Operator is a symbol i.e used to perform operations on operands. For example: $num=10+20;//+ is the operator and 10,20 are operands In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable. PHP Operators can be categorized in following forms: Arithmetic Operators Comparison Operators Bitwise Operators JTO Phase –II DNIT Version 1.0 Sep 2021 Page 104 of 167 For Restricted Circulation JTO Phase-II IT PHP Logical Operators String Operators Incrementing/Decrementing Operators Array Operators Type Operators Execution Operators Error Control Operators Assignment Operators We can also categorize operators on behalf of operands. They can be categorized in 3 forms: Unary Operators: works on single operands such as ++, -- etc. Binary Operators: works on two operands such as binary +, -, *, / etc. Ternary Operators: works on three operands such as "?:". 9.10 PHP COMMENTS PHP comments can be used to describe any line of code so that other developer can understand the code easily. It can also be used to hide any code. PHP supports single line and multi line comments. These comments are similar to C/C++ and Perl style (Unix shell style) comments. PHP Single Line Comments There are two ways to use single line comments in PHP. // (C++ style single line comment) # (Unix Shell style single line comment) Output: Welcome to PHP single line comments PHP Multi Line Comments In PHP, we can comments multiple lines also. To do so, we need to enclose all lines within. Let's see a simple example of PHP multiple line comment. Output: Welcome to PHP multi line comment 9.11 PHP CONTROL STATEMENTS PHP If Else PHP if else statement is used to test condition. There are various ways to use if statement in PHP. if if-else if-else-if nested if PHP If Statement PHP if statement is executed if condition is true. Syntax 1 if(condition){ 2 //code to be executed 3 } Flowchart Example JTO Phase –II DNIT Version 1.0 Sep 2021 Page 106 of 167 For Restricted Circulation JTO Phase-II IT PHP Output: 12 is less than 100 PHP If-else Statement PHP if-else statement is executed whether condition is true or false. Syntax if(condition){ //code to be executed if true }else{ //code to be executed if false } Flowchart Example Output: 12 is even number PHP Switch PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if statement. Syntax switch(expression){ case value1: //code to be executed break; case value2: //code to be executed break;...... default: code to be executed if all cases are not matched; } PHP Switch Flowchart JTO Phase –II DNIT Version 1.0 Sep 2021 Page 108 of 167 For Restricted Circulation JTO Phase-II IT PHP PHP Switch Example Output: number is equal to 20 PHP For Loop JTO Phase –II DNIT Version 1.0 Sep 2021 Page 109 of 167 For Restricted Circulation JTO Phase-II IT PHP PHP for loop can be used to traverse set of code for the specified number of times. It should be used if number of iteration is known otherwise use while loop. Syntax for(initialization; condition; increment/decrement){ //code to be executed } Flowchart Example Output: 1 2 3 4 5 6 7 8 9 10 PHP Nested For Loop We can use for loop inside for loop in PHP, it is known as nested for loop. In case of inner or nested for loop, nested for loop is executed fully for one outer for loop. If outer for loop is to be executed for 3 times and inner for loop for 3 times, inner for JTO Phase –II DNIT Version 1.0 Sep 2021 Page 110 of 167 For Restricted Circulation JTO Phase-II IT PHP loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop). Example Output: 11 12 13 21 22 23 31 32 33 PHP For Each Loop PHP for each loop is used to traverse array elements. Syntax foreach( $array as $var ){ //code to be executed } ?> Example Output: Season is: summer Season is: winter JTO Phase –II DNIT Version 1.0 Sep 2021 Page 111 of 167 For Restricted Circulation JTO Phase-II IT PHP Season is: spring Season is: autumn PHP While Loop PHP while loop can be used to traverse set of code like for loop. It should be used if number of iteration is not known. Syntax while(condition){ //code to be executed } Alternative Syntax while(condition): //code to be executed endwhile; PHP While Loop Flowchart PHP While Loop Example Output: 1 2 3 4 5 6 7 8 JTO Phase –II DNIT Version 1.0 Sep 2021 Page 112 of 167 For Restricted Circulation JTO Phase-II IT PHP 9 10 Alternative Example Output: 1 2 3 4 5 6 7 8 9 10 PHP Nested While Loop We can use while loop inside another while loop in PHP, it is known as nested while loop. In case of inner or nested while loop, nested while loop is executed fully for one outer while loop. If outer while loop is to be executed for 3 times and nested while loop for 3 times, nested while loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop). Example Output: 11 12 13 21 22 23 31 32 33 PHP do while loop PHP do while loop can be used to traverse set of code like php while loop. The PHP do-while loop is guaranteed to run at least once. It executes the code at least one time always because condition is checked after executing the code. Syntax do{ //code to be executed }while(condition); Flowchart JTO Phase –II DNIT Version 1.0 Sep 2021 Page 114 of 167 For Restricted Circulation JTO Phase-II IT PHP Example Output: 1 2 3 4 5 6 7 8 9 10 PHP Break PHP break statement breaks the execution of current for, while, do-while, switch and for-each loop. If you use break inside inner loop, it breaks the execution of inner loop only. Syntax jump statement; break; Flowchart JTO Phase –II DNIT Version 1.0 Sep 2021 Page 115 of 167 For Restricted Circulation JTO Phase-II IT PHP PHP Break: inside loop Let's see a simple example to break the execution of for loop if value of i is equal to 5. Output: 1 2 3 4 5 9.12 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. In PHP, we can define Conditional function, Function within Function and Recursive function also. Advantage of PHP Functions JTO Phase –II DNIT Version 1.0 Sep 2021 Page 116 of 167 For Restricted Circulation JTO Phase-II IT PHP Code Reusability: PHP functions are defined only once and can be invoked many times, like in other programming languages. Less Code: It saves a lot of code because you don't need to write the logic many times. By the use of function, you can write the logic only once and reuse it. Easy to understand: PHP functions separate the programming logic. So it is easier to understand the flow of the application because every logic is divided in the form of functions. PHP User-defined Functions We can declare and call user-defined functions easily. Let's see the syntax to declare user-defined functions. Syntax function functionname(){ //code to be executed } Note: Function name must be start with letter and underscore only like other labels in PHP. It can't be start with numbers or special symbols. PHP Functions Example File: function1.php Output: Hello PHP Function PHP Function Arguments We can pass the information in PHP function through arguments which is separated by comma. PHP supports Call by Value (default), Call by Reference, Default argument values and Variable-length argument list. Let's see the example to pass single argument in PHP function. File: functionarg.php Output: Hello Sonoo Hello Vimal Hello John Let's see the example to pass two argument in PHP function. File: functionarg2.php Output: Hello Sonoo, you are 27 years old Hello Vimal, you are 29 years old Hello John, you are 23 years old 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 Parameterized Example 1 Addition and Subtraction In this example, we have passed two parameters $x and $y inside two functions add() and sub(). Parameter Addition and Subtraction Example JTO Phase –II DNIT Version 1.0 Sep 2021 Page 118 of 167 For Restricted Circulation JTO Phase-II IT PHP /html> 9.13 PHP ARRAYS PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of similar type in a single variable. Advantage of PHP Array Less Code: We don't need to define multiple variables. Easy to traverse: By the help of single loop, we can traverse all the elements of an array. Sorting: We can sort the elements of array. PHP Array Types There are 3 types of array in PHP. 1 Indexed Array 2 Associative Array 3 Multidimensional Array PHP Indexed Array PHP index is represented by number which starts from 0. We can store number, string and object in the PHP array. All PHP array elements are assigned to an index number by default. There are two ways to define indexed array: 1st way: $season=array("summer","winter","spring","autumn"); 2nd way: JTO Phase –II DNIT Version 1.0 Sep 2021 Page 119 of 167 For Restricted Circulation JTO Phase-II IT PHP $season="summer"; $season="winter"; $season="spring"; $season="autumn"; Example File: array1.php Output: Season are: summer, winter, spring and autumn File: array2.php Output: Season are: summer, winter, spring and autumn PHP Associative Array We can associate name with each array elements in PHP using => symbol. There are two ways to define associative array: 1st way: $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000"); 2nd way: $salary["Sonoo"]="350000"; $salary["John"]="450000"; $salary["Kartik"]="200000"; Example File: arrayassociative1.php Output: Sonoo salary: 350000 John salary: 450000 Kartik salary: 200000 File: arrayassociative2.php Output: Sonoo salary: 350000 John salary: 450000 Kartik salary: 200000 PHP Indexed Array PHP indexed array is an array which is represented by an index number by default. All elements of array are represented by an index number which starts from 0. PHP indexed array can store numbers, strings or any object. PHP indexed array is also known as numeric array. Definition There are two ways to define indexed array: 1st way: $size=array("Big","Medium","Short"); 2nd way: $size="Big"; $size="Medium"; $size="Short"; PHP Indexed Array Example File: array1.php Output: Size: Big, Medium and Short File: array2.php Output: Size: Big, Medium and Short Traversing PHP Indexed Array We can easily traverse array in PHP using foreach loop. Let's see a simple example to traverse all the elements of PHP array. File: array3.php Output: Size is: Big Size is: Medium Size is: Short Count Length of PHP Indexed Array PHP provides count() function which returns length of an array. Output: 3 JTO Phase –II DNIT Version 1.0 Sep 2021 Page 122 of 167 For Restricted Circulation JTO Phase-II IT PHP PHP Associative Array PHP allows you to associate name/label with each array elements in PHP using => symbol. Such way, you can easily remember the element because each element is represented by label than an incremented number. Definition There are two ways to define associative array: 1st way: $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000"); 2nd way: 1 $salary["Sonoo"]="550000"; 2 $salary["Vimal"]="250000"; 3 $salary["Ratan"]="200000"; Example File: arrayassociative1.php Output: Sonoo salary: 550000 Vimal salary: 250000 Ratan salary: 200000 File: arrayassociative2.php Output: Sonoo salary: 550000 Vimal salary: 250000 Ratan salary: 200000 JTO Phase –II DNIT Version 1.0 Sep 2021 Page 123 of 167 For Restricted Circulation JTO Phase-II IT PHP PHP Multidimensional Array PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an array. PHP multidimensional array can be represented in the form of matrix which is represented by row * column. Definition $emp = array ( array(1,"sonoo",400000), array(2,"john",500000), array(3,"rahul",300000) ); PHP Multidimensional Array Example Let's see a simple example of PHP multidimensional array to display following tabular data. In this example, we are displaying 3 rows and 3 columns. Id Name Salary 1 sonoo 400000 2 john 500000 3 rahul 300000 File: multiarray.php Output: JTO Phase –II DNIT Version 1.0 Sep 2021 Page 124 of 167 For Restricted Circulation JTO Phase-II IT PHP 1 sonoo 400000 2 john 500000 3 rahul 300000 PHP Array Functions PHP provides various array functions to access and manipulate the elements of array. The important PHP array functions are given below. PHP array() function PHP array() function creates and returns an array. It allows you to create indexed, associative and multidimensional arrays. Syntax array array ([ mixed $... ] ) Example Output: Season are: summer, winter, spring and autumn PHP array_change_key_case() function PHP array_change_key_case() function changes the case of all key of an array. Note: It changes case of key only. Syntax array array_change_key_case ( array $array [, int $case = CASE_LOWER ] ) Example Output: Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 ) Example JTO Phase –II DNIT Version 1.0 Sep 2021 Page 125 of 167 For Restricted Circulation JTO Phase-II IT PHP Output: Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 ) PHP array_chunk() function PHP array_chunk() function splits array into chunks. By using array_chunk() method, you can divide array into many parts. Syntax array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] ) Example Output: Array ( => Array ( => 550000 => 250000 ) => Array ( => 200000 ) ) PHP count() function PHP count() function counts all elements in an array. Syntax int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] ) Example Output: 4 PHP sort() function PHP sort() function sorts all the elements in an array. Syntax bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) Example Output: autumn spring summer winter PHP array_reverse() function PHP array_reverse() function returns an array containing elements in reversed order. Syntax array array_reverse ( array $array [, bool $preserve_keys = false ] ) Example Output: autumn spring winter summer PHP array_search() function PHP array_search() function searches the specified value in an array. It returns key if search is successful. Syntax mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] ) Example Output: 2 PHP array_intersect() function PHP array_intersect() function returns the intersection of two array. In other words, it returns the matching elements of two array. Syntax array array_intersect ( array $array1 , array $array2 [, array $... ] ) Example Output: sonoo smith 9.14 PHP STRING A PHP string is a sequence of characters i.e. used to store and manipulate text. There are 4 ways to specify string in PHP. single quoted double quoted heredoc syntax newdoc syntax (since PHP 5.3) Single Quoted PHP String We can create a string in PHP by enclosing text in a single quote. It is the easiest way to specify string in PHP. Output: Hello text within single quote We can store multiple line text, special characters and escape sequences in a single quoted PHP string. Output: Hello text multiple line text within single quoted string Using double "quote" directly inside single quoted string Using escape sequences \n in single quoted string Note: In single quoted PHP strings, most escape sequences and variables will not be interpreted. But, we can use single quote through \' and backslash through \\ inside single quoted PHP strings. Output: trying variable $num1 trying backslash n and backslash t inside single quoted string \n \t Using single quote 'my quote' and \backslash Double Quoted PHP String In PHP, we can specify string through enclosing text within double quote also. But escape sequences and variables will be interpreted using double quote PHP strings. JTO Phase –II DNIT Version 1.0 Sep 2021 Page 129 of 167 For Restricted Circulation JTO Phase-II IT PHP Output: Hello text within double quote Now, you can't use double quote directly inside double quoted string. Output: Parse error: syntax error, unexpected 'quote' (T_STRING) in C:\wamp\www\string1.php on line 2 We can store multiple line text, special characters and escape sequences in a double quoted PHP string. Output: Hello text multiple line text within double quoted string Using double "quote" with backslash inside double quoted string Using escape sequences in double quoted string In double quoted strings, variable will be interpreted. Output: Number is: 10 PHP String Functions PHP provides various string functions to access and manipulate strings. A list of important PHP string functions are given below. PHP strtolower() function The strtolower() function returns string in lowercase letter. JTO Phase –II DNIT Version 1.0 Sep 2021 Page 130 of 167 For Restricted Circulation JTO Phase-II IT PHP Syntax string strtolower ( string $string ) Example Output: my name is anuj PHP strtoupper() function The strtoupper() function returns string in uppercase letter. Syntax string strtoupper ( string $string ) Example Output: MY NAME IS ANUJ PHP ucfirst() function The ucfirst() function returns string converting first character into uppercase. It doesn't change the case of other characters. Syntax string ucfirst ( string $str ) Example Output: My name is ANUJ JTO Phase –II DNIT Version 1.0 Sep 2021 Page 131 of 167 For Restricted Circulation JTO Phase-II IT PHP PHP lcfirst() function The lcfirst() function returns string converting first character into lowercase. It doesn't change the case of other characters. Syntax string lcfirst ( string $str ) Example Output: mY name IS ANUJ PHP ucwords() function The ucwords() function returns string converting first character of each word into uppercase. Syntax string ucwords ( string $str ) Example Output: My Name Is Sonoo Jaiswal PHP strrev() function The strrev() function returns reversed string. Syntax string strrev ( string $string ) Example Output: lawsiaj oonoS si eman ym PHP strlen() function The strlen() function returns length of the string. Syntax int strlen ( string $string ) Example Output: 24 9.15 PHP MATH PHP provides many predefined math constants and functions that can be used to perform mathematical operations. PHP Math: abs() function The abs() function returns absolute value of given number. It returns an integer value but if you pass floating point value, it returns a float value. Syntax number abs ( mixed $number ) Example Output: 7 7 7.2 PHP Math: ceil() function JTO Phase –II DNIT Version 1.0 Sep 2021 Page 133 of 167 For Restricted Circulation JTO Phase-II IT PHP The ceil() function rounds fractions up. Syntax float ceil ( float $value ) Example Output: 4 8 -4 PHP Math: floor() function The floor() function rounds fractions down. Syntax float floor ( float $value ) Example Output: 3 7 -5 PHP Math: sqrt() function The sqrt() function returns square root of given argument. Syntax float sqrt ( float $arg ) Example Output: 4 5 2.6457513110646 PHP Math: decbin() function The decbin() function converts decimal number into binary. It returns binary number as a string. Syntax string decbin ( int $number ) Example Output: 10 1010 10110 PHP Math: dechex() function The dechex() function converts decimal number into hexadecimal. It returns hexadecimal representation of given number as a string. Syntax string dechex ( int $number ) Example Output: 2 a 16 JTO Phase –II DNIT Version 1.0 Sep 2021 Page 135 of 167 For Restricted Circulation JTO Phase-II IT PHP PHP Math: decoct() function The decoct() function converts decimal number into octal. It returns octal representation of given number as a string. Syntax string decoct ( int $number ) Example Output: 2 12 26 PHP Math: base_convert() function The base_convert() function allows you to convert any base number to any base number. For example, you can convert hexadecimal number to binary, hexadecimal to octal, binary to octal, octal to hexadecimal, binary to decimal etc. Syntax string base_convert ( string $number , int $frombase , int $tobase ) Example Output: 1010 PHP Math: bindec() function The bindec() function converts binary number into decimal. Syntax number bindec ( string $binary_string ) Example Output: 2 10 11 PHP Math Functions Let's see the list of important PHP math functions. abs() acos() acosh() asin() asinh() atan() atan2() atanh() base_convert() bindec() ceil() cos() cosh() decbin() dechex() decoct() deg2rad() exp() expm1() floor() fmod() getrandmax() hexdec() hypot() is_finite() is_infinite() is_nan() lcg_value() log() log10() JTO Phase –II DNIT Version 1.0 Sep 2021 Page 137 of 167 For Restricted Circulation JTO Phase-II IT PHP log1p() max() min() mt_getrandmax() mt_rand() mt_srand() octdec() pi() pow() rad2deg() rand() round() sin() sinh() sqrt() srand() tan() tanh() 9.16 PHP FORM HANDLING We can create and use forms in PHP. To get form data, we need to use PHP superglobals $_GET and $_POST. The form request may be get or post. To retrieve data from get request, we need to use $_GET, for post request $_POST. PHP Get Form Get request is the default form request. The data passed through get request is visible on the URL browser so it is not secured. You can send limited amount of data through get request. Let's see a simple example to receive data from get request in PHP. File: form1.html Name: File: welcome.php PHP Post Form JTO Phase –II DNIT Version 1.0 Sep 2021 Page 138 of 167 For Restricted Circulation JTO Phase-II IT PHP Post request is widely used to submit form that have large amount of data such as file upload, image upload, login form, registration form etc. The data passed through post request is not visible on the URL browser so it is secured. You can send large amount of data through post request. Let's see a simple example to receive data from post request in PHP. File: form1.html Name: Password: File: login.php Output: 9.17 PHP INCLUDE FILE PHP allows you to include file so that a page content can be reused many times. There are two ways to include file in PHP. 1. include 2. require JTO Phase –II DNIT Version 1.0 Sep 2021 Page 139 of 167 For Restricted Circulation JTO Phase-II IT PHP 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. File: menu.html Home | PHP | Java | HTML File: include1.php This is Main Page Output: Home | PHP | Java | HTML This is Main Page PHP require example PHP require is similar to include. Let's see a simple PHP require example. File: menu.html Home | PHP | Java | HTML File: require1.php This is Main Page Output: Home | PHP | Java | HTML This is Main Page PHP include vs PHP require If file is missing or inclusion fails, include allows the script to continue but require halts the script producing a fatal E_COMPILE_ERROR level error. JTO Phase –II DNIT Version 1.0 Sep 2021 Page 140 of 167 For Restricted Circulation JTO Phase-II IT PHP 9.18 PHP SESSION PHP session is used to store and pass information from one page to another temporarily (until user close the website). PHP session technique is widely used in shopping websites where we need to store and pass cart information e.g. username, product code, product name, product price etc from one page to another. PHP session creates unique user id for each browser to recognize the user and avoid conflict between multiple browsers. PHP session_start() function PHP session_start() function is used to start the session. It starts a new or resumes existing session. It returns existing session if session is created already. If session is not available, it creates and returns new session. Syntax bool session_start ( void ) Example session_start(); JTO Phase –II DNIT Version 1.0 Sep 2021 Page 141 of 167 For Restricted Circulation JTO Phase-II IT PHP PHP $_SESSION PHP $_SESSION is an associative array that contains all session variables. It is used to set and get session variable values. Example: Store information $_SESSION["user"] = "Sachin"; Example: Get information echo $_SESSION["user"]; PHP Session Example File: session1.php Visit next page File: session2.php PHP Session Counter Example File: sessioncounter.php PHP Destroying Session PHP session_destroy() function is used to destroy all session variables completely. File: session3.php 9.19 SUMMARY This tutorial has taught you how to use PHP to create your own web site. PHP is the universal language for the Web. PHP lets you make the complete dynamic website using server side script and database connectivity. The key to HTML is the tags, which indicates what content is coming up. JTO Phase –II DNIT Version 1.0 Sep 2021 Page 143 of 167 For Restricted Circulation