Presentation is loading. Please wait.

Presentation is loading. Please wait.

ITCS373: Internet Technology Server-Side Programming PHP – Part 1 Dr. Faisal Al-Qaed.

Similar presentations


Presentation on theme: "ITCS373: Internet Technology Server-Side Programming PHP – Part 1 Dr. Faisal Al-Qaed."— Presentation transcript:

1 ITCS373: Internet Technology Server-Side Programming PHP – Part 1 Dr. Faisal Al-Qaed

2 Introduction to Server Side Programming

3

4 Web Server Web server respond to client requests (typically from a Web browser) by providing resources, such as HTML/XHTML documents. Web server and clients communicate with each other via the platform independent Hypertext Transfer Protocol (HTTP). For example, when users enter a URL address such as http://www.w3schools.com/index.htm into a web- browser, they are requesting index.htm document from a web server. The web server maps the URL to a resource on the server and returns the requested resource to the client using HTTP. http://www.w3schools.com/index.htm

5 Popular Web Servers IIS (Internet Information Services) 5.0/6.0 is an enterprise-level web server that is included with several versions of Windows. It runs on Windows platforms and it is part of Windows OS (XP, Windows Server 2003) – (Not Free). The Apache web server, maintained by the Apache software foundation, is the most popular web server in use today and runs on many platforms (Unix-, Mac-, Windows- based platforms) – (it is open source and Freeware).

6 Client-Side (CS) Scripting CS scripting validates user input, accesses the browser and enhances web-pages with DHTML, ActiveX controls, and Java Applets. CS validation reduces the number of requests that needed to be passed to the server. Performance Tip: to conserve server resources and minimize internet traffic and delays, perform as much processing as possible on the client side. Interactivity allows users to make decisions, click buttons, play games, and so on – making the website experience more interesting. However, CS does have limitations, such as browser dependency, the browser or scripting host must support the scripting language. Another issue is that CS scripts are viewable to the client (e.g. by using the view source option in IE browser). Some web developers do not advocate this because users potentially can view their code. Therefore, sensitive information such as passwords or other personally identifiable data should not be stored or validated on the client.

7 Server-Side (SS) Scripting Programmers have greater flexibility when using SS scripts. SS scripts executed on the server often generate custom responses for clients. For example, a client might connect to an airline’s web server and request a list of all flights from Bahrain to Scotland between May 19 th and July 5 th. The server queries the database, dynamically generates HTML content containing the flight list and sends the HTML document to the client. SS scripting languages have a wider range of programmatic capabilities than CS equivalents. For example, SS scripts often can access the server’s file directory structure, whereas CS scripts cannot. SS scripts also have access to the SS software that extends the server functionality such as counting the number of web page hits, server log files, etc.

8 You can place two types of files on the server. 1.HTML files, XHTML or XML all of which display their code at the client system. 2.Server Side scripts like PHP, ASP, etc. where the output of these scripts are displayed on the clients system.

9 Server Side Programming Concept

10

11 HTTP Request Types The most common HTTP request types are GET and POST. An HTTP request often posts data to a SS form handler (program) that processes the data. GET and POST requests can both used to send form data to a web server, yet each type sends the information differently. A GET request sends information to the server as part of the URL (e.g. www.search- engine.com/search?name=value), where search is the name of a SS form handler, name is the name of the HTML form element and value is the value assigned to that variable. Note a ? Separate the query string from the rest of the URL.www.search- engine.com/search?name=value

12 GET Method Submissions The contents of a form are concatenated with the action URL.  Name / value pairs are separated by ‘&’;  Each name is separated from its value by a ‘=’;  Spaces are replaced by plus signs ‘+’. Based on these rules, the appropriate input string is formed. You may see this string in the URL window of your browser after submitting a form and entering the requested HTML page. http://www.altavista.com/search.cgi?topic=computing&keywords =agents+software+papers&lang=en-gb POST Method Submissions The post method sends form data as an HTTP message, not as part of the URL. Because a GET request limits the query string (i.e. everything to the right of the ?) to 2048 characters, it is often necessary to send large pieces of information using the POST method. The POST method is also sometimes preferred because it hides the submitted data from the user by embedding it in HTTP message. The form data still reaches the server and is processed in a similar fashion to a GET request, but the user does not see the exact information sent. As a result, large pieces of information or sensitive form data such as passwords, are usually sent using the POST method.

