PHP (Hypertext Preprocessor) Preethi Mynepalli Coms 463(Networking II) Dr Syed Mahbubar April 28th , 2003 Table of Contents Definition…………………………………………………………..3 History……………………………………………………………..4 Uses………………………………………………………………..5 Advantages/Disadvantages of PHP……………………..…….…..6 Advantages of PHP over ASP……………………………………..7 General PHP Syntax……………………...………………………..8 Variables in PHP………………….……………………………….10 Conditions in PHP………………………………………………….11 PHP DB Connectivity……………………………………………...13 DB Connection in PHP……………………………………………12 DB Connectivity in ASP…………………………………………..15 Email in PHP………………………………………………………16 Email in ASP………………………………………………………15 Similarities between PHP and ASP………………………………..18 Differences & Similarities between PHP and Cold-Fusion…….…..19 Code related to cookies in PHP………………………….….……..20 Code related to cookie in ASP……………….…………….….…..21 Loops in PHP……………………………………..……………….22 Functions in PHP…………………………………..………………23 How PHP generates HTML Web Pages………………………..….24 Conclusion………………………………………………………….25 2 Definition of PHP PHP can be defined as a programming language for Database access from the web's browser. In other words, it is an HTML-embedded scripting language. It focuses on the logic of how a page responds to user input and not how the page looks that ie not the primary appearance of the page. PHP runs on the server side, which means that the web server that sends an HTML file to a user's browser, will carry out the instructions found in the embedded PHP code first, and then send the output of the PHP code along with the HTML code. The result is a webpage with dynamic content. 3 Brief History on PHP PHP is a language for creating website that can be more or less interactive. It was created in 1994 by Rasmus Lerdorf who was a software engineer and who was part of the Apache Team. In the same year, he created a package, added some database support and called it PHP/FI (Form Interpretation). In 1995, it was called the Personal Home Page Tool then was released as version2 with a name called PHP/FI (a form interpreter responsible for analyzing queries). In mid of 1997, more than 50,000 websites began using PHP and in October, 1998, there was an increase in the number of websites using PHP which was about 100,000. In 2000, there was a release of PHP 4.0.2. And currently over 1,000,000 sites in the whole world are using PHP. 4 PHP and its Uses Php can help read and write files. It also can do basic files and directory maintenance, therefore it basically can help one in editing documents. It can also take content that can be used in the generation of files in various formats which can include HTML (Hypertext Markup Language) and PDF. It also can help manage graphical content which include charts. Not only can it do the above but can it also read, write information in a database. You can make a PHP script to run it without any server or browser. You only need the PHP interpreter to use it. PHP's abilities include outputting images, PDF files, and even Flash movies. PHP can help also output easily any text, such as XML 5 Advantages and Disadvantages of PHP It is more or less cost –free in other words, PHP is an Open Source solution, freely available for a wide variety of platforms. It is also easy, as it’s a combination of C and Perl. The strongest and most significant feature of PHP is its native database support for a wide range of databases for example (MySQL, mSQL, Oracle), which allows access to the databases directly through SQL statements.* There is a cross-platform compatibility (Windows, Macintosh, or a version of Unix,): Compiled and is built on more than 25 platforms. With PHP, you have ‘freedom of choice’ regarding an operating system and a Web server. The error handling is not as sophisticated as in ASP (Active Server Pages). 6 Advantages of PHP over ASP Php runs faster and more stable than ASP PHP is Free and Easy PHP is more efficient with memory PHP can be run on any system with no performance issues PHP is tightly integrated with MySQL ASP commonly uses Microsoft Access which is much slower than MySQL More object oriented than ASP Database connections in PHP which is more than 200% (higher) 7 Basic/General Syntax of PHP Example of the syntax in PHP: <?php ... ?> When embedded in Html tags: <html> <head> <title>My first PHP page</title> </head> <body> This is normal HTML code <?php // PHP code goes here ?> Back into normal HTML </body> </html> 8 Screen-Shot of PHP code for “HELLO WORLD” 9 Variables in PHP Loosely “typed language” i.e given variable can be an integer, floating-point number, string, object, or an array. We shall limit ourselves to integers and floating-oint numbers. Integer: Mathematical data type and represents any whole number and usually can be any value from a negative value to a positive value. Floating-point number: Represents any value that contains a decimal point. A string : Is a datatype. Any combination of letters, numbers, or special symbols as long as consideration is given to characters that have functions in PHP. EXAMPLE OF AN INTEGER VARIABLE <?php // All of the following are numerically equivalent $myint = 83;// Normal decimal notation $myint = O123; // Octal notation for the # 83 $myint = 0x53; // Hexadecimal notation for # 83 ?> EXAMPLE OF AN INTEGER VARIABLE <?php // All of the following are numerically equivalent $myint = 83;// Normal decimal notation $myint = O123; // Octal notation for the # 83 $myint = 0x53; // Hexadecimal notation for # 83 ?> EXAMPLE OF A STRING VARIABLE <?php // This string begins and ends with single quotes $mystring = 'single quoted string'; // This string begins and ends with double quotes $mystring = "double quoted string"; ?> 10 Condition-code in PHP Code Relating to the Condition denotation in PHP <html> <? $var = date("H"); if ($var <= 11) { echo "good morning"; } else { if ($var > 11 and $var < 18) { echo "good afternoon"; } else { echo "good evening"; } } ?> </html> 11 Functions in PHP code SAMPLE CODE <? function show_form($value="") { ?> <form action="submit.php3" method="post"> <input type=text name=value value="<?echo $value?>"> <input type=submit> </form> <? } 12 Database Connectivity code in PHP <html> <head> <title>CDS Bought</title> </head> <body> <h4>Cds Bought</h4> <?php /* set's the variables for MySQL connection */ $server = "localhost:3306"; // this is the server address and port $username = "vworksusr"; // change this to your username $password = "vworkspass"; // change this to your password /* Connects to the MySQL server */ $link = @mysql_connect ($server, $username, $password) or die (mysql_error()); /* Defines the Active Database for the Connection */ if (!@mysql_select_db("cdlibrary", $link)) { echo "<p>There has been an error. This is the error message:</p>"; echo "<p><strong>" . mysql_error() . "</strong></p>"; echo "Please Contact Your Systems Administrator with the details"; } /* Passes a Query to the Active Database */ $result = mysql_query("SELECT * FROM cd_releases", $link); if (!$result) { echo("<p>Error performing query: " . mysql_error() . "</p>"); exit(); } /* Starts the table and creates headings */ ?> <table> <tr> <td><strong>Artist</strong></td> <td><strong>Title</strong></td> <td><strong>Year</strong></td> <td><strong>Label</strong></td> <td><strong>No of Tracks </strong></td> </tr> 13 <? /* Retrieves the rows from the query result set and puts them into a HTML table row */ while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo("<tr>\n<td>" . $row["Artist"] . "</td>"); echo("<td>" . $row["Title"] . "</td>"); echo("<td>" . $row["Year"] . "</td>"); echo("<td>" . $row["Label"] . "</td>"); echo("<td>" . $row["No_of_tracks"] . "</td>"); } /* Closes the table */ ?> </table> <? /* Closes Connection to the MySQL server */ mysql_close ($link); ?> </body> </html> 14 Reading from Data Bases: Data Base Connections in ASP (ASP VIEW) <html><head><title>Practice with SQLPractice</title></head> <body> <% 'connect to the database (note that ‘ in the beginning of a statement is used for commenting) strconn = "DRIVER=Microsoft Access Driver (*.mdb);DBQ=" & Server.MapPath("sqlpractice.mdb") SET objConn = Server.CreateObject("ADODB.Connection") objConn.Open strconn strSQL = "SELECT custname, custaddr, balance FROM customer" strSQL = strSQL & " WHERE balance >= 100;" ' create the recordset Set objRec = Server.CreateObject ("ADODB.Recordset") objRec.Open strSQL, objConn While Not objRec.EOF name = objRec("custname") addr = objRec("custaddr") bal = objRec("balance") Response.Write(name & ", " & addr & ", " & bal & "<br>") objRec.Movenext Wend Response.Write("</Table>") %> </body></html> 15 PHP EMAIL Php code related electronic mail Built-in function called mail(), that helps sends email. mail($receiver, $subject, $message, "From: $sender"); Function in PHP for the function is mail() function -return a variable -true or false, with regard to whether the mail was sent - echo information to your user, as to the email status. $sent = mail($receiver, $subject, $message, "From: $sender"); if ($sent) { echo "your message was sent"; }else { echo "your message was not sent"; } Using CDONTS to send a text based email message using ASP. <% Dim MyBody Dim MyCDONTSMail %> <% Set MyCDONTSMail = CreateObject("CDONTS.NewMail") MyCDONTSMail.From= "somebody@nowhere.com" MyCDONTSMail.To= "nobody@nowhere.com" MyCDONTSMail.Subject="This is a Test" MyBody = "Thank you for ordering that stuff" & vbCrLf MyBody = MyBody & "We appretiate your business" & vbCrLf MyBody = MyBody & "Your stuff will arrive within 7 business days" MyCDONTSMail.Body= MyBody MyCDONTSMail.Send set MyCDONTSMail=nothing %> 16 Sending emails with file attachments and carbon copies using ASP <% Dim MyBody2 Dim MyCDONTSMail3 %> <% Set MyCDONTSMail3 = CreateObject("CDONTS.NewMail") MyCDONTSMail3.From= "somebody@nowhere.com" MyCDONTSMail3.To= "nobody@nowhere.com" MyCDONTSMail3.Cc="nobody2@nowhere.com" MyCDONTSMail3.Subject="This is a Test" MyCDONTSMail3.AttachFile Server.MapPath("/somedirectory/bla.txt") ' or you could specify the path exactly if you knew it like below 'MyCDONTSMail3.AttachFile ("C:\inetpub\wwwroot\somedirectory\bla.txt") MyBody2 = "Thank you for ordering that stuff" & vbCrLf MyBody2 = MyBody2 & "We appretiate your business" & vbCrLf MyBody2 = MyBody2 & "Your stuff will arrive within 7 business days" MyCDONTSMail3.Body= MyBody2 MyCDONTSMail3.Send set MyCDONTSMail3=nothing %> 17 Similarities between PHP and ASP Positive Aspect They are easy to develop. They have easy database connection/configuration. The presentation is separate from processing. Negative Aspects They are scripting languages that have a narrow scope. They are scalability. 18 Differences between PHP and Cold Fusion Cold Fusion (Platform): Relatively limited Platform i.e. Windows, Solaris, Linux or HP/UX PHP (Platform) If you can compile it, it will run. (Language): Built for display code ie does not support user-defined functions. Really fast and easy for display pages and database interaction (Language) built to write applications. language is strong and very flexible Not as easy for the easy stuff, but much easier for the hard stuff. (Database Support): Abstracts database connections, making them simple to use, and very easy to change DB platform with no code changes (Database Support): Has extremely strong native DB support (File System Support): Adequate file support, but is quirky and not feature-rich (File System Support): Comprehensive file system support (Regular Expressions): Basic RegEx capability (Error-handling): good try/catch functionality, making formal error handling possible. (Regular Expressions): On par with PERL for Regex (Error-handling): has no formal error handling (Search Capability): bundled with Verity: *very* capable and feature-rich "fuzzy" search,engine for both file searches and database content searches (Search Capability): has no search capability Cold-Fusion is a web application server, and PHP is a web oriented scripting language. The difference is that PHP is free and Cold-Fusion is expensive. Similarities between PHP and Cold Fusion: Both provide dynamic contents. Both use HTML- like syntax so are easy to learn and easy to do maintenance. Neither needs compilation. Both cover variables, conditional statements, loops, wide variety of functions, and function libraries. 19 Codes relating to the Setting of a Cookie using PHP as well as ASP(Differentiation) PHP CODE RELATING TO COOKIES: <?php // See if the HTTP request has set $count as the // result of a Cookie called "count" if(!isset($count)) { // No cookie called count, set the counter to zero $count = 0; // .. and set a cookie with the "start" time // of this stateful interaction $start = time( ); setcookie("start", $start, time( )+600, "/", "", 0); } else { $count++; } // Set a cookie "count" with the current value setcookie("count", $count, time( )+600, "/", "", 0); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > <html> <head><title>Cookies</title></head> <body> <p>This page comes with cookies: Enjoy! <br>count = <?=$count ?>. <br>start = <?=$start ?>. <p>This session has lasted <?php $duration = time( ) - $start; echo "$duration"; ?> seconds. </body> </html> 20 CODE RELATING TO SETTING COOKIES IN ASP ‘Reponse.Cookies(cookiename)=cookievalue Creating a cookie and setting value of the cookie UserName to CoolDaddy. <% Response.Cookies(“UserName”)=”CoolDaddy” %> 21 Example of code related to LOOPS in PHP <html> <? for($i = 0; $i < 100; $i++) { echo "this message has echoed $i times <br>"; } ?> </html> Steps related to the Way PHP goes through the above code, in numbered format: When PHP parses the above code, it first sees for and looks inside the parentheses for three statements, separated by semicolons. The first statement that it parses is the declaration of the variable $i (remember in PHP variables must be preceded by a dollar sign) being set equal to zero by the statement $i = 0;. It then looks at the middle statement to check if the condition is true. In other words, it looks to see if $i < 100. Since $i is equal to 0 at this point, PHP goes on to the next statement, $i++, which means, raise the value of $i by one. PHP would then go on to execute whatever statements were made between the curly braces ({ and }), as many times as necessary, until the statement $i < 100 became false. Since $i was first set to zero, the code between the curly braces would be executed 100 times. If we wanted the loop to iterate more (or less) than 100 (0-99) times, we would replace 100 with a different value. 22 DENOTING FUNCTIONS IN PHP Code related to functions in PHP function your_function_name() { your PHP code } Incorporated in the HTML tags <html> <? function hello_world() { echo "Hello world!"; } ?> <h3>A Modular PHP Program</h3> <? echo "I am about to say hello..."; hello_world(); echo "There you go, I said something."; ?> </html> SAMPLE CODE <? function show_form($value="") { ?> <form action="submit.php3" method="post"> <input type=text name=value value="<?echo $value?>"> <input type=submit> </form> <? } 23 24 CONCLUSION PHP is a free, open source scripting language. It is easy to develop and provides a powerful control. It helps provide a very strong support for a wide range of databases as well. It can be used on all major operating systems, which might include Linux. It has also support for most of the Web servers today which include the ‘Personal Web Server’, Netscape and a couple others. With PHP, you will have ‘freedom of choice’ regarding a platform, an operating system, a Web server, and a database. People can obtain knowledge and information much more easily than before and can organize them in a way they like by utilizing new technology that costs you less expensive or even free. 25 26 27