Programming PHP on the Server

Slides:



Advertisements
Similar presentations
UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 3 PHP (2) : Functions, User Defined Functions & Environment Variables.
Advertisements

Java Script Session1 INTRODUCTION.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Web Database Programming Using PHP.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
Guide To UNIX Using Linux Third Edition
PHP Server-side Programming. PHP  PHP stands for PHP: Hypertext Preprocessor  PHP is interpreted  PHP code is embedded into HTML code  interpreter.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
PHP: Introduction By Trevor Adams.
Introduction to PHP. PHP PHP is the Hypertext Pre-processor –Script language –Embedded into HTML –Runs as Apache module –Can use DB (MySQL, Oracle, Microsoft.
JSP Standard Tag Library
Introduction to PHP and Server Side Technology. Slide 2 PHP History Created in 1995 PHP 5.0 is the current version It’s been around since 2004.
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
NMED 3850 A Advanced Online Design January 26, 2010 V. Mahadevan.
School of Computing and Information Systems CS 371 Web Application Programming PHP - Basics Serving up web pages.
Week 9 PHP Cookies and Session Introduction to JavaScript.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell scripts do not have to be converted into machine language.
Introduction to PHP A user navigates in her browser to a page that ends with a.php extension The request is sent to a web server, which directs the request.
Website Development with PHP and MySQL Saving Data.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
PHP PHP: Hypertext Preprocesor Personal Home Page Tools.
Just a Little PHP Programming PHP on the Server. Common Programming Language Features Comments Data Types Variable Declarations Expressions Flow of Control.
XP Tutorial 10New Perspectives on HTML and XHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Just a Little PHP Programming PHP on the Server. Common Programming Language Features Comments Data Types Variable Declarations Expressions Flow of Control.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Web Database Programming Using PHP.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Introduction to Javascript. What is javascript?  The most popular web scripting language in the world  Used to produce rich thin client web applications.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
CGS 3066: Web Programming and Design Spring 2016 PHP.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
A pache M ySQL P hp Robert Mudge Reference:
PHP using MySQL Database for Web Development (part II)
Web Database Programming Using PHP
CGS 3066: Web Programming and Design Spring 2017
CX Introduction to Web Programming
Introduction to Dynamic Web Programming
CS 371 Web Application Programming
Loops BIS1523 – Lecture 10.
Web Database Programming Using PHP
DBW - PHP DBW2017.
PHP Functions Besides the built-in PHP functions, we can create our own functions. A function is a block of statements that can be used repeatedly in.
Shell Scripting March 1st, 2004 Class Meeting 7.
Chapter 19 PHP Part III Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
* Lecture # 7 Instructor: Rida Noor Department of Computer Science
BASIC PHP and MYSQL Edward S. Flores.
Server-Side Application and Data Management IT IS 3105 (Spring 2010)
Intro to PHP & Variables
MATLAB: Structures and File I/O
Web Systems Development (CSC-215)
WEB PROGRAMMING JavaScript.
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
Web DB Programming: PHP
HYPERTEXT PREPROCESSOR BY : UMA KAKKAR
Lecture 5: Functions and Parameters
Web Programming Language
PHP an introduction.
PHP-II.
SEEM 4540 Tutorial 4 Basic PHP based on w3Schools
Presentation transcript:

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

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)

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.

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

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

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;

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.

Constants Numeric: 4.2 17.5 1.6E+7 21 0x2A 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

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);

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 )

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

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)

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

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

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

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, 2 .....

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

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

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

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

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)

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

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

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

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

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

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

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

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.

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.

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.

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

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

THE END