Title: php scritping notes Subject: Notes from "PHP in easy steps" by Mike McGrath, 2002 History: 1994 PHP= Personal Home Page - set of perl scripts, by Rasmus Lerdorf. 1996 PHP-FI born 1998 PHP3 (API parser for PHP-FI), by Zeev Suraski and Andi Gutmans. 2000 PHP4 (incorperated the ZEND engine) gaining browser independence. Purpose: to read&write files, gather&process FORM data, send data via email, access&manipulate dataase records, read&write cookies, maintain data in a session variables, facilitate user authentication, provide data encryption, and it keeps growing. Process: client requests-> server runs php parser -> parser accesses database -> parser replaces php lines in docurment -> server returns complete html to client. Requirements: Apache, for windows, didn't take any notes. Sorry. MySQL, for windows, http://sourceforge.net/projects/mysql, pickup mysql3.23.49-win.zip run setup.exe, choose c:\MySQL, rename c:\MySQL\my-example.cnf to mycnf.cnf In nt, win2k, xp, install as service with c:\MySQL\bin\mysqld-nt --install NET START mysql Enter Databae: c:\MySQL\bin\mysql PHP, for windows, www.php.net -> get php-4.1.1-Win32.zip, php-installer.zip unzip to c:\php copy c:\php\php.ini-dist to c:\Windows\php.ini, for initial install better for live systems, is to use php.ini-recommended specify in php.ini location of php files, doc_root for apache for linux, download php-4.1.1.tar.gz tar -xzvpf php-4.1.1.tar.gz; cd php-4.1.1/ Make make files: ./configure --with-mysql --with-apxs=`whereis apxs` Compile: make Install: make install cp /usr/local/php-4.1.1/php.ini-dist /usr/local/lib/ Go to http://php.net/manual/en/security.php Configure apache, for windows, edit httpd.conf -> AddType application/x-httpd-php .phtml .php .php3 .php4 AddType application/x-httpd-php-soure .phps ScriptAlias /php/ "c:/php" Action application/x-httpd-php "/php/php.exe" Test php install: make info.php one line file, and put in doc_root. Test mysql access: make mysqltest.php, and put in doc_root. MySQL Connection Test

#Learning to walk ############################################# php code must be in 3 markup tags ############################################################### php is not case sensetive semicolon ends each line comments on a single line begin wth // or # or surrounded by /* to */ backslach protects the meaning of the character that follows it. \n = new line \t = tab Functions declaration order does not matter (the way it does in shell). ############################################################### Loose typing, $variablename can represent string, integer, float, boolean, NULL Declare variable: $variable = "My Stuff\tand\tYour Stuff, cause I\'m greedy"; Dereferece variable: echo ( "My stuff contains: $variable
" ); variables are local by default keyworkds "local" and "global" control scope ############################################################### There are many functions... ---------------------------- Function: echo () #Send output from php parser back to the browser. save this as hello.php Hello World" ); ?> * HTML source looks like this in a browser:

Hello World

