0% found this document useful (0 votes)
19 views

PHP

PHP for IT students

Uploaded by

Efrem Mekonen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
19 views

PHP

PHP for IT students

Uploaded by

Efrem Mekonen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 100
> Used to create dynamic pages based a number of conditions when the user's Coreen reer iti used when the user’s browser already has alll the code and the page is altered browser makes a request to the server. > The Web Server executes the server-side scripting that produces the page to be sent to the browser. can access the file system residing at the web server. > The settings that belong to Web server can be accessed using server-side on the basis of the users input. ‘The Web Browser executes the client- side scripting that resides at the user's computer. ‘The browser receives the page sent by the server and executes the client-side scripts. Cannot be used to connect to the databases on the web server. can't access the file system that resides at the web server » The files and settings that are local at the user's computer can be accessed Cont... > can’t be blocked by the user > Response from a server-side script is > Response from a client-side scriptis slower as compared to a client-side faster as compared to a server-side script seript > Examples: PHP, JSP, ASP, ASP.Net, Examples: Javascript, VB script, ete. Ruby, Perl What is PHP? ° PHP was originally an acronym for Personal Home Pages. But now it is an acronym for Hypertext Preprocessor. It was developed as an open source. It contains a combination of HTML and scripting. Its file is an extension of .php * How does PHP work? TM. pages are easy-tjustpass thom along Hello server, Now! would liketo sea PHP page Hello client, Justa second... Ineed todo Ineedto read some work PHP pages and do tasks before’ I send them. on Here you are. send itin HTM. format. Servers — + PHP is a server-side technology. Therefore, you need to have a server to run PHP. What is a PHP File? PHP files can contain text, HTML, CSS. JavaScript, and PHP code PHP code are executed on the server, and the result is returned to the browser as plain HTML PHP files have extension ".php* What Can PHP Do? PHP can generate dynamic page content. PHP can create, open, read, write, delete, and close files on the server. PHP can collect form data PHP can send and receive cookies. PHP can add, delete, modify data in your database PHP can restrict users to access some pages on your website. PHP can encrypt data. Why We use —E + PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, ete.) +» PHP is compatible with almost all servers used today (Apache, IIS, etc.) « PHP supports a wide range of databases. + PHP is free. + PHP is easy to learn and runs efficiently on the server side. What Do I Need? To start using PHP, you can: + Finda web host with PHP and MySQL support « Install a web server on your own PC, and then install PHP and MySQL. Set Up PHP on Your Own PC However, if your server does not support PHP, you must: + installa web server * install PHP + installa database, such as MySQL The official PHP website (PHP net) has installation instructions for PHP. The PHP script is executed on the server, and the plain HTML result is sent back to the browser Basic PHP Syntax a | + A PHP script can be placed anywhere in the document : + The default file extension for PHP files is "php". + APHP file normally contains HTML tags, and some PHP scripting code. Example My first PHP page <2php echo "Hello World!"; > Comments in a + Acomment in PHP code is a line that is not read/executed as part of the program. Its only purpose is to be read by someone who is editing the code! Comments are useful for: » To let others understand what you are doing . » To remind yourself what you did . + PHP supports three ways of commenting: Example <2phy 7 This isa single line comment 4 This is also a single line comment f This is a multiple lines comment block that spans over more than one line ay: > PHP Case Sensitivity + In PHP. all user-defined functions, classes, and keywords (e.g. if, else. while, echo, etc.) are NOT case-sensitive. + In the example below, all three echo statements below are legal (and equal): Example "; echo "Hello World!
": EcHo "Hello World!
"; D> + However: in PHP, all variables are case-sensitive. Cont... + However: in PHP, all variables are case-sensitive. + Example + "; echo "My house is ". $COLOR . "
": echo "My boat is" . $eoLOR . "
"; b PHP Variables + Variables are "containers" for storing information: Cont... Example <2php $x=5; $y=6: $z=$x+$y; echo $z: D> Rules for PHP variables: » Avariable starts with the $ sign, followed by the name of the variable A variable name must start with a letter or the underscore character Avariable name cannot start with a number Avariable name can only contain alpha-numeric charactersand underscores (A-z, 0-9, and _ ) Variable names are case sensitive ($y and $Y are two different variables) NOTE: Remember that PHP variable names are case-sensitive! Declaring PHP Variables + PHP has no command for declaring a variable. + A variable is created the moment you first assign a value to it: Example <2php $txt="Hello world!"; $x=5; $y=10.5; ved Note: When you assign a text value to a variable, put quotes around the value. PHPis a Loosely Type Language PHP automatically converts the variable to the correct data type, depending on its value. PHP Variables Scope + In PHP, variables can be declared anywhere in the script. * The scope of a variable is the part of the script where the variable can be referenced/used. » PHP has three different variable scopes: Cont... local global static Local and Global Scope ‘A variable declared outside a function has @ GLOBAL SCOPE and can only be accessed outside a function. Avariable declared within a function has a LOCAL SCOPE and can only be accessed within that function. The following example tests variables with local and global scope Example Test variables inside the fuetions

