Php

Post on 12-Sep-2014

25 views 0 download

Tags:

description

Learn PHP basics

transcript

1

PHP

Server Side Scripting Language

www.php.net

2

What is the other side?

• JavaScript is the client side scripting language

• JavaScript is integrated within your browser

• It helps you do things on the user’s computer for e.g. form validation, simple calculation etc.

3

Why is PHP so powerful?• Open Source and cross-platform• especially lightweight and speedy• can send HTTP headers

– set cookies– manage authentication– and redirect users

• excellent connectivity to many databases • integration with various external libraries

– to let you generate PDF documents– parse XML– create and modify images on the fly

• no need for a special development environment or IDE– You start a block of PHP code with <?php and end it with ?> – PHP goes right into your Web pages

• You don't have to declare variables before you use them• it's easy to create arrays and hashes (associative arrays) • A good rule of thumb for PHP: "When in doubt, try it; it will probably work."

4

PHP history

• In 1995, when Rasmus Lerdorf started what was to become PHP, the only goal he had in mind was to find out who was reading his resume.

• Rasmus Lerdorf's original concept of creating tags within the HTML text for calling C code is revolutionizing the way dynamic Web applications are created.

• Though the code written by him has been revised and the scripting engine re-written from scratch. Still, the concepts and the inspiration for PHP came from Lerdorf's approach of finding practical and dynamic solutions that Web developers could use in their day-to-day work.

5

PHPServer Side Scripting language

Dynamic Web Pages

Mail

Cookies

DataBase Support

6

PHP Basics

• PHP meansPHP: Hypertext Preprocessor

• Escaping from HTML<?php . . . ?>

• StatementsYou use the semi-colon (;) at the end of the line

• CommentsPHP supports, C, C++ style comments./* C, C++ style multi-line comment */

7

Basic Syntax• <?php

echo "Hello, World!";?>produces Hello, World!

• Variables are marked with a preceding $. You could write "Hello, World!" like this: <?php$message = "Hello, World!";echo $message;?>

• String concatenation is done with . (a period)• other arithmetic operators are what you would expect:

<?php$greeting = "Hello ";$num = 3 + 2;$num++;echo "$greeting $num people!";?> produces Hello 6 people!

8

Single and double quote• Just as in Perl, a string surrounded with double quotes causes

variables inside it to be interpolated, but a string surrounded with single quotes does not. So,

• <?php$name = “Shantanu”;$greeting_1 = "Hello, $name!";$greeting_2 = 'Hello, $name!';echo "$greeting_1\n";echo "$greeting_2\n";?> produces Hello, Shantanu!

Hello, $name!• Note that the \n in the string turns into a new line, just as in Perl or in

C. This only works in double-quoted strings, however.

9

Arrays

• You set off array indices (regular or associative) with square brackets ([ and ]): $fruit[0] = 'banana';$fruit[1] = 'papaya';

• A shortcut for creating arrays is the array()$fruit = array('banana','papaya');

• The built-in function count() tells you how many elements are in an array: $fruit = array('banana','papaya');print count($fruit); prints 2

10

Arrays• Array index starts from 0• $a[0] = "first"; // a two element array

$a[1] = "second"; $a[] = "third"; // easy way to append to the array.// Now, $a[2] has "third"

• echo count($a); // prints 3• // create a hash in one shot• $myphonebook = array (• "sbabu" => "5348",• "keith" => "4829",• "carole" => "4533"• );• // oops, forgot dean! add dean• $myphonebook["dean"] = "5397";• // yeoh! carole's number is not that. correct it!• $myphonebook["carole" => "4522"• // didn't we tell that hashes and arrays are • //implemented alike? let's see• echo "$myphonebook[0]"; // sbabu• echo "$myphonebook[1]"; // 5348• Some functions useful in this context are sort(), next(), prev(), each().

11

Environment Variables

• If the page "http://domain.com/company/test.php” contains the code <?phpecho "[$REQUEST_URI]";?> it prints out [/company/test.php]

12

Custom Functions

• You can define your own functions as shown below. Return values can be any of the data types.

• function foo ($arg_1, $arg_2, ..., $arg_n) {• echo "Example function.\n";• return $retval;• }• Any valid PHP code may appear inside a

