1 / 94

ITCS373: Internet Technology Server-Side Programming PHP – Part 1

ITCS373: Internet Technology Server-Side Programming PHP – Part 1. Dr. Faisal Al-Qaed. Introduction to Server Side Programming. Web Server. Web server respond to client requests (typically from a Web browser) by providing resources, such as HTML/XHTML documents.

fern
Télécharger la présentation

ITCS373: Internet Technology Server-Side Programming PHP – Part 1

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ITCS373: Internet TechnologyServer-Side ProgrammingPHP – Part 1 Dr. Faisal Al-Qaed

  2. Introduction to Server Side Programming

  3. 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.

  4. 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).

  5. 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.

  6. 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 19th and July 5th. 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.

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

  8. Server Side Programming Concept

  9. 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.

  10. 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.

  11. 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.

  12. 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

  13. 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.

  14. 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).

  15. 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

  16. 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

  17. 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 <FONT SIZE=.+2.>, together with CFML (ColdFusion Markup Language) tags such as <CFQUERY>, <CFIF> and <CFLOOP>. • 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

  18. Server Side Programming Using PHP

  19. 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.

  20. 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.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).

  21. 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 <?php ?> • 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.

  22. 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.

  23. 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.

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

  25. 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 <html> <body> <?php echo "Hello World"; ?> </body> </html> • 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".

  26. 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.

  27. Comments in PHP <html> <body> <?php //This is a comment /* This is a comment block */ ?> </body> </html>

  28. 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; ?>

  29. 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)

  30. 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. <html> <body> <?php $txt1="Hello World"; $txt2="1234"; echo ($txt1." ".$txt2); //output: Hello World 1234 echo ("<BR />".strlen("Hello world!")); //output: 12 echo ("<br />$txt1 $txt2"); //will also work in PHP ?> </body> </html>

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

  32. If Statement <html> <body> <?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!"; ?> </body> </html>

  33. Switch Statement <html> <body> <?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"; } ?> </body> </html>

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

  35. 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

  36. 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

  37. 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 <br /> "; for( reset($ages); $elem=key($ages); next($ages)) print (“$elem is $ages[$elem] <br />”); ?> • reset function set the pointer to the 1st 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

  38. 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

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

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

  41. 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

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

  43. 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_functions.asp

  44. 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

  45. 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 ?>

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

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

  48. PHP Variable Scope

More Related