" echo "Variable xis: $x" echo "
" echo "Varinble y is: Sy": myTest0; echo "

Test variables outside the fumetion:

echo "Variable xis: Sx echo "
" echo "Variable is: $y"; Cont... + Note: You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared. PHP The global Keyword + The global keyword is used to access a global variable from within a function. + To do this, use the global keyword before the variables (inside the function): Example PHP The static — « Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job. + Todo this, use the static keyword when you first declare the variable: Example <2php functionmyTest() { static $x=0: echo $x; $x; } myTest(); myTest(): myTest(): LP « Note: The variable is still local to the function. PHP echo and print Statements. + There are some differences between echo and print: + echo - can outputone or more strings * print- can only output one string, and returns always 1 NOTE: echo is marginally faster compared to print as echo does not return any value The PHP echo Statement echo is a language construct, and can be used with or without parentheses: echo or echo() Example PHP is fun!"; echo "Hello world!
"; echo "I'm about to learn PHP!
"; echo "This", " string", " was", " made' P "" with multiple parameters."; Display Variables + The following example shows how to display strings and variables with the echo command: Example "; echo "Study PHP at $txt2"; echo "My car is a {$cars[0]}": sed The PHP print Statement print is also a language construct, and can be used with or without parentheses: print or print. Cont... Example <2php print "

PHP is fun!

