OpenGurukul : Language : PHP


Published on

PHP Language Tutorial by OpenGurukul

Published in: Technology
1 Comment
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

OpenGurukul : Language : PHP

  1. 1. PHP By OpenGurukul
  2. 2. Chapter 1Introduction to php 2
  3. 3. Introduction to web applicationWhat is Web Application?Components of Web Application-Presentation-ProcessingUses of PhP- Server Side Scripting- Command Line Scripting 3- Writing Desktop Applications
  4. 4. Introduction to PHPBasic PHP Syntax<?php ?>Example of php program<html><body><?php echo “Hello world”; ?></body></html>Comments in php<html><body><?php //This is a comment/*This is a comment block */?> 4</body></html>
  5. 5. Chapter 2Php data types 5
  6. 6. Php data TypesA data type refers to the type of data a variable can store.8 different type of data types are:integer numbersfloating point numbersstringsbooleansarraysobjectsresouces 6null
  7. 7. IntegersAn integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.Example<?php$a = 1234; // decimal number$a = -123; // a negative number$a = 0123; // octal number (equivalent to 83 decimal)$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)?>Integer Data type can be divided into two types – Octal, Hexadecimal, Decimal 7
  8. 8. Floating point numbersFloating point numbers are those data types which can store decimal valuesExample<?php$a = 1.234;$b = 1.2e3;$c = 7E-10;?> 8
  9. 9. StringsA string is series of characters.Example<?php$str=”Hello world”;echo $str;?>Output: Hello World 9
  10. 10. BooleansThis variable must be true or falseExample<? php$foo = True;// assign the value TRUE to $foo?> 10
  11. 11. ArraysAn array is a variable that holds a group of values.Referencing array elements is done like this:Example$arrayName[index];assign a value to an array position:$listing[0] = "first item";$listing[1] = "second item";$listing[2] = "third item"; 11
  12. 12. ObjectAn object is a data type that allows echo "This is example of object data for the storage of not only data type."; but also information on how to process that data. }Example: }<?php $bar = new foo;class foo $bar->do_foo();{ ?>function do_foo() Output :This is example of object data type.{ 12
  13. 13. Resources and NullResourcesResources are really integers under the surface. Their main benefit is that theyre garbage collected when no longer in use. When the last reference to a resource value goes away, the extension that created the resource is called to free any memory, close any connection, etc. for that resource:NullThe NULL value represents a variable that has no value<?php$var = NULL;?> 13
  14. 14. Type CastingPHP will automatically convert data types as necessary across the boardExample<?php $mystring = "wombat"; $myinteger = (integer)$mystring?>At first, $mystring contains a string.However, we type cast it to be an integer, so PHP will convert it to an integer, and place the result into $myinteger 14
  15. 15. Type jugglingif we add two integer variables then the result is integer typebut if we add one integer and one float type variable then the result is float type because float type has a higher precedence than integer.Example<?php$foo = "0"; // $foo is string (ASCII 48)$foo += 2; // $foo is now an integer (2)$foo = $foo + 1.3; // $foo is now a float (3.3)$foo = 5 + "10 Little Piggies"; // $foo is integer (15)$foo = 5 + "10 Small Pigs"; // $foo is integer (15) 15?>
  16. 16. Chapter 3Variables 16
  17. 17. variablesVariables are used for storing valuesWhen a variable is declared, it can be used over and over again in your script.All variables in PHP start with a $ sign symbol.The variable name is case-sensitive.Ex-$var_name = value; 17
  18. 18. PHP-loosely typed languageExample<?php$txt="Hello World!";$x=16;?>a variable does not need to be declared before adding a value to it.It automatically converts the variable to the correct data type, depending on its value. 18
  19. 19. Variable scopeExample<?php$a=1; /* global scope*/function test(){echo $a;} /* reference to local scope variable*/}test();?>output:It will not produce any output 19
  20. 20. Global keywordExample<?php $a=1; $b=2; function sum() { global $a, $b; $b = $a + $b; } Sum(); echo $b; 20 ?> output: 3
  21. 21. Variables variablesExample<?php$a=”hello”;$$a=”world”;echo "$a ${$a}";?>Here $a is hello then $hello is world so final out put is hello world 21
  22. 22. Chapter 4Constants And Expressions 22
  23. 23. ConstantsConstants just as variables are used to store information.difference between constants and variables is that constant value can not be changed in the process of running program.A constant is case-sensitive by defaultdefine a constant by using the define()-function or the const keyword outside a class definition. 23
  24. 24. Define functionExample<?phpdefine("PASSWORD","admin"); // first we define a constant PASSWORDecho (PASSWORD); // will display value of PASSWORD constant, i.e. adminecho constant("PASSWORD"); // will also display adminecho "PASSWORD"; // will display PASSWORD?> 24
  25. 25. Const keywordExample<?phpconst CONSTANT = Hello World; // Works as of PHP 5.3.0echo CONSTANT;?> 25
  26. 26. Magic ConstantsPHP provides a large number of predefined constants to any script which it runs.__LINE__:The current line number of the file__FILE__:The full path and filename of the file__DIR__:The directory of the file__FUNCTION__:The function name(case-sensitive)__CLASS__:The class name(case-sensitive)__METHOD__:The class method name(case-sensitive)__NAMESPACE__:The name of the current namespace (case-sensitive) 26
  27. 27. ExpressionsExample$a = “5"youre assigning 5 into $a. 5, obviously, has the value 5, or in other words 5 is an expression with the value of 5 (in this case, 5 is an integer constant).After this assignment, youd expect $as value to be 5 as well.So if you wrote $b = $a, youd expect it to behave just as if you wrote $b = 5. In other words.$a is an expression with the value of 5 as well. 27
  28. 28. Chapter 5Operators 28
  29. 29. OperatorsOperators are used to operate on values.Different types of operators we are using in php.i.Arithmetic Operatorsii.Assignment Operatorsiii.Comparison Operatorsiv.Logical Operators 29
  30. 30. Arithmetic OperatorsOperator Description Example Result+ Addition x=2,x+2 4- Subtraction x=2,5-x 3* Multiplication x=4 20 x*5/ Division 15/5 3 5/2 2.5% Modulus (division 5%2 1 remainder) 10%8 2 10%2 0++ Increment x=5 x=6 x++-- Decrement x=5 x=4 x-- 30
  31. 31. Assignment OperatorsOperator Example Is The Same As= x=y x=y+= x+=y x=x+y-= x-=y x=x-y*= x*=y x=x*y/= x/=y x=x/y.= x.=y x=x.y%= x%=y x=x%y 31
  32. 32. Comparision OperatorsOperator Description Example== is equal to 5==8 returns false!= is not equal 5!=8 returns true<> is not equal 5<>8 returns true> is greater than 5>8 returns false< is less than 5<8 returns true>= is greater than or 5>=8 returns equal to false<= is less than or 5<=8 returns true equal to 32
  33. 33. Logical OperatorsOperator Description Example&& and x=6 y=3 (x < 10 && y > 1) returns true|| or x=6 y=3 (x==5 || y==5) returns false! not x=6 y=3 !(x==y) returns true 33
  34. 34. Operator precedenceExample1 + 5 * 3=16 and not 18because ("*") operator has a higher precedence than the ("+") operatorParentheses may be used to force precedence, if necessary.(1 + 5) * 3=18If operator precedence is equal, left to right associativity is used. 34
  35. 35. Chapter 6Control Structure 35
  36. 36. Conditional StatementsConditional statements are used to perform different actions based on different conditions.PhP have the following conditional statementsif statementif else statementif elseif else statementswitch statement 36
  37. 37. If statementSyntax Exampleif (condition) <?phpcode to be executed if condition is true; $a=2; if($a==2)else echo “It is two”;code to be executed if condition is false; ?> output::It is two 37
  38. 38. If else StatementSyntax Example <?phpif (condition) $a=2;code to be executed if condition is true; $b=3; if($b>$a)else {code to be executed if condition is echo “b is greater”; false; } else { echo “a is greater”; } 38 ?> output::b is greater
  39. 39. The if...else if....else StatementUse the if....elseif...else statement to select one of several blocks of code to be executed.Syntaxif (condition) code to be executed if condition is true;elseif (condition) code to be executed if condition is true;else code to be executed if condition is false; 39
  40. 40. if..else if..else statementExample elseif ($a == $b)<?php {$a=3; echo "a is equal to b";$b=4; }if ($a > $b) else{ {echo "a is bigger than b"; echo "a is smaller than b";} } ?> output: a is smaller than b 40
  41. 41. Switch statementUse the switch statement to select one of many blocks of code to be executed.Syntaxswitch (n){case label1:code to be executed if n=label1;break;case label2:code to be executed if n=label2;break;default: 41code to be executed if n is different from both label1 and label2;}
  42. 42. Switch statementExample case 3:<?php echo "Number 3";$x=1; break;switch ($x) default:{ echo "No number between 1 and 3";case 1: }echo "Number 1"; ?>break; output:Number 1case 2:echo "Number 2";break; 42
  43. 43. loopingA loop is simply a block of code that executes multiple times.The following loops are available in php- while statement- do while statement- for statement- foreach statement 43
  44. 44. The while loopThis loop executes a block of code Example while a condition is true. <?phpSyntax $i=1;while (condition) while($i<=5){ {code to be executed; echo $i;} $i++; } ?> output:12345 44
  45. 45. The do...while StatementThe loop will always execute the block of Example code once,then check the condition, and repeat the loop while the <?php condition is true. $i=1;Syntax dodo {{code to be executed; $i++;} echo $i;while (condition); } while ($i<=5); ?> 45 output:123456
  46. 46. The for statementThe loop is used when you know in Example advance how many times the <?php script should run. for ($i=1; $i<=5; $i++)Syntax {for (init; condition; increment) echo $i ;{code to be executed; }} ?> output:12345 46
  47. 47. The foreach LoopThe foreach loop is used to loop through arrays.Syntaxforeach ($array as $value){code to be executed;}For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop iteration, youll be looking at the next array value. 47
  48. 48. Chapter 7 Array 48
  49. 49. ArrayArray is a special type of variable which stores similar types of data.There are 3 types of arrayNumeric array:An array with a numeric indexAssociative array:An array where each ID key is associated with a valueMultidimensional array:An array containing one or more arrays 49
  50. 50. Numeric ArraysThere are two methods to create a numeric array.i.In the following example the index are automatically assigned (the index starts at 0):Ex-$cars=array("Saab","Volvo","BMW","Toyota");ii.In the following example we assign the index manually:$cars[0]="Saab";$cars[1]="Volvo";$cars[2]="BMW";$cars[3]="Toyota"; 50
  51. 51. Associative ArraysExample1In this example we use an array to assign ages to the different persons$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);Example2$ages[Peter] = "32";$ages[Quagmire] = "30";$ages[Joe] = "34"; 51
  52. 52. Multidimensional ArraysExample<?php$families = array("Griffin"=>array ("Peter","Lois","Megan" ),"Quagmire"=>array("Glenn" ),"Brown"=>array ("Cleveland", "Loretta", "Junior" ));?>OutputArray([Griffin] => Array([0] => Peter [1] => Lois [2] => Megan)[Quagmire] => Array([0] => Glenn )[Brown] => Array([0] => Cleveland [1] => Loretta [2] => Junior )) 52
  53. 53. Array FunctionsList()The list() function is used to assign values to a list of variables in one operation.Syntaxlist(var1,var2...)Example<?php $my_array = array("Dog","Cat","Horse");list($a, $b, $c) = $my_array;echo "I have several animals, a $a, a $b and a $c.";?>output:I have several animals, a Dog, a Cat and a Horse. 53
  54. 54. count()The count() function counts the elements of an array, or the properties of an object.Syntaxcount(array,mode)Example<?php $people = array("Peter", "Joe", "Glenn", "Cleveland");$result = count($people);echo $result;?>output: 4 54
  55. 55. array_sum()The array_sum() function returns the sum of all the values in the array.Syntaxarray_sum(array)Example<?php$a=array(0=>"5",1=>"15",2=>"25");echo array_sum($a);?>output: 45 55
  56. 56. Many other functions are therearray_pop() - Pop the element off the end of arrayarray_push - Push one or more elements onto the end of arraysort - Sort an arrayasort - Sort an array and maintain index associationarsort - Sort an array in reverse order and maintain index associationksort - Sort an array by keykrsort - Sort an array by key in reverse orderprint_r - Display all the readable information about the array 56
  57. 57. Chapter 8PHP Forms and User Inputs 57
  58. 58. Html form exampleExampleThe example below contains an HTML form with two input fields and a submit button: html_form.php<html><body><form action="welcome.php" method="post">Name: <input type="text" name="fname" />Age: <input type="text" name="age" /><input type="submit" /></form></body> 58</html>
  59. 59. Collecting data from a formWhen a user fills out the form above and click on the submit button, the form data is sent to a PHP file, called "welcome.php":"welcome.php" looks like this:File: welcome.php<html><body>Welcome <?php echo $_POST["fname"]; ?>!<br />You are <?php echo $_POST["age"]; ?> years old.</body></html>ouput: Welcome John! You are 28 years old. 59
  60. 60. Php $_GET functionIt is used to collect values from a form.Information sent from a form is visible to everyone (it will be displayed in the browsers address bar)Not fit for sending passwords or other sensitive information!Not suitable for very large variable values.(not exceeding 2000 characters) 60
  61. 61. $_GET functionExample<form action="welcome.php" method="get">Name: <input type="text" name="fname" />Age: <input type="text" name="age" /><input type="submit" /></form>URL looks like this: welcome.phpWelcome <?php echo $_GET["fname"]; ?>.<br />You are <?php echo $_GET["age"]; ?> years old! 61
  62. 62. Php $_POST functionIt is also used to collect values from a form.Information sent from a form is invisible to others and has no limits on the amount of information to is an 8 Mb max size for the POST method, by default .Size can be changed by setting the post_max_size in the php.ini file.It is fit for the password or any other sensitive information 62
  63. 63. $_POST functionExample<form action="welcome.php" method="post">Name: <input type="text" name="fname" />Age: <input type="text" name="age" /><input type="submit" /></form>The URL will look like this: welcome.phpWelcome <?php echo $_POST["fname"]; ?>!<br /> www.opengurukul.comYou are <?php echo $_POST["age"]; ?> years old. 63
  64. 64. Php $_REQUEST functionThis function contains the contents of both $_GET, $_POST, and $_COOKIE.It can be used to collect form data sent with both the GET and POST methods.ExampleWelcome <?php echo $_REQUEST["fname"]; ?>!<br />You are <?php echo $_REQUEST["age"]; ?> years old. 64
  65. 65. Chapter 9String Handling 65
  66. 66. String VariablesA string variable is used to store and manipulate text.Example<?php$txt="Hello World";echo $txt;?>output: Hello World 66
  67. 67. String Literal SyntaxA string literal can be specified in four different ways:single quoteddouble quotedheredoc syntaxExample of single quoted: <?php $str=Hello World; ?> 67
  68. 68. Example of double quote<?php $str=”hello world”; ?>Example of heredocHeredoc is a robust way to create string in PHP with more lines but without using quotations.<?php$str = <<<DEMOThis is a demo message with heredoc.DEMO;echo $str; ?>output: This is a demo message with heredoc. 68
  69. 69. The concatenation operatorThe concatenation operator (.) is used to put two string values together.Example<?php$txt1="Hello World!";$txt2="What a nice day!";echo $txt1 . " " . $txt2;?>output: Hello World! What a nice day! 69
  70. 70. String FunctionStrlen()The strlen() function is used to return the length of a string.Syntaxint strlen ( string $string )Example<?php$str = abcdef;echo strlen($str); // 6$str = ab cd ;echo strlen($str); // 7 70?>
  71. 71. str_replace()It replaces some characters with some other characters in a string.Syntaxstr_replace(find,replace,string,count)Example<?php$arr = array("blue","red","green","yellow");print_r(str_replace("red","pink",$arr,$i));echo "Replacements: $i";?>output:Array([0] => blue [1] => pink [2] => green [3] => yellow) Replacements: 1 71
  72. 72. strrev()The strrev() function reverses a string.Syntaxstrrev(string)Example<?phpecho strrev("Hello World!");?>output : !dlroW olleH 72
  73. 73. Strrpos()The strrpos() function finds the position of the last occurrence of a string inside another string.Syntaxstrrpos(string,find,start)Example<?phpecho strrpos("Hello world!","wo");?>output: 6 73
  74. 74. Explode()The explode() function breaks a string into an array.Syntaxexplode(separator,string,limit)Example<?php$str = "Hello world. Its a beautiful day.";print_r (explode(" ",$str));?>output:Array([0] => Hello [1] => world. [2] => Its [3] => a [4] => beautiful [5] => day.) 74
  75. 75. Chapter 10Function 75
  76. 76. FunctionA function is a block of code that performs a specific task. It has a name and it is reusable.There are two types of functions-Built-in functions-User defined functions 76
  77. 77. User defined functionFunctions those are defined by user Example according to user requirements. <?phpSyntax function writeName()function functionName() {{ echo "Kai Jim Refsnes";code to be executed; }} echo "My name is "; writeName(); ?> output: My name is Kai Jim Refsnes 77
  78. 78. Function ArgumentsInformation may be passed to echo "My sisters name is "; functions via the argument list, writeName("Hege"); which is a comma-delimited list of expressions. ?> output:My name is Kai Jim Refsnes.Example My sisters name is Hege Refsnes.<?phpfunction writeName($fname){echo $fname . " Refsnes.<br />";}echo "My name is ";writeName("Kai Jim"); 78
  79. 79. Pass by value vs. Pass by referenceEx-pass by value Ex-pass by reference<?php <?phpfunction pass_by_value($param) function_by_reference(&$param){ {push_array($param, 4, 5); push_array($param, 4, 5);} }$ar = array(1,2,3); $ar = array(1,2,3);pass_by_value($ar); pass_by_reference($ar);foreach ($ar as $elem) foreach ($ar as $elem){ {print "<br>$elem"; print "<br>$elem";} } 79?> output:1, 2, 3 ?> output: 1, 2, 3, 4, 5.
  80. 80. Return valuesTo let a function return a value, use the return statement .Example<?phpfunction add($x,$y){$total=$x+$y;return $total;}echo "1 + 16 = " . add(1,16);?>ouput:1 + 16 = 17 80
  81. 81. Built-in functionDate()The PHP date() function is used to format a time and/or date.Syntaxdate(format,timestamp)Example<?php echo date("Y/m/d") . "<br />";echo date("Y.m.d") . "<br />";echo date("Y-m-d"); ?>output:2009/05/11 2009.05.11 2009-05-11 81
  82. 82. mktime()The mktime() function returns the Unix timestamp for a date.Syntaxmktime(hour,minute,second,month,day,year,is_dst)Example<?php$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));echo "Tomorrow is ".date("Y/m/d", $tomorrow);?>output:Tomorrow is 2009/05/12 82
  83. 83. include()You can insert the content of one PHP file into another PHP file before the server executes itExample<html><body><?php include("header.php"); ?><h1>Welcome to my home page!</h1><p>Some text.</p></body></html> 83
  84. 84. Require()It is identical as the include functionExample()<?phprequire("wrongFile.php");echo "Hello World!";?> 84
  85. 85. Include vs RequireInclude RequireGenerates warning if file not found Gives fatal error if file not foundScript will continue execution Script will stop 85
  86. 86. require_once() & include_once()include_once() and require_once() function is used to include a file only once in a page.Example<?phprequire_once(“header.php");include_once(“header.php");?> 86
  87. 87. Chapter 11cookies 87
  88. 88. cookieA cookie is often used to identify a user.A cookie is a small file that the server embeds on the users computer.It is used for an origin website to send state information to a users browser and for the browser to return the state information to the origin site 88
  89. 89. Creating CookieThe setcookie() function is used to set a cookie.Syntaxsetcookie(name, value, expire, path, domain);Example<?phpsetcookie("user", "Alex Porter", time()+3600);?> 89
  90. 90. Retrieving Cookie ValueThe PHP $_COOKIE variable is used to retrieve a cookie value.Example<?phpecho $_COOKIE["user"]; // Print a cookieprint_r($_COOKIE); // A way to view all cookies?> 90
  91. 91. Deliting cookieWhen deleting a cookie you should assure that the expiration date is in the past.Example<?php// set the expiration date to one hour agosetcookie("user", "", time()-3600);?> 91
  92. 92. Chapter 12Sessions 92
  93. 93. SessionsA PHP session variable is used to store information about, or change settings for a user session.Session variables hold information about one single user, and are available to all pages in one application. 93
  94. 94. Starting a PHP SessionBefore you can store user information in your PHP session, you must first start up the session.Session_start() is used to start a sessionExample<?php session_start(); ?><html><body></body></html> 94
  95. 95. Storing a Session VariableExample<?phpsession_start();$_SESSION[user]=”Ram”;echo $_SESSION[user];?>output:Ram 95
  96. 96. Destroying a SessionUnset() and session_destroy() are used to delete the sessionunset():It is used to free the specified session variable:Example of unset()<?phpunset($_SESSION[views]);?>session_destroy():is used to compltetly destroy the sessionExample of session_destroy()<?phpsession_destroy(); 96?>
  97. 97. Chapter 13File Handling 97
  98. 98. File open Fopen() is used to open a filefirst parameter shows file name and the second parameter shows mode of the fileExample<?php$file=fopen("welcome.txt","r");?> 98
  99. 99. Closing a FileThe fclose() function is used to close an open file:Example<?php$file = fopen("test.txt","r");//some code to be executedfclose($file);?> 99
  100. 100. Check End-of-fileThe feof() function checks if the "end-of-file" (EOF) has been reached.Example<?phpif (feof($file))echo "End of file";?> 100
  101. 101. File Reading - Line by LineThe fgets() function is used to read a single line from a file.Example<?php$file = fopen("welcome.txt", "r") or exit("Unable to open file!");//Output a line of the file until the end is reachedwhile(!feof($file)){echo fgets($file). "<br />";}fclose($file);?> 101
  102. 102. File Reading - Character by CharacterThe fgetc() function is used to read a single character from a file.Example<?php$file=fopen("welcome.txt","r") or exit("Unable to open file!");while (!feof($file)){echo fgetc($file);}fclose($file);?> 102
  103. 103. File uploadCreate an Upload-File Form<html><body><form action="upload_file.php" method="post" enctype="multipart/form-data"><label for="file">Filename:</label><input type="file" name="file" id="file" /><input type="submit" name="submit" value="Submit" /></form></body></html> 103
  104. 104. Create The Upload ScriptExample else<?php {if ($_FILES["file"]["error"] > 0) echo "Upload: " . $_FILES["file"]["name"] . "<br />";{ echo "Type: " . $_FILES["file"]["type"] .echo "Error: " . $_FILES["file"]["error"] . "<br />"; "<br />"; echo "Size: " . ($_FILES["file"]["size"] /} 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["file"] ["tmp_name"]; } ?> 104
  105. 105. Restrictions on UploadExample echo "Upload: " . $_FILES["file"]["name"] . "<br />";<?php echo "Type: " . $_FILES["file"]["type"] . "<brif ((($_FILES["file"]["type"] == "image/gif") || />"; ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) echo "Size: " . ($_FILES["file"]["size"] / && ($_FILES["file"]["size"] < 20000)) 1024) . " Kb<br />";{ echo "Stored in: " . $_FILES["file"] ["tmp_name"];if ($_FILES["file"]["error"] > 0) }{ }elseecho "Error: " . $_FILES["file"]["error"] . "<br />"; {}else echo "Invalid file";{ } 105 ?>
  106. 106. Chapter 14Sending Email 106
  107. 107. Sending Email using mail()The PHP mail() function is used to Example send emails from inside a script. <?phpSyntax $to = "";mail(to,subject,message,headers,pa $subject = "Test mail"; rameters) $message = "Hello! This is a simple email message."; $from = ""; $headers = "From: $from"; mail($to,$subject,$message,$headers); echo "Mail Sent."; ?> 107
  108. 108. Chapter 15Error Handling 108
  109. 109. Default & Other MethodsThe default error handling in PHP is very simple. An error message with filename, line number and a message describing the error is sent to the browser.different error handling methods:-Simple "die()" statements-Custom errors and error triggers-reporting 109
  110. 110. Basic Error Handling: Using the die() functionExample<?php if(!file_exists("welcome.txt")){die("File not found");}Else{$file=fopen("welcome.txt","r");}?>Now if the file does not exist you get an error like this: File not found 110
  111. 111. Creating a Custom Error HandlerThis function must be able to handle a minimum of two parametersi.e (error level and error message) but can accept up to five parameters(optionally: file, line-number, and the error context):Syntaxerror_function(error_level,error_message,error_file,error_line,error_context) 111
  112. 112. Error Report levelsE_WARNING: Non-fatal run-time errorsE_NOTICE: Run-time noticesE_USER_ERROR: Fatal user-generated errorE_USER_WARNING: Non-fatal user-generated warningE_USER_NOTICE: User-generated noticeE_RECOVERABLE_ERROR: Catchable fatal errorE_ALL: All errors and warnings, except level E_STRICT 112
  113. 113. Set Error HandlerSyntaxset_error_handler("customError");Example<?php function customError($errno, $errstr) //error handler function{echo "<b>Error:</b> [$errno] $errstr";}set_error_handler("customError"); //set error handlerecho($test); //trigger error?>output: [8] Undefined variable: test 113
  114. 114. Trigger an ErrorIn a script where users can input data it is useful to trigger errors when an illegal input occurs.trigger_error() function is used for this.Example<?php$test=2;if ($test>1){trigger_error("Value must be 1 or below");}?>output: Notice: Value must be 1 or below 114 in C:webfoldertest.php on line 6
  115. 115. Chapter 16Exception Handling 115
  116. 116. Exception HandlingExceptions are used to change the normal flow of a script if a specified error occursWe will show different error handling methods:-Basic use of Exceptions-Creating a custom exception handler-Multiple exceptions-Re-throwing an exception-Setting a top level exception handler 116
  117. 117. Basic Use of ExceptionsWhen an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block.If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message. 117
  118. 118. Basic use of exception output:Fatal error: Uncaught exceptionExample Exception<?php with message Value must be 1 or below in C:webfoldertest.php:6function checkNum($number) Stack trace: #0{ C:webfoldertest.php(12):if($number>1) checkNum(28) #1 {main} thrown in C: webfoldertest.php on line 6{throw new Exception("Value must be 1 or below");}return true;} 118checkNum(2); ?>
  119. 119. Try, throw and catchTry - A function using an exception should be in a "try" block.If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown"Throw - This is how you trigger an exception. Each "throw" must have at least one "catch"Catch - This block retrieves an exception and creates an object containing the exception information 119
  120. 120. Try throw catchExample Try<?php {function checkNum($number) checkNum(2);{ echo If you see this, the number is 1 or below;if($number>1) }{ catch(Exception $e)throw new Exception("Value must be 1 or below"); {} echo Message: .$e->getMessage();return true; }} ?> Message: Value must be 1 or below output: 120
  121. 121. Chapter 17 Filter 121
  122. 122. FiltersPHP filters are used to validate and filter data coming from insecure sources, like user input.To test, validate and filter user input or custom data is an important part of any web application. 122
  123. 123. Use of filterWe should always filter all external data!What is external data?-Input data from a form-Cookies-Web services data-Server variables-Database query results 123
  124. 124. Functions and FiltersTo filter a variable, use one of the following filter functions:filter_var() - Filters a single variable with a specified filterfilter_var_array() - Filter several variables with the same or different filtersfilter_input - Get one input variable and filter itfilter_input_array - Get several input variables and filter them with the same or different filters 124
  125. 125. filter_var()Example of filters:we validate an integer using the filter_var() function:$int = 123;if(!filter_var($int, FILTER_VALIDATE_INT)){echo("Integer is not valid");}else{echo("Integer is valid");}?> 125
  126. 126. Validating and SanitizingAre used to validate user input Are used to allow or disallow specified characters in a stringStrict format rules (like URL or E- Mail validating) No data format rulesReturns the expected type on success or FALSE on failure Always return the string 126
  127. 127. Validate inputExample else<?php {if(!filter_has_var(INPUT_GET, "email")) echo "E-Mail is valid";{ }echo("Input type does not exist"); }} ?>else The example tells{ 1. Check if an "email" input variable of the "GET" type existif (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL)) 2. If the input variable exists, check if it is a valid e-mail address{echo "E-Mail is not valid"; 127}
  128. 128. Sanitize InputExample The example tells<?php 1. Check if the "url" input of the "POST" type existsif(!filter_has_var(INPUT_POST, "url")) 2. If the input variable exists, sanitize (take{ away invalid characters) and store it in the $url variableecho("Input type does not exist");}else{$url = filter_input(INPUT_POST, "url", FILTER_SANITIZE_URL);}?> 128
  129. 129. Chapter 18PHP & MySQL 129
  130. 130. Connecting to a DatabaseIn PHP,mysql_connect() function is used to connect the databaseSyntaxmysql_connect( servername, username ,password);Example<?php$con = mysql_connect("localhost","root","root”);if (!$con){die(Could not connect: . mysql_error());} 130?>
  131. 131. Closing a ConnectionThe connection will be closed automatically when the script ends.To close the connection before, use the mysql_close() function:Example<?php$con = mysql_connect("localhost","root","root”);if (!$con){die(Could not connect: . mysql_error());}mysql_close($con); 131?>
  132. 132. Creating DatabaseThe CREATE DATABASE statement is used to create a database in MySQL.SyntaxCREATE DATABASE database_nameTo execute the statement query we must use the mysql_query() function 132
  133. 133. Creating databaseExample if (mysql_query("CREATE DATABASE my_db",$con))<?php {$con = mysql_connect("localhost","root","root echo "Database created"; ”); }if (!$con) else{ {die(Could not connect: . mysql_error()); echo "Error creating database: " .} mysql_error(); } mysql_close($con); 133 ?>
  134. 134. Creating TableThe CREATE TABLE statement is used to create a table in MySQL.SyntaxCREATE TABLE table_name(column_name1 data_type,column_name2 data_type,column_name3 data_type,) 134
  135. 135. Creating tableExample else<?php {$con = echo "Error creating database: " . mysql_connect("localhost","root","root”); mysql_error();if (!$con) }{ mysql_select_db("my_db", $con);die(Could not connect: . mysql_error()); $sql = "CREATE TABLE Persons} (if (mysql_query("CREATE DATABASE FirstName varchar(15), my_db",$con)) LastName varchar(15),{ )";echo "Database created"; mysql_query($sql,$con); 135} mysql_close($con); ?>
  136. 136. Inserting data to DBThe INSERT INTO statement is used to add new records to a database table.SyntaxINSERT INTO table_nameVALUES (value1, value2, value3,...)INSERT INTO table_name (column1, column2, column3,...)VALUES (value1, value2, value3,...) 136
  137. 137. Insert Data From a Form Into a DatabaseHere is the HTML form:form.php<html><body><form action="insert.php" method="post">Firstname: <input type="text" name="firstname" />Lastname: <input type="text" name="lastname" /><input type="submit" /></form></body></html> 137
  138. 138. continueIn insert.php $sql="INSERT INTO Persons (FirstName, LastName, Age)<?php VALUES$con = mysql_connect("localhost","root","root”); ($_POST[firstname],$_POST[lastname],$_ POST[age])";if (!$con) if (!mysql_query($sql,$con)){ {die(Could not connect: . mysql_error()); die(Error: . mysql_error());} }mysql_select_db("my_db", $con); echo "1 record added"; mysql_close($con) ?> 138
  139. 139. Select statementIt is used to select data from a mysql_select_db("my_db", $con); database. $result = mysql_query("SELECT * FROM Persons");Syntax while($row = mysql_fetch_array($result))SELECT column_name(s) FROM table_name { echo $row[FirstName] . " " .Example $row[LastName];<?php echo "<br />";$con = } mysql_connect("localhost","root","root”); mysql_close($con);if (!$con) ?>{die(Could not connect: . mysql_error()); 139}
  140. 140. Update statementIt is used to update existing records if (!$con) in a table. {Syntax die(Could not connect: . mysql_error());UPDATE table_name SET } column1=value, mysql_select_db("my_db", $con); column2=value2,... mysql_query("UPDATE Persons SET Age =WHERE some_column=some_value 36 WHERE FirstName = Peter AND LastNameExample = Griffin");<?php mysql_close($con);$con = ?> mysql_connect("localhost","root","root”); 140
  141. 141. Delete statementThe DELETE FROM statement is if (!$con) used to delete records from a { database table. die(Could not connect: . mysql_error());Syntax }DELETE FROM table_name mysql_select_db("my_db", $con); WHERE some_column = some_value mysql_query("DELETE FROM Persons WHERE LastName=Griffin");Example mysql_close($con);<?php ?>$con = mysql_connect("localhost","root","root”); 141
  142. 142. Important functionsmysql_num_rows:Get number of rows in resultmysql_affected_rows:Get number of affected rows in previous MySQL operationmysql_select_db:Select a MySQL database 142
  143. 143. mysql_num_rowsExample<?php$link = mysql_connect("localhost", "mysql_user", "mysql_password");mysql_select_db("database", $link);$result = mysql_query("SELECT * FROM table1", $link);$num_rows = mysql_num_rows($result);echo "$num_rows Rowsn";?> 143
  144. 144. mysql_affected_rowsExample<?php$link = mysql_connect(localhost, mysql_user, mysql_password);if (!$link) {die(Could not connect: . mysql_error());}mysql_select_db(mydb);mysql_query(DELETE FROM mytable WHERE id < 10);printf("Records deleted: %dn", mysql_affected_rows());mysql_query(DELETE FROM mytable WHERE 0);printf("Records deleted: %dn", mysql_affected_rows()); 144?>
  145. 145. mysql_select_dbExample<?php$link = mysql_connect(localhost, mysql_user, mysql_password);if (!$link) {die(Not connected : . mysql_error());}$db_selected = mysql_select_db(foo, $link);if (!$db_selected) {die (Cant use foo : . mysql_error());}?> 145
  146. 146. Chapter 19PHP & ODBC 146
  147. 147. Create an ODBC ConnectionHere is how to create an ODBC connection to a MS Access Database:1.Open the Administrative Tools icon in your Control Panel.2.Double-click on the Data Sources (ODBC) icon inside.3. Choose the System DSN tab.4.Click on Add in the System DSN tab.5. Select the Microsoft Access Driver. Click Finish.6. In the next screen, click Select to locate the database.7.Give the database a Data Source Name (DSN).8. Click OK. 147
  148. 148. DSN On Linux:To use MySQL via ODBC:<?php$db_host = "server.mynetwork";$db_user = "dbuser";$db_pass = "dbpass";$dsn = "DRIVER={MySQL ODBC 3.51 Driver};" ."CommLinks=tcpip(Host=$db_host);" ."DatabaseName=$db_name;" ."uid=$db_user; pwd=$db_pass";odbc_connect($dsn, $db_user, $db_pass); 148?>
  149. 149. Connecting to an ODBCThe odbc_connect() is used to connect to an ODBC data source.It takes four parameters:-data source name-username-password-optional cursor type.ExampleThe following example creates a connection to a DSN called northwind, with no username and no password.$conn=odbc_connect(northwind,,); 149
  150. 150. Executing SQL Statement: odbc_exec()The odbc_exec() function is used to execute an SQL statement.Exampleexample with no username and no password.It then creates an SQL and executes it:$conn=odbc_connect(northwind,,);$sql="SELECT * FROM customers";$rs=odbc_exec($conn,$sql); 150
  151. 151. Retrieving Records odbc_fetch_row()This function is used to return records from the result-set.The function takes two parameters:- ODBC result identifier- an optional row numberExampleodbc_fetch_row($rs) 151
  152. 152. Retrieving Fields from a Record: odbc_result()This function is used to read fields from a record.It takes two parameters:-The ODBC result identifier- a field number or name.Example1$compname=odbc_result($rs,1);returns the value of the first field from the record:Example2$compname=odbc_result($rs,"CompanyName");returns the value of a field called "CompanyName": 152
  153. 153. Closing an ODBC Connection: odbc_close()The odbc_close() function is used to close an ODBC connection.Exampleodbc_close($conn); 153
  154. 154. Chapter 20Object Oriented Programming 154
  155. 155. classesA class is user defined data type that contains attributes or data members; and methods which work on the data members.Class structureclass <class-name>{<class body :- Data Members &amp; Methods>;} 155
  156. 156. Class exampleclass Customer //customer is the class name{private $first_name, $last_name; //$first_name/$last_name are attributes or data members.public function setData($first_name, $last_name) //setData is the method{$this->first_name = $first_name;$this->last_name = $last_name;}public function printData() //printData is also the method{echo $this->first_name . " : " . $this->last_name;} 156}
  157. 157. The new instanceTo create an instance of a class, the new keyword must be used.An object will always be created when unless the object has a constructor defined that throws an exception on error.Classes should be defined before instantiationIf a string containing the name of a class is used with new, a new instance of that class will be created.Syntax$instance = new Class();Or we can write $className = Foo; $instance = new $className(); 157
  158. 158. Object assignmentExample$instance = new SimpleClass();$assigned = $instance;$reference =& $instance;$instance->var = $assigned will have this value;$instance = null; // $instance and $reference become nullvar_dump($instance);var_dump($reference);var_dump($assigned); 158
  159. 159. Extends keywordA class can inherit the methods and } properties of another class by $extended = new ExtendClass(); using the keyword extends in the class declaration. $extended->displayVar(); ?>Example output:Extending class<?php a default valueclass ExtendClass extends SimpleClass{function displayVar(){ echo "Extending classn"; parent::displayVar(); 159}
  160. 160. PropertiesClass member variables are called "properties"They are defined public, protected, or private, followed by a normal variable declaration.This declaration may include an initialization, but this initialization must be a constant value 160
  161. 161. PropertiesExample // valid property declarations:<?php public $var6 = myConstant;class SimpleClass public $var7 = array(true, false);{ // This is allowed only in PHP 5.3.0 and later. // invalid property declarations: public $var8 = <<<EODpublic $var1 = hello . world; hello worldpublic $var2 = <<<EOD EOD;hello world }EOD; ?>public $var3 = 1+2;public $var4 = self::myStaticMethod();public $var5 = $myVar; 161
  162. 162. Class constantsExample<?phpclass MyClass{const constant = Any Testing Constant Value;function showConstant() {echo self::constant . "n";}}echo MyClass::constant . "n";?> 162output: Any Testing Constant Value
  163. 163. ConstructorSyntax class SubClass extends BaseClassvoid __construct ([ mixed $args [, $... ]] ) { function __construct()Example {<?php parent::__construct();class BaseClass print "SubClass constructorn";{ }function __construct() }{ $obj = new BaseClass();print "BaseClass constructorn"; $obj = new SubClass();} ?>} Output: BaseClass constructor BaseClass 163 constructor SubClass constructor.
  164. 164. DestructorSyntax function __destruct() {void __destruct ( void ) print "Destroying " . $this->name . "n";Example }<?php }class MyDestructableClass $obj = new MyDestructableClass();{ ?>function __construct() Output{ In constructor Destroyingprint "In constructorn"; MyDestructableClass$this->name = "MyDestructableClass";} 164
  165. 165. Object inheritanceExample class bar extends foo<?php {class foo public function printItem($string){ {public function printItem($string) echo Bar: . $string . PHP_EOL;{ }echo Foo: . $string . PHP_EOL; }} $foo = new foo(); $bar = new bar();public function printPHP() $foo->printItem(baz); // Output: Foo: baz{ $foo->printPHP(); // Output: PHP is greatecho PHP is great. . PHP_EOL; $bar->printItem(baz); // Output: Bar: baz} $bar->printPHP(); // Output: PHP is great ?> 165} output:Foo: baz PHP is great. Bar: baz PHP is great.
  166. 166. Scope Resolution Operator (::)It is a token that allows access to static, constant, and overridden properties or methods of a class.The variables value can not be a keyword (e.g. self, parent and static).Example<?phpclass MyClass{const CONST_VALUE = Any constant value;}$classname = MyClass;echo MyClass::CONST_VALUE; ?>output:Any constant value 166
  167. 167. Self and parentTwo special keywords self and parent class OtherClass extends MyClass are used to access properties or { methods from inside the class definition. public static $my_static = static var; public static function doubleColon()Example {<?php echo parent::CONST_VALUE . "<br>";class MyClass echo self::$my_static . "<br>";{ }const CONST_VALUE = Any constant value; }} $classname = OtherClass;$classname = MyClass; OtherClass::doubleColon(); ?> 167 Output: A constant value static var
  168. 168. Static keywordDeclaring class properties or methods as static makes them accessible without needing an instantiation of the class.A property declared as static can not be accessed with an instantiated class object .The variables value can not be a keyword (e.g. self, parent and static). 168
  169. 169. Static keywordExample }<? public function getStaticData()class ClassName {{ echo ClassName::$staticvariable; //Accessing Static Variablestatic private $staticvariable; //Defining Static Variable }function __construct($value) }{ $a = new ClassName("12");if($value != "") $a = new ClassName("23");{ $a = new ClassName("");ClassName::$staticvariable = $value; //Accessing ?> Static Variable Output:12} 23 169$this->getStaticData(); 23
  170. 170. Abstract classesIt is not allowed to create an instance of a class that has been defined as abstract.Syntax<?abstract class classname{//attributes and methodsabstract function methodname}class derived extends classname{ function methodname} 170?>
  171. 171. Abstract classExample class EmployeeData extends employee //extending abstract class<? {abstract class employee function __construct($name,$age){ {protected $empname; $this->setdata($name,$age);protected $empage; }function setdata($empname,$empage) function outputData(){ {$this->empname = $empname; echo $this->empname;$this->empage = $empage; echo $this->empage;} }abstract function outputData(); EmployeeData("Hitesh","24"); $a = new 171} $a->outputData(); ?> Output: Hitesh 24
  172. 172. Object interfacesInterface is a object oriented concept,It is the place where we can define the function.SyntaxInterface interface_name{const 1;const N;function methodName1()function methodNameN()} 172
  173. 173. Object interfacesExample function shimu()<?php {interface shahu print "<br />";{ print self::lotu;const lotu="lotu is lucky"; }public function rooja(); }} $hanu=new hasu();class hasu implements shahu $hanu->rooja();{ $hanu ->shimu();public function rooja() ?>print "<br />"; output:lotu is luckyprint self::lotu; print "<br />"; www.opengurukul.comhai roja 173print "hai roja"; } lotu is lucky
  174. 174. OverloadingOverloading in PHP provides means to dynamically "create" properties and methods.All overloading methods must be defined as public.Two types of overloading are there-Property overloading-Method overloading 174
  175. 175. Property overloadingExamplevoid __set ( string $name , mixed $value )mixed __get ( string $name )bool __isset ( string $name )void __unset ( string $name )The $name argument is the name of the property being interacted with.__set() is run when writing data to inaccessible properties.__get() is utilized for reading data from inaccessible properties.__isset() is triggered by calling isset() or empty() on inaccessible properties.__unset() is invoked when unset() is used on inaccessible properties. 175
  176. 176. Method overloadingExamplemixed __call ( string $name , array $arguments )mixed __callStatic ( string $name , array $arguments )-$name argument is the name of the method being called.-The $arguments argument is an enumerated array containing the parameters passed to the $nameed method.__call() is triggered when invoking inaccessible methods in an object context.__callStatic() is triggered when invoking inaccessible methods in a static context. 176
  177. 177. Object iterationPHP 5 provides a way for objects to be foreach($this as $key => $value) defined so it is possible to iterate through { a list of items. print "$key => $value<br>";Example }<?php }class MyClass }{ $class = new MyClass();public $var1 = value 1; foreach($class as $key => $value)public $var2 = value 2; {public $var3 = value 3; print "$key => $value<br>";protected $protected = protected var; }function iterateVisible() echo "<br>";{ 177 $class->iterateVisible(); ?>echo "MyClass::iterateVisible:n";
  178. 178. Magic methodsThere are so many functions which are _wakeup magical in php _toString_construct _invoke_destruct _set_state_call _clone_callStatic_get_set_isset_unset_sleep 178
  179. 179. __sleep and __wakeupSerialize()checks if your class has a function with the magic name __sleep,If so, that function is executed prior to any serializationUnserialize()checks for the presence of a function with the magic name __wakeupIf present, this function can reconstruct any resources that the object may have. 179
  180. 180. __toString,__invoke,__set_state__toStringThe __toString method allows a class to decide how it will react when it is treated like a string.__invokeThe __invoke method is called when a script tries to call an object as a function.__set_stateThis static method is called for classes exported by var_export() since PHP 5.1.0. 180
  181. 181. Final keywordIt prevents child classes from overriding a method by prefixing the definition with final.If the class itself is being defined final then it cannot be extended.Properties cannot be declared final, only classes and methods may be declared as final. 181
  182. 182. Final keywordExample<?phpfinal class BaseClass {public function test() {echo "BaseClass::test() calledn";}final public function moreTesting() // Here it doesnt matter if you specify the function as final or not{echo "BaseClass::moreTesting() calledn";}}class ChildClass extends BaseClass { 182}// Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass) ?>
  183. 183. Cloning objectit simply creates a copy of an object. $so = new SmallObject;Example $so->field++;$x = 1; $soRef = $so;$y =& $x; $soClone = clone $so;$x++; $so->field++;echo"$y $x<br>"; echo $so->field; // outputs: 2class SmallObject echo $soRef->field; // outputs: 2{ echo $soClone->field; // outputs: 1 public $field = 0;} 183
  184. 184. Late static bindingIt can be used to refer the called class.The name late static binding is coined because of the static:: will no longer be resolved using the class where the method is defined. 184
  185. 185. Late static bindingExample class Two extends One { public static function classIdentifier() {<?php echo __CLASS__;class One { }public static function classIdentifier() { }echo __CLASS__; Two::classtest();} ?>public static function classtest() { Output: Oneself::classIdentifier();}} 185
  186. 186. Objects and referencesExample $d->foo = 2; // ($c,$d) = <id><?php echo $c->foo."n";class A { $e = new A; public $foo = 1; function foo($obj) {} // ($obj) = ($e) = <id>$a = new A; $obj->foo = 2;$b = $a; // $a and $b are copies of the same } identifier foo($e); // ($a) = ($b) = <id> echo $e->foo."n";$b->foo = 2; ?>echo $a->foo."n"; output:2$c = new A; 2$d = &$c; // $c and $d are references 186 2
  187. 187. Object serializationSerialization in the context of storage and transmitting is the process of converting an object into a sequence of bitsso that it can persist in a storage medium and or transmitted across a network.serializing and unserializing can be done by two functions They are:-Serialize-unserializeserialize() returns a string containing a byte-stream representation of any valueunserialize() can use this string to recreate the original variable values. 187
  188. 188. Chapter 21PHP Built-in Functions 188
  189. 189. PHP Calendar Functions and constantscal_days_in_month:It Return the number of days in a month for a given year and calendar.Syntax:int cal_days_in_month ( int $calendar , int $month , int $year )Parameters:calendar - Calendar to use for calculation month - Month in the selected calendar year - Year in the selected calendarExample<?php$num = cal_days_in_month(CAL_GREGORIAN, 8, 2003);echo "There was $num days in August 2003";?> www.opengurukul.comOutput -There was 31 days in August 2003 189
  190. 190. cal_infoIt Returns information about a particular calendar.Syntax:array cal_info ([ int $calendar = -1 ] )Parameters:Calendar - Calendar to return information for. If no calendar is specified information about all calendars is returned.Example:<?php $info = cal_info(0); print_r($info); ?>output:Array ( [months] => Array ( [1] => January [2] => February [3] => March [4] => April [5] => May [6] => June [7] => July [8] => August [9] => September [10] => October [11] => November [ 190
  191. 191. Many other calender functioncal_from_jd:It Converts from Julian Day Count to a supported calendar.cal_to_jd:It Converts from a supported calendar to Julian Day Count.FrenchToJD :It Converts a date from the French Republican Calendar to a Julian Day Count.GregorianToJD:It Converts a Gregorian date to Julian Day Count. 191
  192. 192. Date/time Functions and constantsDate functionThe PHP date() function is used to format a time and/or date.Syntaxdate(format,timestamp) ;Parameterformat - Required. Specifies the format of the timestamptimestamp - Optional. Specifies a timestamp. Default is the current date and time. 192
  193. 193. Directory Functions and constantsChdir: It change the directorySyntax: bool chdir ( string $directory )Parameters: directory - The new current directoryExample:<?php // current directory echo getcwd() . "n"; chdir(public_html); // current directory echo getcwd() . "n"; ?>output:/home/vincent 193 /home/vincent/public_html
  194. 194. chrootIt change the root directorySyntaxbool chroot ( string $directory )Parametersdirectory - The path to change the root directory to.Example<?phpchroot("/path/to/your/chroot/");echo getcwd();?>output: / 194
  195. 195. getcwdIt gets the current working directorySyntax: string getcwd ( void )Example:<?php // current directory echo getcwd() . "n"; chdir(cvs); // current directory echo getcwd() . "n"; ?>output:/home/matsya home/matsya/cvs 195