Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming PHP on the Server

Similar presentations


Presentation on theme: "Programming PHP on the Server"— Presentation transcript:

1 Programming PHP on the Server
Just a Little PHP Programming PHP on the Server

2 Common Programming Language Features
Comments Data Types Variable Declarations Expressions Flow of Control Statements Functions and Subroutines Macros and Preprocessor Commands I/O Statements Libraries External Tools (Compiler, debugger etc)

3 PHP like JavaScript is Embedded in Web Pages
<html> <body> <!- - Regular HTML -- > <?php //Your PHP goes here ?> <!- - More HTML - -> </html> The difference is that a PHP file is executed by the Server BEFORE being sent to the client. Just like CGI.

4 Comments // This is a single line comment /*
This is a multiline comment just like C */ # works as a comment, just like the bash shell

5 Data Types PHP is a weakly typed language.
Any variable can be any data type The available data types are: boolean number (integer and float) string array object

6 Variable Names To declare a scalar variable just use it.
Variable names begin with a $, ie: $x=7; echo $counter; Assignment - all variables preceded by $ whether on the left or the right $x=$myValue*2;

7 Using Quotes $x=‘The contents $var of this string are literally’;
$y=“But $var is the value of the variable”; $z=`uptime`; #Run as a shell command, stored in $z $a=“Quoting in \$doubleQuotes \n<br>”;k Quotes behave just like they do in the bash shell. $Values inside double quotes are evaluated A $ is taken literally inside single quotes Backquotes are evaluated as bash shell command. The ability to link php code to the shell is one of the most powerful features of php.

8 Constants Numeric: E x2A String: “Hello” ‘Nice Day’ Bob define(“MYCONSTANT”, 42); echo MYCONSTANT If a constant is not defined it stands for itself, ie: Bob. Otherwise it stands for its value. Constants should be ALLCAPS and do not use a $ before the name

9 Creating an Array $list[0] = 17; //This creates an array
$list = array(1,2,3 4,5); //creates an indexed array $list = array(“Smith” => “Carpenter, “Jones”=> “Technician”, “Rajiv” => “Manager”); //Associative array $n=sizeof($list);

10 Debugging with Arrays print_r($myArray); //or var_dump($variable)
This will dump a string representation of an item to the output page. Array ( [0] => hello [1] => bye )

11 Operators Arithmetic: Regular C style operators = * / % += -= *= /= Relational: == != <> > < >= <= Note: “4” == 4 is True String: “a” . $b $a.=$b; Logical: && || !

12 Web Page Output echo “The size of my array is: “ . $n;
print “Hello World: “ . $n; printf “There are %4d items in my array, %s\n”, $n, $name; printf uses the same format codes that C uses: %d (integer) %f (float) %x (hex) %s (string) (There is one new format code: %b - binary)

13 if/then/else if ($price <10 || $price>20) {
printf “%10.2f is a reasonable price<br>”, $price; $total+=$price; } else echo “Try again!”;

14 switch switch($choice) { case 1: case ‘beer’: doSomething(); ...
break; case ‘prezels: doSomethingElse(); ... default: echo “Unknown option”; }

15 Simple for loops for($i=1;$i<10;$i++) {
$sum+=$i; echo “Running total is: “ + $sum + “<br>”; } echo “Final total is: “ $sum;

16 Looping Through Associative Arrays
foreach( $array as $key => $value) { echo “Key: “ . $key echo “Value: “ . $value; } Note: Associative Arrays and Indexed Arrays are the same thing. The key values for an indexed array are: 0, 1,