"; print "Hello world!
"; print "I'm about to learn PHP!"; P PHP Data Types + String, Integer, Floating point numbers, Boolean, Array, Object, NULL. PHP Strings + A string is a sequence of characters, like "Hello world!", + A string can be any text inside quotes. You can use single or double quotes: Cont... Example <2php Sx = "Hello world!"; echo $x: echo "
"; Sx = "Hello world!’; echo $x: » PHP Integers An integer is a number without decimals. Rules for integers: An integer must have at least one digit (0-9) An integer cannot contain comma or blanks An integer must not have a decimal point An integer can be either positive or negative Integers can be specified in three formats: decimal (10-based), hexadecimal (16- based - prefixed with 0x) or octal (8-based - prefixed with 0) Cont... * The PHP var_dump() function returns the data type and value of variables: Example "; $x = -345://negative number var_dump($x); echo "
"; $x = Ox8C; // hexadecimal number var_dump($x): echo "
"; $x = 047; // octal number var_dump($x): seg PHP Floating P 11 + A floating point number is a number with a decimal point or a number in exponential form. Example ": $x = 2.463; var_dump($x); echo "
"; $x = 8E-S: var_dump($x); > PHP Booleans + Booleans can be either TRUE or FALSE. + Sx=true; Sy=false: + Booleans are often used in conditional testing. PHP Arrays + Anarray stores multiple values in one single variable. + In the following example we create an array, and then use the PHP var_dump() function to return the data type and value of the array Example <2php Scars=array("Volvo","BMW","Toyota"); var_dump($cars): eS PHP Objects An object is a data type which stores data and information on how to process that data. Cont + In PHP. an object must be explicitly declared. + First we must declare a class of object. For this, we use the class keyword. A class is a structure that can contain properties and methods. + We then define the data type in the object class, and then we use the data type in instances of that class: Example color= $color: function what_color() { return $this->color; 3 i 9 PHP NULL Value + The special NULL value represents that a variable has no value. NULL is the only possible value of data type NULL. +» The NULL value identifies whether a variable is empty or not. Also useful to differentiate between the empty string and null values of databases. + Variables can be emptied by setting the value to NULL: Example <2php $x="Hello world!"; PHP String Functions A string is a sequence of characters, like "Hello world!". The PHPstrlen() function + The strlen(Q function returns the length of a string, in characters. Cont... Example PHP Assignment Operators « The PHP assignment operator is used to write a value to a variable. + The basic assignment operatorin PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right. Cont... OS Sam Ec eso NO xey xey The left operand gets set to the value ofthe expression on the right xty Xexty Addition ery XEXry Subtraction x*zy xex*y Matiplcation x/ty xex/y Division xhey xexhy Modulus Cont... Example Not equal Not identical Lb Greater than lk Less than Greater than or equal to le: Less than or equal to En Sx t= $y sx <> sy sx! $x >$y sx= $y $x <= $y True if $x is equal to Sy ‘True if $x is equal to Sy, and they are o the same type ‘True if $x is not equal to sy ‘True if $x is not equal to sy 4 ‘True if $x is not equal to $y, or they are not of the same type True if $x is greater than $y ‘True if Sx is less than sy True if $x is greater than or equal to Sy True if $x is less than or equal to $y | Cont... Example <2php $x=100; Sy="100"; var_dump($x == $y); echo "
"; var_dump($x === $y); echo "
"; var_dump(Sx != $y); echo "
"; var_dump($x !== $y); echo "
"; Sa=50; Sb=90, var_dump($a > $b): echo "
"; var_dump($a < $b); LQ Cont.. PHP Logical Operators Og ry ect eri and And $x and $y True if both $x and $y are tue or Or $x or $y True if either $x or $y is true xor Xor $x xor Sy True if either $x or $y is true, but not both & And $x 8& Sy True if both $x and sy are true | Il Or $x || $y True if either $x or $y is true | Not. gx True if $x is not true Cont.. PHP Array Operators IThe PHP array operators are used to compare arrays: clog Name scl coo + Union $x + $y Union of $x and $y (but duplicate keys are not overwritten) Equality True if $x and $y have the same key/value pairs Identity ‘True if $x and gy have the same key/value pairs in the same order and of the same types = Inequality $ul=sy True if $x is not equal to Sy ° Inequality Sosy ‘True if $xis not equal to Sy Cont.. Example <2php $x = array("a" —> "red", "b" => "green"); $y = array("c" => "blue", "d" => "yellow"): $z = Sx + Sy; // union of $x and $y var_dump($z); var_dump($x == $y); var_dump(S: Sy); var_dump(Sx != Sy); var_dump($x <> $y); var_dump($x !== $y): D> PHP if...else...else if Statements Conditional statements are used to perform different actions based on different conditions. PHP Conditional Statements + Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. « In PHP we have the following conditional statements: + if'statement - executes some code only if a specified conditionis true + if...else statement - executes some code if a conditionis true and another code if the conditionis false ...else statement - selects one of several blocks of code to be executed « if...elseif * switch statement - selects one of many blocks of code to be executed PHP - The if Statement + The if statement is used to execute some code only if a specified condition is true. Syntax if (condition) { code to be executed if conditionis true; } + The example below will output "Have a good day!" if the current time (HOUR) is less than 20: Cont... PHP switch Statement The switch statement is used to perform different actions based on different conditions. Use the switch statement to select one of many blocks of code to be executed. + Syntax + switch (n) { case label]: code to be executed if n=labell break; case label2: code to be executed if n=label2: break: case label3. code to be executed if n=label3; break: default: code to be executed if n is different from all labels: y J « Example ° <2pl $favcolor="red"; switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue, or green!"; : ?> PHP while Loops PHP while loops execute a block of code while the specified conditionis true. PHP Loops Ofien when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal code-linesiin a script, we can use loops to perform a task like this. In PHP. we have the following looping statements: while - loops through a block of code as long as the specified conditionis true do...while- loops through a block of code once. and then repeats the loop as long as the specified conditionis true for - loops through a block of code a specified number of times For each- loops through a block of code for each element in an array. Cont.. The while loop executes a block of code as long as the specified conditionis true. Syntax while (condition is true) { code to be executed: 3 The example below first sets a variable $x to 1 ($x=1:). Then, the while loop will continue to runas long as $x is less than, or equal to 5. $x will increase by 1 each time the loop runs ($x++;): Example <2php $x=1; while($x<=5) { echo "The number is: $x
"; SxHs } PD Cont... The do...while loop will always execute the block of code once. it will then check the condition, and repeat the loop while the specified conditionis true. Syntax » dof code to be executed; } while (condition is true); The example below first sets a variable $x to 1 ($x=1;). Then, the do while loop will write some output, and then increment the variable $x with 1. Then the conditionis checked (is $x less than, or equal to 52), and the loop will continue to run as long as $x is less than, or equal to 5: Example "; Sx+4; } while (Sx<=5); TZ Cont... Notice that in a do while loop the condition is tested AFTER executing the statements within the loop. This means that the do while loop would execute its statements at least once, even if the condition fails the first time. PHP for Loops PHP for loops execute a block of code a specified number of times. Syntax for (init counter; test counter; increment counter) { code to be executed; 3 Parameters: init counter: Initialize the loop counter value test counter: Evaluated for each loop iteration. If it evaluates to TRUE. the loop continues. If it evaluates to FALSE, the loop ends. increment counter: Increases the loop counter value Cont... Example <2php for ($x=0: $x<=10; $x+4) { echo "The number is: $x
"; } D> The PHP for each Loop The for each loop works only on arrays, and is used to loop through each key/value pair in an array. Syntax For each (Sarrayas $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, until it reaches the last array element. Cont... Example <2php $colors = array("red","ereen","blue"," yellow"); for each (Scolors as $value) { echo "$value
"; } > PHP - Constants Types e Aconstant is a name or an identifier for a simple value. A constant value cannot change during the execution of the script. » By default, a constant is case-sensitive. By convention, constant identifiers are always uppercase. - Aconstant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. » If you have defined a constant, it can never be changed or undefined. Cont... + To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name. Unlike with variables, you do not need to have a constant with a $. You can also use the function constant() to read a constant's value if you wish to obtain the constant's name dynamically. Cont... constant() function - As indicated by the name, this function will return the value of the constant. + This is useful when you want to retrieve value of a constant, but you do not know its name, i.e. It is stored in a variable or returned by a function. Example: > Only scalar data (boolean, integer, float and string) can be contained in constants. Difference between constants and variables «There is no need to write a dollar sign ($) before a constant, where as in Variable one has to write a dollar sign. «Constants cannot be defined by simple assignment, they may only be defined using the define() function. **Constants may be defined and accessed anywhere without regard to variable scoping rules. **Once the Constants have been set, may not be redefined or undefined. Valid and invalid constant names // Valid constant names define("ONE", "first thing"); define("TWO2", "second thing"); define("THREE_3", "third thing"); // Invalid constant names define("2TWO", "second thing"); define("__THREE__", "third value"); PHP Functions + User defined functions Besides the built-in PHP functions, we can create our own functions. A function is a block of statements that can be used repeatedly in a program. A function will not execute immediately when a page loads A function will be executed by a call to the function. Create a User Defined Function in PHP A.user defined function declaration starts with the word "function": Syntax functionfimnctionName() { code to be executed, } Note: A function name can start with a letter or underscore (nota number). « Function names are NOT case-sensitive. Cont... Example <2phy fiction writeMsg() { echo "Hello world!”; writeMsg(); // call the fimetion > PHP Function Arguments Information can be passed to functions through arguments. An argument is just like a variable Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want. just seperate them with a comma. Example "; familyName("Jani"); familyName("Hege"); familyName("Stale"); familyName("Kai Jim"); familyName("Borge"); PS PHP Default Argument Value + The following example shows how to-use a defanlt parameter. If we call the function setHeight() without argnments it takes the default value as argument: Example "; 1 setHleight(350): setFfeight(); //-will use the default value of $0 setHeight(135): setHeighi(S0), PHP Functions - Returning values To let a function return a value, use the return statement: Example "; echo "7 + 13="". sum(7.13). "
"; echo "2 +4=". sum(2.4): — PHP Arrays + An array stores multiple values in one single variable: Example <2php $cars=array("Volvo","BMW","Toyota"), echo "I like". Sears[0].",". Scars[1]." and" . $cars[2]. "."; > What is an Array? An array is a special variable, which can hold more than one value at a time Create an Array in PHP ° In PHP, the array() function is used to create an array: array(); +» In PHP, there are three types of arrays: + Indexed arrays - Arrays with numeric index + Associative arrays - Arrays with named keys + Multidimensional arrays - Arrays containing one or more arrays PHP Indexed Arrays There are two ways to create indexed arrays: + The index can be assigned automatically (index always starts at 0): $cars=array("Volvo","BMW"," Toyota"): + or the index can be assigned manually $cars[0]="Volvo"; $cars[1]="BMW", Scars[2]="Toyota": Example <2php $cars=array(""Volvo","BMW","Toyota"); echo 'T like" . $cars[0].",". $cars[1] "and" . $cars[2] . "."; P Get The Length of an Array - The count() Function The count() function is used to return the length (the number of elements) of an array: Example "; } D> PHP Associative Arrays + Associative arrays are arrays that use named keys that you assign to them. + There are two ways to create an associative array: "'35","Ben"=>"37","Joe"=>"43"); + Sage=array("Peter | Cont... Example <2php Sage=array("Peter"=>"35","Ben"=>"37","Toe"=>"43"): echo "Peter is " . Sage['Peter'] . " years old."; D> Loop Through an Associative Array To loop through and print all the values of an associative array, you could use a foreach loop, like this: Example "43"): foreach(Sage as $x=>$x_value) { echo "Key="_. $x.", Value="_. $x_value; echo "
"; } > PHP Global Variables - Superglobals PHP $GLOBALS $GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. The example below shows how to use the super global variable $GLOBALS: Example PHP $_ SERVER $_SERVER is a PHP super global variable which holds information about headers, paths, and script locations The example below shows how to use some of the elements in $_SERVER: Example <2php echo $_SERVER['PHP_SELF']; echo "
"; echo $ SERVER['SERVER_NAME’]: echo "
"; echo $ SERVER['HTTP_HOST']; echo "
"; echo $_SERVER['HTTP_REFERER']; echo "
"; echo $ SERVER[HTTP_USER_AGENT"; echo "
"; echo $_SERVER['SCRIPT_NAME"]; PS NT el he following table lists the most important elements that can go inside $ SERVER: iil ene ee |$_SERVER['PHP_SELF') Retums the filename of the currently executing script |$_SERVER['GATEWAY_INTERFACE'] Retums the version of the Common Gateway Interface (CGI) the server is using IS_SERVER['SERVER_ADOR’) Retums the IP address of the host server \$_SERVER[ SERVER_NAME’) Retums the name of the host server (such as www.w3schools.com) \$_ SERVER['SERVER_SOFTWARE'] Retums the server identification string (such as Apache/2,2,24) I$_SERVER['SERVER_PROTOCOL'] Retums the name and revision of the information protocol (such as HTTP/1.1 \$_SERVER['REQUEST_METHOD') Retums the request method used to access the page (such as POST) \$_SERVER['REQUEST_TIME’] Retums the timestamp of the start of the request (such as 1377687496) s_SERVERT QUERY_STRING!) Retumns the query string if the page is accessed via @ query string Cont. 5_SERVER['HTTP_ACCEPT] +_SERVER['HTTP_ACCEPT_CHARSET'] ;_SERVER['HTTP_HOST') 5_SERVERTHTTP_REFERER'] s_SERVER('HTTPS') 5_SERVER['REMOTE_ADDR'} ;_SERVER('REMOTE HOST) __SERVER('REMOTE_PORT' ;_SERVER['SCRIPT_FILENAME') |_SERVER['SERVER_ADMIN'] S_SERVER{'SERVER_PORT') ;_SERVER['SERVER_SIGNATURE'] __SERVER[PATH_TRANSLATED') :_SERVER['SCRIPT_NAME'] SERVERI'SCRIPT_URY Returns the Accept header from the current request Retums the Accept_Charset header from the current request (such as utf-8,150-8859-1) Retums the Host header from the current request Returns the complete URL of the current page (not reliable because not all luser-agents support it) Is the script queried through a secure HTTP protocol Returns the IP address from where the user is viewing the current page Returns the Host name from where the user is viewing the current page Returns the port being used on the user's machine to communicate with th| web server Returns the absolute pathname of the currently executing script Retums the value given to the SERVER_ADMIN directive in the web server configuration file (if your script runs on’ virtual host, it will be the value defined for that virtual host) (such as [email protected]) Returns the port on the server machine being used by the web server for communication (such as 60) Returns the server version and virtual host name which are added to serve| generated pages Returns the file system based path to the current script Returns the path of the current script Returns the URI of the current page PHP $_ REQUEST + PHP $ REQUEST is used to collect data after submitting an HTML form. Example
Name:
<2php Sname = $_REQUEST|['fname']; echo $name; > PHP $_POST + PHP$ POST is widely used to collect form data after submitting an HTML form with method="post". §_ POST is also widely used to pass variables. Example
‘2php echo $_SERVER|'PHP_SELF'];?>"> ="fname"> PHP $_GET PHP $_GET can also be used to collect form data after submitting an HTML form with method="get" $_GET can also collect data sent in the URL. Assume we have an HTML page that contains a hyperlink with parameters: Test SGET Example <2php echo "Study ". $_GET['subject'] ." at" . $_GET['web']; LP PHP - File Inclusion + You can include the content of a PHP file into another PHP file before the server executes it. There are two PHP functions which can be used to included one PHP file into another PHP file. The include() Function “The require() Function This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be reused on multiple pages. This will help developers to make it easy to change the layout of complete website with minimal effort. If there is any change required then instead of changing thousand of files just change included file. The include() Function ¢ The includeQ) function takes all the text in a specified file and copies it into the file that uses the include function. - If there is any problem in loading a file then the include() function generates a warning but the script will continue execution. - Assume you want to create a common menu for your website. Then create a file menu.php with the following content. Cont * Home * w3 schools ° AJAX © MySQL
Now create as many pages as you like and include this file to create header. For example now your test.php file can have following content.