13 Accessing Web Servers To request documents from web servers, users must know the machine names (called host names) on which the web server software reside. User can request documents from local web servers (i.e. ones residing on users’ machines) or remote web servers (i.e. ones residing on different machines). Local web server can be accessed in two ways:  Through machine name (computer name)  Through localhost – a host name that references the local machine, or through local IP (127.0.0.1) A remote web server can be accessed by the domain name that is registered with ISP (Internet Service Provider) or IP address of the remote machine.

14 Popular Server-Side Scripts: ASP/ASP.NET Microsoft ASP stands for Active Server Pages. The classic ASP is interpreted by IIS where ASP.net is a compiled.NET programming platform. ASP.NET takes the advantage of Microsoft.NET framework, which provides a thousands of classes. IIS can serve ASP.net documents, although the Apache web server support older versions of ASP (if additional modules are installed), it does not support ASP.net This means that ASP.net can be only executed using IIS on Windows platform only. The classic ASP file extension is.asp where ASP.net file is.aspx

15 Popular Server-Side Scripts: Perl/CGI Perl (Practical Extraction and Report Language) is the most widely used language for web programming, known for its power with text-processing capabilities. – Perl script needs interpreter program to be executed. CGI (Common Gateway Interface): is a standard protocol through which applications interact with web servers. Because CGI is an interface, it cannot be programmed directly, a script like Perl must be executed to interact with it. CGI add the necessary interface for Perl program to extract data from HTML form and cookies. Perl is arguably the most popular CGI program. IIS and Apache web server can both serve Perl generated documents. But of course you will need to install Perl interpreter Perl file extension is.pl or.cgi.

16 Popular Server-Side Scripts: Java Servlet/JSP Java Servlet/JSP (Java Active Pages) developed by Sun Microsystems. Java provides a number of built-in networking capabilities that make it easy to develop Internet-based and Web-based applications. A Servlet extends the functionality of a server, such as a Web server. Packages javax.servlet and javax.servlet.http provide the classes and interfaces to define servlets. Packages javax.servlet.jsp and javax.servlet.jsp.tagext provide the classes and interfaces that extend the Servlet capabilities for JSPs. Using special syntax, JSP allows Web-page implementers to create pages that use encapsulated Java functionality and even to write scriptlets of actual Java code directly in the page. Note that Servlet is a compiled java technology where JSP is a script that need an interpreter program to be executed. In fact, JSP file is converted into Servlet program on runtime before execution. The servlet and JSP are part of the Jakarta Project is called Tomcat server. Tomcat is based on Apache web server. It contains the official reference implementation of the JSP and servlet standards. JSP file extension is.jsp, where Servlet file extension is.java (before compilation) and. Class (after compilation).

17 Popular Server-Side Scripts: Python Python is an interpreted, cross-platform, object-oriented language that can be used to write large-scale Internet search engines, small administration scripts, GUI applications, CGI scripts and more. Python is a freely distributed technology whose open- source nature has encouraged a wide base of developers to submit modules that extend the language. Python’s interpreted nature facilitates rapid application development (RAD) of powerful programs. GUI applications, in particular, can be developed and tested quickly using Python’s interface to Tcl/Tk (among other GUI toolkits). ActivePython is the industry-standard distribution of Python for Windows, Solaris and Linux platforms. Python file extension is.py

18 Popular Server-Side Scripts: PHP PHP (Hypertext Preprocessor), is quickly becoming one of the most popular SS scripting languages for creating dynamic web pages. PHP is an open source technology that is supported by a large community of users and developers. Of PHP’s many strength as a SS language, perhaps the greatest lies in its ability to dynamically change its HTML output in reactions to user input. PHP is platform independent; implementations exist for all major Unix, Linux and Windows OSs. PHP script needs interpreter program to be executed. PHP also supports a large number of databases, including MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc. PHP file extension is.php

19 Other Server-Side Languages Macromedia ColdFusion MX (it is not free):  It is a programming language based on standard HTML that is used to write dynamic web-pages. ColdFusion pages consist of standard HTML tags such as, together with CFML (ColdFusion Markup Language) tags such as, and.  It supports most operating systems including Windows, Unix, Linux, IBM AIX and HP-UX  ColdFusion file extension is.cfm Ruby  Ruby is a dynamic, reflective, general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features.  It is open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.  In Ruby, Everything, including a literal, is an object, so this works: "ruby is cool".length #output = 12  Ruby file extension is.rb  It supports most operating systems including Windows, Unix, Linux, and Mac

20 Server Side Programming Using PHP