function, even other functions and class definitions. Functions must be defined before they are referenced.

13

Custom Functions - Example

• <?• function AddFive ($TheNumber)• {• $TheNumberPlusFive = $TheNumber + 5;• print("$TheNumber plus 5 equals

$TheNumberPlusFive.<br>");• }• AddFive(15);• AddFive(23);• ?>

14

Objects

• To create an object, use the new statement. • class foo {• function do_foo () { • echo "Doing foo."; • }• }• $bar = new foo;• $bar->do_foo();

15

Classes• class Employee {• var $empno; // employee number• var $empnm; // name• function add_employee($in_num, $in_name){• $this->empno = $in_num;• $this->empnm = $in_name;• }• function show() {• echo "$this->empno, $this->empnm";• return;• }• function changenm($in_name){• $this->empnm = $in_name;• }• }• $sbabu = new Employee;• $sbabu->add_employee(10,"sbabu");• $sbabu->changenm("babu");• $sbabu->show();

16

Guest Book Example• guest.htm

– A form where the site visitor will type his name and message.– Submit button will call the guestbook.php file.

• guestbook.php– open the guestbook.txt file– read old contents, add the new comment– display all comments to the browser– also add the new comment to the guestbook.txt file

• guestbook.txt– Starts with welcome message.– Keeps adding the comments added by users.– Don't forget to change the file permission from read to write once

uploaded to the server.

17

guest.htm

• <body>• <form name="form1" method="post"

action="guestbook.php">• <input type="text" name="visitor"><p>• <textarea name="comment" rows="10"

cols="40"></textarea><p>• <input type="submit" name="Submit"

value="Submit">• </form>• </body>

18

guestbook.php• <?• $file="guestbook.txt"; • $handle=fopen($file, "r+"); • $prevtext=fread($handle,filesize("$file")); • $new="<div align=\"center\"> Posted by:

<u><b>$visitor</b></u> <br> <p><font face=\"Fixedsys\"> $comment </font></p> <hr> </div>";

• $total = $prevtext . $new; • fclose($handle); • echo "$total"; • $handle=fopen($file, "w"); • fwrite($handle, $total); • fclose($handle); • ?>

19

guestbook.txt

• <p>Welcome</p>

20

Cookies

• To create and modify a cookie, use the PHP function setcookie(). setcookie() takes up to six arguments, depending upon how much control you want over the cookie and who can read its value.

• The simplest way of setting a cookie is like this:setcookie('name', 'bret');

21

Add the following to the top of guestbook.php

• <?php• if (!$mevisit1){• @setcookie("mevisit1", "$visitor", time()+3600);• }• If ($mevisit1 != $visitor){• echo "hi $mevisit1!, we know you are not $visitor!!";• }• else {• echo "welcome back, $visitor";• …• }

22

Variables through URL

• <html>

• <font color=<?php echo $mycolor; ?>>THis color is decided in the variable</font>

• </html>

• test.php?mycolor=blue

23

Control Structure (If - Else)

• You can use the control structures if and elseif: if ($user_count > 200) {print "The site is busy right now!";} elseif ($user_count > 100) {print "The site is sort of active right now!"; } else {print "The site is lonely - only $user_count user logged on.";}

24

Control Structure (while or for)

• To Print the following you can use looping structures such as for and while :I have eaten 4 bagels today.I have eaten 5 bagels today.I have eaten 6 bagels today.I have eaten 7 bagels today.

• $i = 4; while ($i < 8) {print "I have eaten $i bagels today.\n";$i++;}

• for ($i = 4; $i < 8; $i++) {print "I have eaten $i bagels today.\n"; }

25

Control Structure (foreach)

• <?php• $month = array("January", "February", "March", "April", "May",

"June", "July", "August", "September", "October", "Novemeber", "December");

• echo "<FORM METHOD=POST ACTION = results.php>";• echo "<SELECT NAME=column_name >";• echo"<OPTION VALUE=\"/\">Pick a Month</OPTION>";• foreach($month as $MON)• {• echo "<OPTION VALUE=\"$MON\">$MON</OPTION>";• }• echo "</SELECT></FORM>";• ?>

26

Switch• Switch is an elegant replacement for multiple if-elseif-else structure. • switch ($i) {• case 0:• print "i equals 0";• case 1:• print "i equals 1";• case 2:• print "i equals 2";• }• break, continue • break breaks out of current looping control-scructures. • continue is used within looping structures to skip the rest of the

current loop iteration and continue execution at the beginning of the next iteration.

27

Mobile Handset Dealer’s website Example

• index.phpThe file with a drop down option.

• myfiles/photos.htmA html file with photos section.

• myfiles/products.htmA html file with products section.

• myfiles/printer.phpThis .php file will display the contents of the current page with the help of printer.css stylesheet.

• myfiles/normal.cssNormal stylesheet file.

• myfiles/printer.cssPrinter friendly stylesheet file.

• myfiles/A6188.gif

28

Index.php1. <HTML>2. <HEAD>3. <LINK rel="stylesheet" type="text/css" href="include/normal.css">4. </HEAD>5. <BODY>6. <FORM name="infosys">7. <SELECT size="1"8. onchange="window.location=document.infosys.navigation.options[document.infosys.navigation.selectedIndex].value"

name="navigation">9. <OPTION selected>-------------------</OPTION>10. <OPTION value="index.php?do=photos">photos </OPTION>11. <OPTION value="index.php?do=products">products</OPTION>12. </SELECT>13. <?php14. switch ($do) {15. case "photos":16. include “myfiles/photos.htm";17. $printer=“myfiles/printer.php?print_mode=1&&doc=photos.htm";18. break;19. case "products":20. include “myfiles/products.php";21. $printer=“myfiles/printer.php?print_mode=1&&doc=products.htm";22. break;23. } ?>24. </FORM>25. <P>Want to print? <a href="<?php echo "$printer" ?>">Printer Friendly Page</a> </P>26. </BODY>27. </HTML>

29

myfiles/photos.htm

1. <html>2. <head>3. <title>Photo Gallery</title>4. </head>5. <body>6. <P> Please visit our photo gallery 7. <a href=“http://yahoo.com/photos">Here</a>8. </body>9. </html>

30

Myfiles/products.htm1. <html>2. <head>3. <title>Product specification</title>4. </head>5. <body>6. <p>Motorola A6188 </P> Welcome to your new office. The new Motorola

Accompli A6188 is a Chinese/English WAP-enabled PDA and mobile phone. Which makes it the world's smartest way to..<P>

7. <img src=include/a6188.gif>8. <TABLE>9. <TR> <TD>Device Name </TD> <TD>Accompli A6188 </TD> </TR>10.<TR> <TD>GSM 900 </TD> <TD> Yes</TD> </TR>11.<TR> <TD>Input Method </TD> <TD>On-screen keyboard/Voice

Recognition </TD> </TR>12.</TABLE>13.</body>14.</html>

31

myfiles/printer.php• <html>• <head>• <STYLE TYPE="text/css">• <?PHP• if ($print_mode != 1) { • include 'normal.css'; • } else { • include 'printer.css'; • } • ?>• </STYLE>• </head>• <body>• Print Friendly Page:• <?PHP• include "$doc";• ?>• </body>• </html>

32

myfiles/normal.cssmyfiles/printer.css

normal.css

1. body { color: white; background-color: #003366; font-size: 12pt}

2. A{color:#6666FF; text-decoration:none}

3. A:visited{color:#6666FF; text-decoration:none}

4. A:active{color:#6666FF; text-decoration:none}

5. A:hover{color:#6666FF; text-decoration:underline}

printer.css

1. BODY {margin: 2em; color: black; font-size: 12pt; text-indent: 2em;

2. /* i.e. 36pt */}

3. IMG {display: none}

4. table {font-size: 12pt; background: none; width: 100%;}

33

myfiles/a6188.gif

34

Estate broker example

• broker.htmA simple form with 4 fields Name, Surname, FlatHave and FlatWant with a submit button that will call the process_form.php file.

• process_form.phpThe variables $Name, $Surname, $FlatHave and $FlatWant are added to the “list” table of “broker” database. A mail is sent to the manager about the new entry added.

• display.phpDisplay everything from “list” table.

35

broker.htm1. <html>2. <head>3. <title> Add Record</title>4. </head>5. <body>6. Please add the record here...7. <FORM name="myform" ACTION="process_form.php" METHOD="POST">8. Your Name: <INPUT TYPE="TEXT" NAME="Name"><br>9. Your Surname: <INPUT TYPE="TEXT" NAME="Surname"><br>10.Flat Have at: <INPUT TYPE="TEXT" NAME="FlatHave"><br>11.Flat Want at: <INPUT TYPE="TEXT" NAME="FlatWant"><br>12.<INPUT TYPE="SUBMIT" VALUE="Add Record" NAME="sendit">13.<INPUT TYPE="SUBMIT" VALUE="Cancel" NAME="cancelit"><br>14.</FORM>15.</body>16.</html>

36

process_form.php

• <html>• <body>• <?php• mysql_connect("","","");• mysql_select_db("broker");• mysql_query ("INSERT INTO list values (´´, ´$Name´,

´$Surname´, ´$FlatHave´, ´$FlatWant´);");• ?>• Thank you for your entry.• </body>• </html>

37

Mail

• Now can you send an e-mail to the manager whenever someone adds an entry?

• Add the following code in the process_form.php file• <?php• mail("shantanuo@hotmail.com", "Entry Added","• Name : $Name• Surname : $Surname• Flat Have : $FlatHave• Flat Want : $FlatWant• ");• ?>

38

display.php1. <html>2. <body>3. The data stored into the “broker” Database -“List” Table.4. <?php5. mysql_connect("","","");6. mysql_select_db("broker");7. $query = "select * from list";8. $result = mysql_query ($query);9. while($row = mysql_fetch_array($result)) 10.{11.echo $row[Name] ."<br>". $row[Surname]."</p>";12.}13.?>14.</body>15.</html>

39

contents of database student Part I

• <?php• • $dbname = "student";• $loginname = "shaileshr21";• $loginpass = "";• $dbhost = "mysql";• • echo('<html><body bgcolor="#FFFFFF">');• echo('<font face="arial" size="+4"><center>');• echo(" $dbname");• • $id_link = @mysql_connect($dbhost, $loginname, $loginpass);• • $tables = mysql_list_tables($dbname, $id_link);• • $num_tables = mysql_num_rows($tables);

• // store table names in an array• $arr_tablenames[] = '';•

40

contents of database student Part II

• // store number of fields per table(index 0,1,2..) in an array• $arr_num_fields[] = '';• for ($i=0; $i < $num_tables; $i++) {• $arr_tablenames[$i] = mysql_tablename($tables, $i);• $arr_num_fields[$i] = mysql_num_fields(mysql_db_query($dbname, "select *

from $arr_tablenames[$i]", $id_link));• }• • // store field names in a multidimensional array:• // [i] == table number, [ii] == field number for that table• for ($i=0; $i < $num_tables; $i++) {• for ($ii=0; $ii < $arr_num_fields[$i]; $ii++) {• $result = mysql_db_query($dbname, "select * from $arr_tablenames[$i]",

$id_link);• $hash_field_names[$i][$ii] = mysql_field_name($result, $ii);• } • }

41

contents of database student Part III• for ($i=0; $i < $num_tables; $i++) {• echo("<center><h2> $arr_tablenames[$i] </h2></center>");• echo('<table align="center" border="1"><tr>');• $result = mysql_db_query($dbname, "select * from $arr_tablenames[$i]", $id_link);• for ($ii=0; $ii < $arr_num_fields[$i]; $ii++) {• echo("<th>");• echo $hash_field_names[$i][$ii];• echo("</th>");• }• echo("</tr><tr>");• $number_of_rows = @mysql_num_rows($result);• for ($iii = 0; $iii < $number_of_rows; $iii++) {• $record = @mysql_fetch_row($result);• for ($ii=0; $ii < $arr_num_fields[$i]; $ii++) {• echo("<td>");• // echo $record[$ii];• $mytext = nl2br($record[$ii]);• echo $mytext;• echo("</td>");• }• echo("</tr>");• }• echo("</table>");• }• echo('</body></html>');• ?>

42

Display Bookmarks Part I• <html>• <head>• <basefont face="Arial">• </head>• <body>

• <?php• // set database server access variables:• $host = "mysql";• $user = "shaileshr21";• $pass = "";• $db = "student";

• // open connection• $connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");

• // select database• mysql_select_db($db) or die ("Unable to select database!");

• // create query• $query = "select concat('<a href=\"',Website,'\">', Website, '</a>'), Explanation from Bookmarks where

Catgegory='$mycat'";

43

Display Bookmarks Part II• echo "<h2>$mycat</h2>";• // execute query• $result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());• // see if any rows were returned• if (mysql_num_rows($result) > 0) {• // yes• // print them one after another• echo "<table cellpadding=10 border=1>";• while($row = mysql_fetch_row($result)) {• echo "<tr>";• echo "<td>".$row[0]."</td>";• echo "<td>" . $row[1]."</td>";• echo "</tr>";• }• echo "</table>";• }• else {• // print status message• echo "No rows found!";• }

• // free result set memory• mysql_free_result($result);

• mysql_close($connection);• ?>• </body>• </html>

44

Mysql front-ends

• phpMyAdminSearch across tables, Most Popular, (free software)

• phpFlashMyAdminUser friendly flash interface, graphical representation of innodb tables, (Paid)

• MySql Data ManagerBetter Administrative interface in perl (Paid)

45

Mysql interface

• CSV to MySQLhttp://www.sqldbu.com/eng/sections/tips/normalize.htmlUpload the .csv and get the create table and insert statements

• MySQL to CSVhttp://saraswaticlasses.com/sites/dump.phpType the table name and password to download the records in the excel form.

• MySQL to RSShttp://saraswaticlasses.com/sites/createrss.htmPublish the records from your mysql database using the RSS feed without any web interface.

46

Simple RSS Reader• <?php

• $cookies = array();• getcookies();

• if ($_GET["deleteall"]=="yes") {• foreach($cookies as $id=>$url) {• deletecookie($id);• }• header("Location: $PHP_SELF");• } elseif(is_numeric($_GET["delete"])) {• deletecookie($id);• header("Location: $PHP_SELF");• } elseif(!empty($_GET["formfeedurl"])) {• addcookie($formfeedurl);• header("Location: $PHP_SELF");• } elseif ($cookiecount > 0) {• foreach($cookies as $id=>$url) {• echo "<!-- FeedCookie[$id] == $url -->"; // For debugging, or something.• ?>• <script language="javascript" src="http://p3k.org/rss/index.r?url=<?php echo $url; ?>%3Ff

%3D7&amp;align=left&amp;width=300&amp;frameColor=black&amp;titleBarColor=%23add8e6&amp;titleBarTextColor=black&amp;boxFillColor=white&amp;textColor=black&amp;fontFace=&amp;maxItems=7&amp;compact=&amp;showXmlButton=&amp;javascript=true""></script>

• <?php• }• } else {• // There are no feeds defined.• }• ?>

47

Simple RSS Reader II

• <p style="clear: both">• <form action="<?php echo $PHP_SELF; ?>">• <input type="text" name="formfeedurl" size="26">• <input type="submit" name="Add" value="Add Feed">• </form>• <a href="<?php echo $PHP_SELF; ?>?

deleteall=yes">Delete All Cookies</a><p>• <a href="<?php echo $PHP_SELF; ?>?

source=yes">Source Code</a><p>

48

Simple RSS Reader Part III• <?php

• function getcookies() {• global $cookiecount, $cookies;• foreach ($_COOKIE as $name=>$value) {• if (ereg("^FeedCookie-([0-9]{1,2})$",$name,$regs)) {• $id = (int)$regs[1];• $cookies[$id] = $value;• }• }• $cookiecount = count($cookies);• }

• function addcookie($value) {• global $cookies;• for ($i=0; $i<100; $i++) {• if (!isset($cookies[$i])) {• $id = $i;• break;• }• }• if (!isset($id)) {• echo "No ID.";• return 0;• }• • setcookie("FeedCookie-$id",$value,time()+31536000);• return 1;• }

• function deletecookie($id) {• global $cookies;• if (isset($cookies[$id])) {• setcookie("FeedCookie-$id","",time()-3600);• return 1;• } else {• return 0;• }• }

• if ($source==yes) { • $source = 'simplefeed.php';• highlight_file( $source ); • }

• ?>