############################################################### Declare a function function my_function () { echo ("This is my funktion"); } # Call the funtion -------------------------------------------- my_function (); # Passing to a funtion ---------------------------------------- $args"); } ?> # Passing to & Returning from a function ---------------------- $args"; return $value; } ?> # Passing a list to a funtion, and Setting Default Values ----- The sum equals $the_sum
"); $the_sum = bla (); echo ("
The sum equals $the_sum
"); ?> ############################################################### #Arithmetic Operators------------------------------------------ + addition - subtraction * multiplicaiton / division % modulo ++ incriment -- decriment #String operator----------------------------------------------- . Concatination $a=1; $b=2; $c=10; $result = ($a+$b); #add contents of a and b, assign to results echo ("
a plus b = $result"); $result .= ", but it does not equal $c"; #string operator . adds text to the end. echo ("
a plus b = $result"); #Assignment Operators------------------------------------------ = += -= *= /= %= .= #Comparison Operators------------------------------------------ == != > < >= <= ############################################################### Logical && and return true (1) if both are true || or return true (1) if either is true xor exclusive XOR return true (1) if one is ture and one is false ! NOT return true (1) if test is false common practice for a togle ( a=!a ) #Test syntax: : ; $test = ( $a and $b ) ? "true" : "false"; echo $test; ?> ############################################################### # Control structures #if------------------------------------------------------------ #if-else ------------------------------------------------------ $num
"; if ( $num%2 != 0){ $msg = "$num is odd ."; echo ( "
$msg
" ); } else if ( $num%2 == 0){ $msg = "$num is not odd."; echo ( "
$msg
" ); } ?> #switch -or- case (depending on where you are from) ----------- this is a case 1 code
"); break; case 2 : echo ( "
this is a case 2 code
"); break; case 3 : echo ( "
this is a case 3 code
"); break; } ?> #for ---------------------------------------------------------- ?> For Loop:\t"); for ( $i=0; $i<5; $i++ ){ echo "\t$i"; } ?> #foreach------------------------------------------------------- I you count to $value?"); } ?> #while -------------------------------------------------------- While Loop:\t"); while ( $i<10 ){ echo "\t$i"; $i++; } ?> #do-while ----------------------------------------------------- Do-While Loop:\t"); do { echo "\t$i"; } while ( $i<10 ); ?> #interrupting ------------------------------------------------- break; # exits the loop continue; # skips to the next iteration of the loop ############################################################### #Create array ------------------------------------------------- $arr[0].$arr[1].$arr[2]
"); ?> #Array size: sizeof() is an alias for count() ---------------- My array has $size elements
"); ?> # Add/remove from end of array -------------------------------- # Add/remove from beginning of array -------------------------- #Array keys&values--------------------------------------------- "Value 1", 'key2' => "Value 2", 'key3' => "Value 3"); ?> #One-based indexing ------------------------------------------- "1st","2nd","3rd","4th","5th"); #Manipulating arrays $arr = array_merge ($arr1,$arr2); $arr = array_slice($arr,1,4); $arr_new = shuffle($arr); ############################################################### # getenv() ---------------------------------------------------- ID users browser with getenv()
"); $browser=getenv("HTTP_USER_AGENT"); echo ("\tYou are using the browser $browser
"); ?> # Looking for a pattern in a variable ------------------------- ############################################################### # Making a date a/A Prints am/pm or AM/PM g/h Hours in 1-12/01-12 G/H Hours in 0-23/00-23 i Minutes 00-59 s Seconds 00-59 Z Time zone offset in seconds (-43200 to 43200) U Seconds since Jan 1, 1970 00:00:00 GMT j/d Day of the month 1-31/01-31 D/l Day of the week Mon-Sun/Monday-Sunday w Day of the week 0-6 from Sunday to Saturday M/F Month Jan-Dec/January-December n/m Month 1-12/01-12 $today=date("j M, Y"); # 10 Dec, 2003 $today=date("d.m.y"); # 10.12.03 $time= date("g:i a"); # 5.25 pm $time= date("H:i:s"); $ 05:25:30 The time is: $date $time
"); ?> ############################################################### #Random number # getting values from a form----------------------------------- #Make test3.html
Enter Your credit card number:"

Select card:
Master Card Visa American Express
#Make tes3.php----------------------------------------------- $steelme $account" ); } ?> ############################################################### # String manipulation----------------------------------------------- "); #$rev_string=(strrev=($my_string)); # echo ("Reverse string= $rev_string
"); $upcase_string = (strtoupper("$my_string")); echo ("Upcase string = $upcase_string
"); $lowercase_string=(strtolower("$my_string")); echo ("Lowercase string= $lowercase_string
"); $upcase_first_letter_of_each_word=(ucwords("$my_string")); echo ("Upcase each word = $upcase_first_letter_of_each_word
"); ?> ############################################################### # Using PHP_SELF Number guess guess what it is ..."; } #error message for invalid entries if ( $num != null and !is_numeric($guess)){ $msg="your guess was invalid