21 PHP: Hypertext PreProcessor PreProcessor means it processes what will appear as Hypertext before the hypertext appears on the screen. This means it will allow you to do programming, loops, database search, before the script generates the HTML that will appear on the screen.

22 Why PHP? PHP runs on different platforms (Windows, Linux, Unix, etc.) PHP is compatible with almost all servers used today (Apache, IIS, etc.) PHP is FREE to download from the official PHP resource: www.php.netwww.php.net PHP is easy to learn and runs efficiently on the server side. PHP is an open source technology that is supported by a large community of users and developers (so it will not die soon).

23 How Does it work? The server has an interpreter (a program) that takes the script you write as input, and it executes all the commands that are enclosed in the script type tags. For php these are Executing may display data, or perform comparisons, or loops. It may also access a database, to search for values and display the results on the screen.

24 What do you need to run PHP? You will need three components to work with PHP server side scripting;  Apache web server  PHP interpreter program  MySql database However, to make your lives easier, there is such a thing as a “kit”. All you have to do is to get an AppServ kit (ver. 2.5.10 for Windows) and install it. It will install all the three components for you without the need for doing any configurations.

25 The Directory to use: Once you have installed the kit you must find out what folder to place all your files in (i.e. C:\AppServ\www\) You can open an browser window and type the word localhost (or type in 127.0.0.1) and that will open the default page that came with the kit. Remember that the default page always has the name index so it is either index.htm or index.html or index.php.

26 Good PHP Tutorials for Beginner Check out these websites:  http://www.tizag.com/ http://www.tizag.com/  http://www.w3schools.com/ http://www.w3schools.com/

27 Your First Script You can use HTML Kit or Notepad if you wish and write a script that has php code in it, then save it as the filename.php <?php echo "Hello World"; ?> There are two basic statements to output text with PHP: echo and print. In the example above we have used the echo statement to output the text "Hello World".

28 Note: You cannot view the PHP source code by selecting "View source" in the browser - you will only see the output from the PHP file, which is plain HTML. This is because the scripts are executed on the server before the result is sent back to the browser.

29 Comments in PHP <?php //This is a comment /* This is a comment block */ ?>

30 Variables in PHP Variables are used for storing a values, like text strings, numbers or arrays. When a variable is set it can be used over and over again in your script All variables in PHP start with a $ sign symbol. <?php $txt = "Hello World!"; $number = 16; echo $txt; print $number; ?>

31 PHP is a Loosely Typed Language  In PHP a variable does not need to be declared before being set.  PHP automatically converts the variable to the correct data type, depending on how they are set.  In PHP the variable is declared automatically when you use it. Variable Naming Rules  A variable name must start with a letter or an underscore "_"  A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )  A variable name should not contain spaces. If a variable name is more than one word, it should be separated with underscore ($my_string), or with capitalization ($myString)

32 Another Example To concatenate two or more variables together, use the dot (.) operator The strlen() function is used to find the length of a string. <?php $txt1="Hello World"; $txt2="1234"; echo ($txt1." ".$txt2); //output: Hello World 1234 echo (" ".strlen("Hello world!")); //output: 12 echo (" $txt1 $txt2"); //will also work in PHP ?>

33 PHP Operators PHP operators are similar to C Operators (i.e. +, -, ==, !=, ++, --, %) See: http://www.w3schools.com/php/php_operato rs.asp

34 If Statement <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; elseif ($d=="Sun") echo "Have a nice Sunday!"; else echo "Have a nice day!"; ?>

35 Switch Statement <?php switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; } ?>

36 PHP Looping while (condition) code to be executed; do { code to be executed; } while (condition); for (initialization; condition; increment) { code to be executed; }

37 PHP Arrays There are three different kind of arrays:  Numeric array - An array with a numeric ID key  Associative array - An array where each ID key is associated with a value  Multidimensional array - An array containing one or more arrays

38 Numeric Arrays Create an array:  $names = array("Peter","Quagmire","Joe"); OR use this way:  $names[0] = "Peter";  $names[1] = "Quagmire";  $names[] = "Joe"; //will automatically use the next index echo $names[1]. " and ". $names[2]. " are ". $names[0]. "'s neighbors"; ?> echo count($names); //output 3

39 Associative array An associative array, each ID key is associated with a value. <?php $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; echo "Peter is ". $ages['Peter']. " years old "; for( reset($ages); $elem=key($ages); next($ages)) print (“$elem is $ages[$elem] ”); ?> reset function set the pointer to the 1 st element Key function will return the current key index Next function will move the pointer to next element The loop will continue as long as the key returns an index Note: unset($ages[‘Joe’]); will delete the element