17 Functions in PHP function myFunction($arg1, $arg2, $arg3) {
//Do some calculation ie: $result= ($arg1 + $arg2) % $arg3; return $result; }

18 Including a library of functions
Use any of: include (“myLibraryFile.php”); require(“myLibrary.php”); require_once(“myLibrary.php”);

19 Debugging Php In the same directory as your php program, include the file php.ini: display_errors=on A missing quote may result in a blank web page. Test your program for syntax error on the command line where it will show up: $bash 3.2: php -l yourProg.php

20 Debugging Continued In every PHP program include the following as the
very first commands: <?php ini_set(‘display_errors’,1); error_reporting(E_ALL); ... ?> Strategies: Always comment your code FIRST Comment out blocks of code to isolate the error Narrow down syntax errors to a single line. Split complex lines into smaller stages Use echo and printf statements liberally

21 Debugging in the bash shell
php -l yourProg.php #Shows syntax errors (not very good) php -a Interactive php REPL environment (Read Eval Print Loop)

22 Debugging with NetBeans
Create a new PHP project Set up a default configuration similar to the above Define name/value pairs as arguments for testing your php code

23 Then create a simple PHP Program
PHP will colorize the code and show syntax errors – doing a much better job than php -l.

24 Important PHP Variables
Purpose $_GET, $_POST, $_COOKIE $_REQUEST Data sent between client and server. $_REQUEST includes all 3 $REMOTE_ADDR IP of the client $HTTP_REFERER Previous Web Page $REQUEST_TIME When page was requested (EPOCH time) $HTTP_USER_AGENT Browser Info $_SERVER Array of Server related values

25 SQL Functions Some PHP Functions EXPLANATION date(‘r’)
The current date as a string time() current time die(message) print out a message and quit include(‘fileName’) require_once(‘fileName’); include an external PHP file – allows shared code and libraries header(‘attribute: value’) adds a header to the response phpinfo() Show php install configuration

26 Since PHP is based on and written in C…..
The “Little Functions” in PHP basename(path,[suffix]) Extracts file name from path. If suffix specified, removes it. chdir(dirName) Changes current directory chmod(path,octalMode) Changes permissions on file chgrp(filename,group) Change group ownership of a file to another group you belong to chown(filename,user) Change file ownership given file name and user name or number. Only available if php is running as root. Not advisable!!! dirname(path) Returns path w/o the file name – directories only. getcwd() Returns current directory link(oldName, newLinkName) Creates a hard link mkdir(dirNam,octMode) Create a directory realpath(filename) Resolves and returns full canonical path to a file rename(oldName, new) Renames a file moves to a new directory. Same as mv in shell

27 Since PHP is based on and written in C…..
More “Little Functions” in PHP rmdir(dirName) Deletes a directory. symlink(old,new) Creates a symbolic link unlink Removes a file entry from a directory xattr_get(file,attrName) xattr_list(file) xattr_set(file,attrName, attrValue) Retrieves an extended attribute from a file Lists all extended file attribute Sets an extended attribute. Miscellaneous related functions copy(file,newfile) Makes a copy of a file opendir(dirName) Returns a resource reference to a directory readdir(dirResource) Reads the next directory entry rewinddir(dirResource) Resets directory reference to beginning stat(filename) Returns an associative array of file properties - ino ftruncate(fileRes,size) Creates or resizes a file

28 Since PHP is based on and written in C…..
File functions in PHP fopen(filename,mode) Same as fopen in C. Returns a file resource handle fgets(fileRes [,length]) Reads a line from a file fscanf(fileRes,fmt,args) Same as fscanf in C. fread(fileRes,length) Raw binary read from a file file(fileName) Returns entire file as an array, one entry per line. file_get_contents( fileName) Returns entire file as a single string. Handles open and close so you don’t have to fgetcsv(fileRes) Reads a line formatted as CSV. Returns an array of items file_exists(fileName) is_readable(fileName) is_writeable(fileName) is_executable(fileName) is_file(fileName) is_dir(filename) Test file properties Fclose(fileRes) ftruncate(fileRes,size) Creates or resizes a file

29 Since PHP is based on and written in C…..
File output functions in PHP fputs(fileRes,string) Output a string to a file fprintf(fileRes,fmt,arg) Same as fprintf in C fwrite(fileRes,string[,len) Write string to a file fread(fileRes [,length]) Raw binary read from a file fputcsv(fileRes,array) Outputs an array as a line of csv text file_put_contents( fileName, string) Outputs a string. The entire file will consist of this string sprintf(format,vars) Like output to a file but returns a formatted string.

30 Since PHP is based on and written in C…..
String Functions in PHP == >= <= != String comparison uses operators strcmp(str1,str2) strncmp(str1,str2,n) strcasecmp(str1,str2) strncasecmp(str1,str2,n) Same as in C. Returns 1, 0 or -1 explode(delim,string) Returns an array. Similar to split in JavaScript implode(delim,string) Returns a string. Each array element is separated by delimiter strlen(string) Returns length of string strpos(string,searchStr) Returns position of searchStr in string. -1 if not found substr(string,start[,n]) Returns a substring. Zero based indexing trim(string) Returns a new string with whitespace removed from both ends. See all ltrim, rtrim preg_match(pattern,str, $matches) Worth a whole lecture. Performs a regular expression pattern match on a string and returns an array of items that match. preg_match(‘/[a-zA-Z/’, string, $matches) - $matches becomes an array of words found in string.

31 3 Ways to Run PHP on the Web
Mix PHP and HTML in a web page with an extension of PHP. Attach the php file to the action property of a form. When the submit button is pressed the name/value pairs in the form are passed via the query string. PHP then pick these up in the superglobal associated array $_REQUEST. If you have a field named username, $_REQUEST[‘username’] will hold its value. Use JQuery’s $.ajax() function in JavaScript. When the function is executed your php code is passed information and the output of the php code is passed back to your program without the need to refresh the whole page or go to a new one.

32 JavaScript: $.ajax $.ajax( { datatype: ‘json’, //could also be text type: ‘get’, url: ‘doSomePHP.php’ , //name of php file success: function(data,status) { //function receives data from the server console.log(“We got a response!!!”,data); //process data …, display in current web page } error: function(errorObj,errorMsg,thrownMsg) { //Failure – diagnose what went wrong console.log(“Ooops – we had a problem”); //set a breakpoint here & figure out what went wrong } }); Pass a JSON object to the $.ajax() function. Entries in the object are: datatype, type, url (php file on server), success (function to run on success) and error

33 SQL Functions MYSQL FUNCTION CALL EXPLANATION mysql_error()
Report on last error mysql_connect(host,user, pass) connects to database; returns a connection to the database mysql_selectdb(dbName) use specified schema $result=mysql_query(stmt) runs stmt against the database returns 0 to n rows for SELECT returns number of rows affected for INSERT, UPDATE or DELETE $row=mysql_fetch_array($result) creates an associative array using column names as keys mysql_close($con) closes the database connection

34 THE END


Download ppt "Programming PHP on the Server"

Similar presentations


Ads by Google