Try Again!

";} else if ($guess == $num) #is guess correct { if($num != null) { $msg="CORRECT! - THE NUMBER WAS $num"; $msg.="

"; $msg.="CLICK HERE TO TRY AGAIN???

"; } setnum(); #set a number number to guess } else if ($guess > $num) # is guess to high? { $msg="You guessed $guess

My number is lower!

"; } else if($guess < $num) # is guess to low? {$msg="You guessed $guess

My number is higher!

"; } echo ($msg); #write out the message ?>
Guess:
############################################################### # Browser redirection Redirect Choose a site to visit:
############################################################### # Working with File # List a dir -------------------------------------------------- you are on windows
"); $dirname="c:\\Apache\\bin"; } else if ( preg_match( "/linux/i", "$viewer" )){ echo ("
you are on linux
"); $dirname="/usr/local/httpd/expFreames/notes/"; } $dir=opendir($dirname); while( false != ($file = readdir($dir))) { if ( ($file != ".") && ( $file != "..") ) { $file_list .= "
  • $file"; } } closedir($dir); ?> Listing directory

    Files in

    # Copy and rename files --------------------------------------- # Deleting files ---------------------------------------------- # Opening &closing files -------------------------------------- # Reading a file ---------------------------------------------- # Writing a file ---------------------------------------------- # Logging visitor details ------------------------------------- # Enabling files uploads -------------------------------------- # Creating an upload form ------------------------------------- # Creating an upload script ----------------------------------- # Uploading a file -------------------------------------------- # Confirming file upload -------------------------------------- ################################################################ # mysql seciton ################################################################ # mysql_connect(server-name,user-name,password); Open connection to mysql server, Returns a link-identifyer on success or false on failure mysql_create_db(database-name, link-identifier); Create a new database on server with the specified link-identifyer Returns true on success or false on failure mysql_select_db (database-name, link-identifier); mysql_drop_db(database-name, link-identifier); mysql_fetch_array(result-resource); mysql_list_dbs(link-identifier); mysql_num_rows(result-resource); mysql_list_tables(database-name, link-identifier); mysql_query (SQL-query-string, link-identifier); ################################################################ ## gui for MySQLGUI: http://www.mysql.com/downloads/ #use mysql; --- opens a data base #show tables; --- list tables in database #explain users; --- to see format of the user table #create database ; -- create #show databases; -- list all databases #create table cars(id int, make text, model text); #primary key --- unique identifyer # data types # int # decimal # double # date # time # datetime # year # timestamp # char() # varchar() # text # blob # enum # set # modifyer not null- insist that each record must include data entry in this column unique - insist that the records may not duplicate any entry in this column auto_increment -available only for numeric columns to auto matically generate a number that is one more tha the previous value in that column primary key() - Specifies as its argument the name of the colun to be used as the primary key for that table. for example, 'primary key(id). i.e. create table cars(id int auto_increment, make varchar(20) not null, model varchar(20) not null unique, primary key(id) ); # inserting data insert into cars values(1,"Porsche","Carrera"); insert into cars(make,model) values("Ferrari","Dino"),("Lamborghini","Diablo"); #Altering an existing table use garage; select * from cars; alter table cars add top_mph int; # updating records update cars set model="911 Turbo" where id=1; update cars set model="F355" where make="Ferrari"; update cars set model="Murcielargo" where make="Lamborghini"; update cars set top_mph=189 where id=1; update cars set top_mpg=183 where id=2; update cars set top_mpg=205 where id=3; # Deleting data tables and databases delete from cars where id=3; alter table cars drop top_mph; drop table cars; drop database garage; ########################################## # query select * from cars where top_mph > 200; #php functions mysql_connect() mysql_query() ########################################## #creating mysql users and passwd #login mysql -u root mysql -u root -p passwd ########################################## # adding priv for mike grant all privileges on *.* to mike@localhost identify by "bingo" with grant option; ########################################## #connecting to a database as mike Connecting user

    ########################################## # Listing databasees "; } ?> Listing databases

    ########################################## # Listing table names ".$this_db."
    "; if($this_db != "mysql" ) { $rs2=mysql_list_tables($this_db); for($num=0; $num < mysql_num_rows($rs2); $num++) { $list.= " - ".mysql_tablename($rs2,$num)."
    "; } } } ?> Listing Tables</titles></head> <body><?php echo ($list); ?> </body></html> ########################################### # Creating a database <?php $conn=@mysql_connect("localhost","mike","bingo") or die("Sorry - could not connect to MySQL"); $rs1= @mysql_create_db( $db ); $rs2= @mysql_list_dbs( $conn ); for ($row=0; $row < mysql_num_rows($rs2); $row++) { $list .= mysql_tablename($rs2, $row)." | "; } ?> <html><head><title>Createing databases</titles></head> <body> <form action="<?php echo($PHP_SELF); ?>" method="post"> Current databases: <?php echo ($list); ?> <hr> Name:<input type="text" name="db"> <input type="submit" value="Create database"> </form></body></html> ########################################### # Deleting a database delete_table.php <?php <?php $conn=@mysql_connect("localhost","mike","bingo") or die("Sorry - could not connect to MySQL"); $rs1= @mysql_drop_db( $db ); $rs2= @mysql_list_dbs($conn); for ($row=0; $row < mysql_num_rows($rs2); $row++) { $list .= mysql_tablename($rs2, $row)." | "; } ?> <html><head><title>Drop databases</titles></head> <body> <form action="<?php echo($PHP_SELF); ?>" method="post"> Current databases: <?php echo ($list); ?> <hr> Name:<input type="text" name="db"> <input type="submit" value="Delete database"> </form></body></html> ########################################### # Create a table- create_table.php <html><head><table>Create a table</table></head> <body> <?php if( !$fields and !$db ){ $form ="<form action=\"$PHP_SELF\" method=\"post\">"; $form.="How many fiels are needed in the new table?"; $form.="<br><input type=\"text\" name=\"fields\"; $form.="<input type=\"submit\" values=\"Submit\">; echo ($form); } else if ( !$db ){ $form ="<form action=\"$PHP_SELF\" method=\"post\">"; $form.="Database: <input type=\"text\" name=\"db\"><br>"; $form.="Table Name: <input type=\"text\" name=\"table\"><br>"; for ($i = 0; $i <$fields; $i++){ $form.="Calumn Name:<input type=\"text\" name=\"name[$i]\">"; $form.="Type: <select name=\"type[$i]\">"; $form.="<option value=\"char\">char</option>"; $form.="<option value=\"int\">int</option>"; #...plus options for all other possible data types... $form.=</select> "; $form.=Size:<input type=\"text\" name\"size[$i]\">"; } $form.="<input type=\"submit\" value=\"Submit\">"; $form.="</form>"; echo($form); } else { #make the connection to the mysql $conn = @mysql_connect("localhost", "mike", "bingo") or die("Err:Conn"); #select the specified database $rs = @mysql_select_db($db, $conn) or die("Err:Db"); #create the query $sql = "create table $table ("; for ( $i=0; $i<count($name); $i++){ #field name & date type $sql.="$name[$i] $type[$i]"; #allow size specification for char and varchar types if(( $type[$i] != "" ){ $sql.="($size[$i])";} } # if this is not the final field add a comma if (($i+1) != count($name) ){ $sql.=",";} } $sql .= ")"; #display the SQL query echo("SQL COMMAND: $sql <hr>"); #execute the query - attempt to create the table $result = mysql_query($sql,$conn) or die("Err:Query"); #confirm if successful if ($result) { echo ("RESULT: table \"$table\" has been created"); } ?> </body></html> ########################################### # Inserting table data <html><head><title>Add record to my_database/my_table
    ID: First Name: Last Name:
    ########################################### # Altering tables