40 Multidimensional Arrays $families = array ( "Griffin"=>array ( "Peter", "Lois", "Megan" ), "Quagmire"=>array ( "Glenn" ), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) ); echo "Is ". $families['Griffin'][2]. " a part of the Griffin family?"; //Is Megan a part of the Griffin family? //you can use $families[0][2] instead

41 The foreach Statement foreach (array as value) { code to be executed; } Example: <?php $arr=array("one", "two", "three"); foreach ($arr as $value) { echo "Value: ". $value. " "; } ?>

42 The foreach with Associative Arrays <?php $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; foreach ($ages as $key =>$value) { echo $key. “=".$value. " "; } ?>

43 PHP Functions Creating PHP functions: All functions start with the word "function()" Name the function - It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number) Add a "{" - The function code starts after the opening curly brace Insert the function code Add a "}" - The function is finished by a closing curly brace Note: PHP function names are not case sensitive

44 Example <?php function add($x,$y) { $total = $x + $y; return $total; } echo "1 + 16 = ". add(1,16); ?>

45 PHP Functions The real power of PHP comes from its functions library. In PHP - there are more than 700 functions available. See: http://www.w3schools.com/php/php_func tions.asp

46 Example: Header function <?php //Redirect browser header("Location: http://www.w3schools.com/"); ?> Note: header function must be used before any output including space character in the php file

47 Disable Caching Using Headers <?php //to disable caching use this header("Cache-Control: no-cache, must- revalidate"); // HTTP/1.1 //Or header("Expires: Mon, 26 Jul 2008 05:00:00 GMT"); // Date in the past ?>

48 PHP Server Variables <?php echo "Referer: ". $_SERVER["HTTP_REFERER"]. " "; echo "Browser: ". $_SERVER["HTTP_USER_AGENT"]. " "; echo "User's IP address: ". $_SERVER["REMOTE_ADDR"]; ?>

49 IP Split Example <?php //to disable caching use this header("Cache-Control: no-cache, must-revalidate"); ?> <?php $myIP=$_SERVER["REMOTE_ADDR"]; $arr=split("\.", $myIP); //explode(“\.", $myIP) is equivalent echo ($myIP." "); foreach ($arr as $value) echo ("IP Portion: ". $value. " "); ?>

50 PHP Variable Scope

51 Using global keyword Using $GLOBALS Associative Array: Using static keyword =>

52 PHP Form Handling Enter your name: Enter your age:

53 Welcome.php Welcome. You are years old!

54 Output Welcome John. You are 28 years old! Note: If the method attribute of the form is GET, then the form information will be set in $_GET instead of $_POST.

55 The $_REQUEST Variable The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods. Example Welcome <?php echo $_REQUEST["name"]; ?>. You are years old!

56 Form Validation User input should be validated whenever possible. Client side validation is faster, and will reduce server load. However, any site that gets enough traffic to worry about server resources, may also need to worry about site security. You should always use server side validation if the form accesses a database. A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error.

57 PHP Include and Require PHP Include: you can save yourself a great deal of time with the use of the PHP include command. include takes a file name and simply inserts that file's contents into the script that issued the include command. PHP Require: Just like Include command, the require command is used to include a file into your PHP code. However there is one huge difference between the two commands, though it might not seem that big of a deal. Include versus Require: When you include a file with the include statement and PHP cannot find it you will see an error message like “Warning: main(noFileExistsHere.php): failed to open stream: No such file or directory “ and the remaining php script will be executed because a Warning does not prevent our PHP script from running. On the other hand, if you used the require statement we would get the same warning message but with fatal error and the remaining php script will not be executed.

58 PHP Include Example Note: to use require instead, replace include with require(“menu.php”);

59 The Date() Function The date() function is used to format a time or a date. Syntax string date (date_format[,int timestamp]) This function returns a string formatted according to the specified format. A timestamp is the number of seconds from January 1, 1970 at 00:00

60 Date Examples This example uses the mktime function to create a timestamp for tomorrow. To go one day in the future we simply add one to the day argument of mktime. For your future reference, we have the arguments of mktime. Note: These arguments are all optional. If you do not supply any arguments the current time will be used to create the timestamp. mktime(hour, minute, second, month, day, year, daylight savings time)

61 Date Function: Time Reference For Full date reference, visit: http://www.tizag.com/phpT/phpdate.php