This is an example to show how to include PHP file!

The require() Function The require() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script. So there is no difference in require() and include() except they handle error conditions. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed. You can try using above example with require() function and it will generate same result. But if you will try following two examples where file does not exist then you will get different results. Cont...

This is an example to show how to include wrong PHP file!

output This is an example to show how to include wrong PHP file! Cont...

This is an example to show how to include wrong PHP file!

output This fime Tilé execution halts and nothing is displayed. NOTE — You may get plain warning messages or fatal error messages or nothing at all. This depends on your PHP Server configuration. Creating Directories in PHP » Anew directory can be created in PHP using the mkdir( function. ° This function takes a path to the directory to be created. » To create a directory in the same directory as your PHP script simply provide the directory name. ¢ To create a new directory in a different directory specify the full path when calling mkdirQ. Cont... Deleting a Directory + Directories are deleted in PHP using the rmdir(O function. ¢ rmdir( takes a single argument, the name of the directory to be deleted. + The deletion will only be successful if the directory is empty. e If the directory contains files or other sub- directories the deletion cannot be performed until those files and sub-directories are also deleted. Read files in PHP ¢ The freadQ) function reads from an open file. + The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read. Example:- Open File in PHP ¢ A better method to open files is with the fopen() function. ° The first parameter of fopen() contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened. | Cont... (| Ee a file for read only. File pointerstarts at the beginning of the file |Open a file for write only. Erases the contents of the file or createsa new file ifit doesn't exist. File jpointer starts at the beginning of the file |Open a file for write only. The existing data in file is preserved. File pointerstartsat theend of the file. Createsa new file if the file doesn't exist (Creates a new file for write only. Returns FALSE and an erroriffile already exists |Open a file for read/write. File pointer startsat the beginning of the file Open a file for read/write. Erases the contents of the file or creates a new file ifit doesn't exist. File ipointer starts at the beginning of the file lOpen a file for read/write. The existing data in ile is preserved. File pointerstartsat the end of the file. Creates a new file if the file doesn’t exist (creates a new file for read/write. Returns FALSE and an error if file already exists PHP Cookies + Acookie is often used to identify a user. ‘What is a Cookie? + Acookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser it will send the cookie too. With PHP, you can both create and rettieve cookie values, Create Cookies With PHP: + Accookie is created with the setcookie( funetion. Syntax + seteookie(name, value, expire, path, domain, secnre, httponty); + Only the name parameter is required, All other parameters are optional PHP Create/Retrieve a Cookie +The following example creates a cookie named "user" with the value "fohn Doe". The cookie will expire after 30 days (66100 * 30). The "/" means that the cookieis available in enfie website (otherwise, select the directory you pref). + Wethen retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use the isset() function to find outif the cookie is set Note: The setcookie() function must appear BEFORE the tag. Example <2php Scookie_name = "user"; Seookie_valne = "Ton Doe"; setcookie(Scookie_name, Scookie_value, time() + (86400 * 30), "/"; // 86400 = 1 day "; echo "Value is: ". $ COOKIE[Scookie_name]; 3 is not sett” PHP Sessions + A session is a way to store information (in variables) to be used across multiple pages. + Unlike a cookie, the information is not stored on the users computer + Session variables hold information about one single user, and are available to all pages in one application. + Ifyou need a permanent storage. you may want to store the data in a database + Asessionis started with the session_startQ function. + Session variables are set with the PHP global variable: $_SESSION, Example Cont... + Note: The session_start() function must be the very first thing in your document. Before any HTML tags. Get PHP Session Variable Values + Example <2php session_stat(; W/Echo session variables that were set on previous page echo "Favorite coloris ". §_SESSION["faveolor"]."
" echo "Favorite animal is". $_SESSION["favanimal"] ." > Destroy a PHP Session + Toremove all global session variables and destroy the session, use session_unsel() and session_destroy(): Example bil <2php //xemove all session variables session_unset(): (destroy the session session_destroy(); > PHP MySQL Database + With PHP, you can connect fo and manipnlate databases + MySQL is the most popnlar database system used with PHP. ‘What is MySQL? + MySQL is a database system used on the web + MySQLis a database system that ins om a server + MySQL is ideal for both small and large applications + MySQL is very fast, reliable, and easy to use + MySQL uses standard SQL + MySQL compiles on a number of platforms + MySQLis free to download and use + MySQL is developed, distributed. and supported by Oracle Corporation The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of cohmns and rows. D: + Aquery is a question or a request. + We can query a database for specific information snd have a recordset retuned. Example: SELECT LastName FROM Employees yase Queries Connecting to databases >To connect PHP with database, four important things must be taken place. Those are:- a2 SoS Define constants Create connection using mysql_connect. Select database. Close connection. 1. Define constants >To connect php with database, defining constants is very important. Constants that must be defined are:- “ Define the server. efine user name of the server. “Define password of the user. Define database name. >» To define the constant, we can use as follows: php define("db_server","localhost");// the server that we use define("db_user","root");//the username of the server define("db_pass",")://password of the server define("db_name","schoolmgt"),//the database that we use » 2. Opening Database Connection » After defining constants using php, opening or creating connection is very important. To open or create database connection, we use mysql_connect function. + This function takes three parameters. Those are: + db_server,db_user,db_pass. _ Oa password of the user accessing the database. Thofiost name running database server The username accessing the database From the above the host name running database server is “localhost”, the username accessing the database is “user”, and the password of the user accessing the database is empty. Comnection can opened or created as follows. $connection=mysql_connect(db_server,db_user,db_pass); 3. Select database ° Once you establish a connection with a database server then it is required to select a particular database where your all the tables are associated. ° This is required because there may be multiple databases residing on a single server and you can do work with a single database at a time. + To select database, we use mysql_select_db as follows:- $db_select=mysql_select_db(db_name,$connection); 4, Closing database connection Its simplest function mysql_close PHP provides to close a database connection. This function takes connection resource returned by mysql_connect function. For example, to close the connection that you use in the above; you use mysql_close function as follows:- mysql_close($connection); Create MySQL Database Using PHP + To create and delete a database you should have admin privilege. Its very easy to create a new MySQL database. PHP uses mysql_query function to create a MySQL database. For example to create the database test_db using php, you can write as follows: <2php define("db_server","localhost"); define("db_user”,"root"): define("db_pass".""); Sconnection=mysql_connect(db_server.db_user.db_pass): if(/Sconnection) a die(“error connection to db server" anysql_errorQ); J echo “Comected successfill Ssql = “CREATE Database test_db; Sretval = mysql_query( $sql, connection); if{! Sretval ) { die(Could not create database: } ‘echo "Database test_db created successfilly\n"; mysql_close Sconnection): S mysql_error); Creating Database Tables / * To create tables in the new database you need to do the same thing as creating the database. First create the SQL query to create the tables then execute the query using mysql_query() function. Cont ". "EMP NAME : {$row['emp_name']}
". "EMP SALARY : {$row['emp_salary']}
". Cont... * The content of the rows are assigned to the variable $row and the values in row are then printed. e Always remember to put curly brackets when you want to insert an array value directly into a string. e In above example the constant MYSQL_ASSOC is used as the second argument to mysql _fetch_array(), so that it returns the row as an associative array. With an associative array you can access the field by using their name instead of using the index. ¢ PHP provides another function called mysql_fetch_assocQ) which also returns the row as an associative array. Using mysql_fetch_assoc() while($row = mysql_fetch_assoc($retval)) { echo "EMP ID :{$row['emp_id']}
". "EMP NAME: {$row['emp_name']}
" "EMP SALARY : {$row['emp_salary']}
". x Using MYSQL_NUM while(Srow = mysql_fetch_array(Sretval, MYSQL_NUM)) { echo "EMP ID :{$row[0]}
". "EMP NAME : {$row[1]}
" "EMP SALARY : {$row[2]}
, Deleting Data from MySQL Database » Data can be deleted from MySQL tables by executing SQL DELETE statement through PHP function mysql_query. * Below is a simple example to delete records into employee table. To delete a record in any table it is required to locate that record by using a conditional clause. Below example uses primary key to match a record in employee table. Semp_id = $_POST['emp_id']; $sql = "DELETE FROM employee WHERE emp_id= $emp_id" ; Deleting MySQL Database and table Using PHP Ifa database is no longer required then it can be deleted forever. You can use pass an SQL command to mysql_query to delete a database. $sql = 'DROP ees test_db’; deleting MySQL database $sql ='DROP TABLE employee’; deleting table Updating Data into MySQL Database * Data can be updated into MySQL tables by executing SQL UPDATE statement through PHP function mysql_query. * Below is a simple example to update records into employee table. To update a record in any table it is required to locate that record by using a conditional clause. Below example uses primary key to match a record in employee table. Semp_id=$_POST[emp_id’]; Semp_salary =$ POST|'emp_salary’]; $sql = "UPDATE employee". "SET emp_salary = Semp_salary". "WHERE emp_id=$emp_id" ;

You might also like