62 Example: Dynamic Content

63 noCache.php <?php //Note we will use this file for disable caching //in all php examples //you need to save this file with your PHP scripts header("Cache-Control: no-cache, must- revalidate"); // HTTP/1.1 header("Expires: Mon, 26 Jul 2008 05:00:00 GMT"); // Date in the past ?>

64 Form.php <?php require("noCache.php"); ?> Enter Your Details: Name: Surname: Occupation Description: Gender: Male Female

65 processData.php <?php require("noCache.php"); ?> <?php extract($_POST); //Built-in function that will extract form elements to PHP variables if ( !$name || !$sname || !$descr){ echo ("Information missing"); die(); // terminate script execution } else if (isset($T)) //used to check which submit button was used { displayTable($name,$sname,$descr,$gender); } else if (isset($L)) { displayList($name,$sname,$descr,$gender); } ?> Thank You

66 Continued: processData.php <?php function displayTable($name,$sname,$descr,$gender) { echo(" \n"); echo (" Name Surname Gender Description "); echo (" $name $sname $gender $descr "); echo (" \n"); } function displayList($name,$sname,$descr,$gender) { echo("Your Details: \n"); echo (" Name: $name Surname: $sname Gender: $gender Description: $descr "); echo (" \n"); } ?>

67 Example: Dynamic Table Creation

68 Form.php <?php require("noCache.php"); ?> Enter Table Size: Rows: Columns:

69 displayTable.php <?php require("noCache.php"); ?> <?php extract($_POST); //it will extract all form elements to PHP variables if ( !$rows || !$cols) { echo ("Table Info Missing"); die();} else { settype($rows,"integer"); //data-type conversion function (integer, double, string) settype($cols,"integer"); if ($rows>0 && $cols>0) displayTable($rows,$cols); else { echo ("Invalid Table Size"); die(); } } ?> Your Table Size is

70 Continued: displayTable.php <?php function displayTable($rows,$cols) { echo(" \n"); for ($r=1;$r<=$rows; ++$r) { echo (" "); for ($c=1;$c<=$cols; ++$c) echo (" $r:$c "); echo (" "); } echo (" \n"); } ?>

71 Form Example with $PHP_SELF

72 <?php extract($_POST); if (!isset($submit)) { // if page is not submitted to itself echo the form ?> "> First Name: Last Name: Gender: Male: Female: Please choose type of residence: Steak: Pizza: Chicken: Enter your favorite quote! Select a Level of Education: Jr.High HighSchool College

73 Select your favorite time of day: Morning Day Night <?php } else { echo "Hello, ".$Fname." ".$Lname.". "; echo "You are ".$gender.", and you like: "; foreach ($food as $f) { echo $f." "; } echo " ".$quote." "; echo "You're favorite time is ".$TofD.", and you passed ".$education."! "; } ?>

74 Cookies Creating Cookie: <?php $inTwoMonths = 60 * 60 * 24 * 30 * 2 + time(); setcookie("lastVisit", "my site is wonderful", $inTwoMonths); ?> Note: time() return the current time in seconds Reading Cookie: <?php if(isset($_COOKIE['lastVisit'])){ $visit = $_COOKIE['lastVisit']; echo "The contents of your cookie are - ". $visit;} else echo "You've got out of date cookie!"; ?> Deleting a Cookie <?php // set the expiration date to one hour ago setcookie(“lastVisit", "", time()-3600); ?>

75 Session A 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. When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state. A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database or file. Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

76 Sessions <?php session_start(); //store session data $_SESSION['views'] = 1; //retrieve data echo "Pageviews = ". $_SESSION['views'];?> Click here <?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views'] = $_SESSION['views']+ 1; else $_SESSION['views'] = 1; echo "views = ". $_SESSION['views']; ?> Note: The session_start() function must appear BEFORE the tag: Tip: a good use of session is to check whether the user had login or not, if not, redirect the user to the login page. <?php //destroy Session views unset($_SESSION['views']); //Destroy All Sessions session_destroy(); ?>

77 What if a Browser Does NOT Support Cookies/Sessions? If your application deals with browsers that do not support cookies/sessions, you will have to use other methods to pass information from one page to another in your application. There are two ways of doing this:

78 1. Add parameters to a URL You can add parameters to a URL: Go to Welcome Page And retrieve the values in the "welcome.php" file like this: <?php $fname= $_GET["fname“]; $lname=$_GET[“lname“]; echo (" Hello $fname $lname ! "); ?>

79 2. Use a form You can use a form. The form passes the user input to "welcome.php" when the user clicks on the Submit button. You can use invisible form element called hidden as follow: or ’ /> Retrieve the values in the "welcome.php" file like this: $un=$_POST(“username"); $un=$_GET(“username"); //depending on the form method used

80 PHP Files Manipulating files is a basic necessity for serious programmers and PHP gives you a great deal of tools for creating, reading, and editing files. Create/Open/Close $myFile = "testFile.txt"; $myFileHandle = fopen($myFile, 'w') or die("can't open file"); fclose($myFileHandle);

81

82 File Write $myFile = "testFile.txt"; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = "Bobby Bopper\n"; fwrite($fh, $stringData); $stringData = "Tracy Tanner\n"; fwrite($fh, $stringData); fclose($fh); Note: if you open the file again with ‘w’ mode, it will overwrite the old data

83 File Read $myFile = "testFile.txt"; $fh = fopen($myFile, ‘r') or die("can't open file"); $theData = fread($fh, 5); //it’ll read 5 bytes fclose($fh); echo $theData;

84 File Read: reading all data in a file $myFile = "testFile.txt"; $fh = fopen($myFile, 'r'); $theData = fread($fh, filesize($myFile)); fclose($fh); echo $theData; Note: filesize will return returns the length of a file, in bytes

85 File Read by line $myFile = "testFile.txt"; $fh = fopen($myFile, 'r'); $theData = fgets($fh); fclose($fh); echo $theData; Note: fegets read the file by line. Use this function if you had separated your data with new lines.

86 Reading a File Line by Line <?php $file = fopen("welcome.txt", "r") or exit("Unable to open file!"); //The feof() checks if the "end-of-file" (EOF) has been reached while(!feof($file)) { echo fgets($file). " "; } fclose($file); ?> Note that you can use split or explode the function to read each string in the line separately

87 Reading a File Character by Character <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); while (!feof($file)) echo fgetc($file); fclose($file); ?> The fgetc() function is used to read a single character from a file.

88 Read file using fscanf Function <?php require("noCache.php"); $handle = fopen("C:\AppServ\users.txt", "r"); while (!feof($handle)) { list ($name, $prof, $cc) =fscanf($handle, "%s\t%s\t%d\n"); echo "Hi $name, $prof, country code is $cc. "; } fclose($handle); ?> Note: DON’T Store your files in the Server path (i.e. WWW) because if so, it can be downloaded by any user. You can use the following for reading using fscanf (%c (char), %d (int), %f (float), %s (string)).

89 Browser Output Hi Noof, Student, country code is 971. Hi Ali, Manager, country code is 44. Hi Ameena, Secertary, country code is 973. Hi Mike, Supervisor, country code is 44. The content of the file users.txt as follows:

90 File Write using fprintf <?php $str = "Hello"; $number = 123; $file = fopen("test.txt","w"); echo fprintf($file,"%s world. Day number %d",$str,$number); ?>

91 Fseek function fseek($fh,0); //jump to the beginning of a file fseek($fh, 1024); //jump to byte 1024 from the beginning fseek($fh, 100, SEEK_CUR); //jump ahead 100 bytes from your current position fseek($fh, -100, SEEK_CUR); //jump back 100 bytes from your current position fseek($fh, -100, SEEK_END); //jump back 100 bytes before the end of the file

92 File Append to end of File $myFile = "testFile.txt"; $fh = fopen($myFile, 'a') or die("can't open file"); $stringData = "New Stuff 1\n"; fwrite($fh, $stringData); $stringData = "New Stuff 2\n"; fwrite($fh, $stringData); fclose($fh); The above example may not seem very useful, but appending data onto a file is actually used everyday. Almost all web servers have a log of some sort. These various logs keep track of all kinds of information, such as: errors, visitors, and even files that are installed on the machine. A log is basically used to document events that occur over a period of time, rather than all at once. Logs: a perfect use for append!

93 File Delete/Truncate Delete a file $myFile = "testFile.txt"; unlink($myFile); //will delete the file //make sure you delete the write file Truncate a file (deleting all information in the file) $myFile = "testFile.txt"; $fh = fopen($myFile, 'w'); fclose($fh);

94 Reading Read the Book Chapter on PHP Use PHP handout in the Yahoo Group as reference


Download ppt "ITCS373: Internet Technology Server-Side Programming PHP – Part 1 Dr. Faisal Al-Qaed."

Similar presentations


Ads by Google