PHP Basics (See PHP on line manual at: PHP - Overview Scripting vs Programming Code Examples – PHP; Perl; JSP PHP Strengths.

Slides:



Advertisements
Similar presentations
PHP I.
Advertisements

Introducing JavaScript
Introduction to PHP MIS 3501, Fall 2014 Jeremy Shafer
Lab Homework #3 PHP Overview (based on by Lisa Wise)
IST 221 Internet Concepts and Applications Introduction to PHP.
Guide To UNIX Using Linux Third Edition
Introduction to C Programming
PHP Server-side Programming. PHP  PHP stands for PHP: Hypertext Preprocessor  PHP is interpreted  PHP code is embedded into HTML code  interpreter.
1 CS428 Web Engineering Lecture 18 Introduction (PHP - I)
DAT602 Database Application Development Lecture 15 Java Server Pages Part 1.
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.
August Chapter 1 - Essential PHP spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
1 Introduction to PHP. 2 What is this “PHP” thing? Official description: “PHP, which stands for "PHP: Hypertext Preprocessor" is a widely-used Open Source.
Copyright © Curt Hill PhP History and Introduction.
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)PHP Recap.
PHP H ypertext P re-processor. Unit 6 - PHP - Hello World! - Data types - Control structures - Operators.
AIT 616 Fall 2002 PHP. AIT 616 Fall 2002 PHP  Special scripting language used to dynamically generate web documents  Open source – Free!!!  Performs.
Introduction to Python
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.
Nael Alian Introduction to PHP
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
IST 210: PHP BASICS IST 210: Organization of Data IST210 1.
Modified from Moseley ’s sli desWeb Applications Development. Lecture 5 Slide 1 Lecture 5: Introduction to PHP Instructor: Dr. Mohammad Anwar Hossain.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
DHTML AND JAVASCRIPT Genetic Computer School LESSON 5 INTRODUCTION JAVASCRIPT G H E F.
20-753: Fundamentals of Web Programming 1 Lecture 12: Javascript I Fundamentals of Web Programming Lecture 12: Introduction to Javascript.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
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.
Open Source Software Unit – 3 Presented By Mr. R.Aravindhan.
PHP - Basic Language Constructs CSCI 297 Scripting Languages - Day Two.
Class 2Intro to Databases Goals of this class Include & Require in PHP Generating Random Numbers in PHP Arrays – Numerically Indexed and Associative Program.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
PHP. What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server.
PHP PHP: Hypertext Preprocesor Personal Home Page Tools.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
Intro to PHP IST2101. Review: HTML & Tags 2IST210.
Introduction to PHP Advanced Database System Lab no.1.
What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Introduction to Java Java Translation Program Structure
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
David Lawrence 7/8/091Intro. to PHP -- David Lawrence.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Just a Little PHP Programming PHP on the Server. Common Programming Language Features Comments Data Types Variable Declarations Expressions Flow of Control.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP Basics.
8 th Semester, Batch 2009 Department Of Computer Science SSUET.
Basic Scripting & Variables Yasar Hussain Malik - NISTE.
1 PHP Intro PHP Introduction After this lecture, you should be able to: Know the fundamental concepts of Web Scripting Languages in general, PHP in particular.
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,
Unit – 3 Control structures. Condition Statements 1.If.…..else :- Has someone ever told you, "if you work hard, then you will succeed"? And what happens.
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.
IST 210: PHP Basics IST 210: Organization of Data IST2101.
By bscshelp.com 1.  It is a group assignment.  Complete Website design Using Html and Css.  Due date: 10 th December, 2014 (Hard Deadline) 2.
PHP using MySQL Database for Web Development (part II)
Web Database Programming Using PHP
Web Database Programming Using PHP
DBW - PHP DBW2017.
Server-Side Application and Data Management IT IS 3105 (Spring 2010)
PHP Introduction.
Intro to PHP & Variables
PHP.
Web DB Programming: PHP
HYPERTEXT PREPROCESSOR BY : UMA KAKKAR
Intro to PHP.
PHP an introduction.
Presentation transcript:

PHP Basics (See PHP on line manual at: PHP - Overview Scripting vs Programming Code Examples – PHP; Perl; JSP PHP Strengths Basics of PHP Included files Variables & Scope Output Variable types ; Boolean; Strings String Functions & Parsers Screening User Input/Output Maths functions Control and flow

PHP PHP is a scripting language that allows you to create dynamic web pages You can embed php scripting within normal html coding PHP was designed primarily for the web PHP includes a comprehensive set of database access functions

Scripting vs Programming A script is interpreted line by line every time it is run A true programming language is compiled from its human readable form(source code) into a machine readable form (binary code) which is delivered to the user as a program. Variables in scripting languages are typeless whereas variables in programs need to be declared as a particular type and have memory allocated to them. PHP requires programming skills PHP web sites should be developed within a software engineering framework

PHP Competitors Perl Microsoft Active Server Pages (ASP) Java Server Pages (JSP) Cold Fusion It would be good to work together to make equivalent code libraries across scripting languages –Eg. Web Services.

PHP Code Examples <?php $name = "Lisa"; $date = date ("d-m-Y", time()); ?> Hello World Hello World It's and all is well. <?php echo " Hello ".$name.". \n"; ?>

Perl Coding Example #!/usr/local/bin/perl print "Content-type: text/html \n\n"; $date = `/usr/local/bin/date`; $name = "Lisa"; print " "; print " Hello World " print " \n "; print " Hello World "; print " It\'s $date and all is well "; print " Hello $name "; print " ";

JSP Coding Example page language="java" contentType="text/html" %> Hello World Hello World It's and all is well. Hello.

PHP Strengths High performance - see benchmarks at Interfaces to different database systems Low cost SourceForge has PHPTriad (Apache, PHP and MySQL) for WindowsPHPTriad Ease of learning and use Portability – –available on multiple platforms, Unix and Windows

Basics of PHP PHP files end with.php other places use.php3.phtml.php4 as well PHP code is contained within tags Canonical: or Short-open: HTML script tags: Recommend canonical tags so as not to confuse with xml tags

Include files Files can be inserted into other files using include or require These files can have any name and be anywhere on the file system so long as the file trying to include them has appropriate rights CAVEAT: if these files are not called blah.php, and they are fetched independently by a browser, they will be rendered in plaintext rather than passed to the PHP interpreter - not good if they contain username/passwords and the like.

Include() eg. Note ‘var scope’ vars.php test.php

Output Most things in PHP execute silently You need to explicitly ask PHP to generate output Echo is not a function and cannot return a value – echo " This is a paragraph. "; Print is a function and returns a value –1 = success, 0 = failure – print (" This is a paragraph too. "); Use echo or print statements and View Source for debugging your code

Variables All variables begin with $ and can contain letters, digits and underscore (and no digit directly after the $) The value of a variable is the value of its most recent assignment Don’t need to declare variables Variables have no intrinsic type other than the type of their current value Can have variable variables $$variable –Like a pointer variable type; best to avoid PHP Manual-variables

Variables Scope Scope refers to where within a script or program a variable has meaning or a value Mostly script variables are available to you anywhere within your script. Note that variables inside functions are local to that function and a function cannot access script variables outside the function even if they are in the same file. The modifiers global and static allow function variables to be accessed outside the function or to hold their value between function calls respectively

Variable types Strings Numbers –Integers –doubles Booleans – TRUE / FALSE Arrays Objects

Variable Examples Integer $a = 1234; # decimal number $a = -123; # a negative number $a = 0123; # octal number (equivalent to 83 decimal) $a = 0x1A; # hexadecimal number (equivalent to 26 decimal) Floating Point Numbers $a = 1.234; $a = 1.2e3; $a = 7E-10; Boolean $foo = True; // assign the value TRUE to $foo // == is an operator which returns a boolean if ($action == "show_version") { echo "The version is 1.23"; } // this is not necessary: if ($show_separators == TRUE) { echo " \n"; } // because you can simply type this: if ($show_separators) { echo " \n"; }

Variable Examples cont. Strings (single or double quoted) echo 'this is a simple string'; echo 'You can also have embedded newlines in strings, like this way.'; echo 'Arnold once said: "I\'ll be back"'; // output:... "I'll be back" echo 'Are you sure you want to delete C:\*.*?'; // output:... delete C:\*.*? Arrays $error_descriptions[E_ERROR] = "A fatal error has occurred"; $error_descriptions[E_WARNING] = "PHP issued a warning"; $error_descriptions[E_NOTICE] = "This is just an informal notice"; the last example is in fact the same as writing: $error_descriptions[1] = "A fatal error has occurred"; $error_descriptions[2] = "PHP issued a warning"; $error_descriptions[8] = "This is just an informal notice"; (The first method is useful if E_ERROR is defined as a constant etc).

Constants and Globals To define a constant: define(“PI”, ); $area = PI*$radius*$radius ; Globals: –Defined outside any function; eg form variables … global $var1, $var2 … …function xyz() { $localvarX = $var1 …}

Boolean Unlike PHP3, PHP4 has a boolean type –if (TRUE) print ("This will always print"); A number is FALSE if it exactly equals 0 otherwise it is TRUE A string is FALSE if it is empty (has zero characters) or is "0" otherwise it is TRUE An array or object is FALSE if it contains no other values and is TRUE otherwise

Arrays in PHP An array in PHP is actually an ordered map which maps values to keys. An array can be thought of in many ways. Each of the concepts below can be implemented in a PHP array, so you can choose which ever of these ideas that you understand to conceptualise an array. linearly indexed array list (vector) hashtable (which is an implementation of a map) dictionary collection stack (LIFO) queue (FIFO) can easily simulate trees and linked lists with arrays of arrays

Eg: Numerically-indexed arrays (Vector array) Say that we have a list of marks out of 100 in a subject 95, 93, 56, 70, 65, 98 – array value – array value – array value – array value – array value – array value $marks = array (95, 93, 56, 70, 65, 98); generates a numerically- indexed array $marks[0] = 95 ; $marks[1] = 93 ; $marks[2] = 56 ; $marks[3] = 70 ; $marks[4] = 65 ; $marks[5] = 98 ;

Example: Numerically-indexed arrays (cont) The following code also generates a numerically- indexed array, allocating the next index after the highest current index to the element. – $marks[] = 95; – $marks[] = 93; marks[0] is 95 and marks[1] is 93. Note that array indexes start at 0 by default. You can skip indices by allocating a specific index to a value - – $marks[5] = 56; – $marks[] = 70; will allocate 70 to $marks[6]. –marks[5] is 56 and marks[6] is 70.

Associative arrays Say we have a list of marks out of 100 in a subject and we want to know who got what mark: – Adrian - 95, Matty - 93, Lance - 56, Stephen - 70, Craig - 65, Andy - 98 $marks = array ("Adrian"=>93, "Lance"=>56, "Stephen"=>70, "Craig"=>65, "Andy"=>98); maps a value to a key name is the key (Adrian,Lance etc) mark is the value (93, 56 etc)

List an associative array list() in conjunction with each() assigns a key / value pair into the variables $key and $variable. The following code prints each key / value pair into a table. Note that $value might itself be an array. reset($marks); // go to the beginning of the array echo " “; //note escape sequences while (list($key, $value) = each($marks)) { echo " $key $value \n"; } echo " ";

List an associative array (cont) each() actually returns an array for each array item which includes the key and value as well as the index 0 mapped to the key and the index 1 mapped to the value. Reset() puts the index pointer back to 0. Hence if you are more comfortable with numeric indexes, you can do the following: reset($marks); while ($row = each($marks)) { echo "Mark for $row[0] is $row[1] "; }

Array functions Foreach is another way to iterate through an array. foreach ($marks as $index => $mark ) { echo “ $index => $mark”;} Index Pointer manipulation Current() $mark = current($marks); Next() $nextmark = next($marks); Prev() $prevmark = prev($marks); Sorting –Sort() ; asort(); rsort() etc

Strings Dot operator for concatenation (joining) singly quoted read in and store literally double quoted – allow for variable substitution certain sequences beginning with \ are replaced with special characters + \n \t \r \$ \" \\ Variable names are replaced with string representations of their values Variable interpolation No limit on string length

String Functions boolean strcmp ($str1, $str2) boolean strcasecmp ($str1, $str2) boolean strstr ($str1, $str2) boolean stristr ($str1, $str2) int strlen($str) string substr ($str, $start_pos, $len)

String functions (cont) string chop ($str) string ltrim ($str) string trim ($str) string str_replace ($old_txt, $new_txt, $text) string substr_replace ($old_txt, $new_txt, $text) strtolower($str) strtoupper($str) ucfirst($str) ucwords($str) these last two don’t correct inappropriate upper case to lower case

Formatting User Input/Output addslashes($str) stripslashes($str) magic_quotes_gpc($str) not magic_quotes_runtime($query) escapeshellcmd($str) strip_tags($str) htmlspecialchars($str) htmlentities($str) nl2br($str) Urlencode() Rawurlencode() etc

Maths functions + - / * % = -= *= = is set to (assignment) = = is equivalent to eg $a == $b Equal TRUE if $a is equal to $b. = = = is identical to eg $a === $b Identical TRUE if $a is equal to $b, and they are of the same type. (PHP 4 only) $low_int = floor ($double) $high_int = ceil ($double) $nearest_int = round ($double) –(nearest even number if exactly.5) $positive = abs ($number) $min = min ($n1, $n2 …, $nn) $max = max ($n1, $n2 …, $nn)

Control and flow if (expr1) { } elseif (expr2) { } else { } while (cond) { } do { } while (cond) switch ($var) case a { } case b { } for ($i = 0; $i < expr; $i ++) { } foreach (array_expr as $value) { } foreach (array_expr as $key=>$value) { } break [1] continue

If.. Then.. else *if ($a > $b) print "a is bigger than b"; *if ($a > $b) { print "a is bigger than b"; $b = $a; } *if ($a > $b) { print "a is bigger than b"; } elseif ($a == $b) { print "a is equal to b"; } else { print "a is smaller than b"; } *echo "You have $i ". ($i==1 ? "message" : "messages"). " in your mailbox.\n";

While /* example 1 */ $i = 1; while ($i <= 10) { print $i++; /* the printed value would be $i before the increment (post-increment) */ } /* example 2 - alternative notation to using the braces - : and endwhile*/ $i = 1; while ($i <= 10): print $i; $i++; endwhile;

For loops /* example 1 similar to C syntax */ for ($i = 1; $i <= 10; $i++) { print $i; } /* example 2 */ for ($i = 1;;$i++) { if ($i > 10) { break; } print $i; } /* example 3 */ $i = 1; for (;;) { if ($i > 10) { break; } print $i; $i++; } /* example 4 */ for ($i = 1; $i <= 10; print $i, $i++);

Foreach An easy way to iterate over arrays. There are two syntaxes; the second is a minor but useful extension of the first: foreach(array_expression as $value) statement foreach(array_expression as $key => $value) statement The following are functionally identical: //example 1 // reset ($arr); while (list(, $value) = each ($arr)) { echo "Value: $value \n"; } //example 2 // foreach ($arr as $value) { echo "Value: $value \n"; }

Foreach cont. /* foreach example 1: value only */ $a = array (1, 2, 3, 17); foreach ($a as $v) { print "Current value of \$a: $v.\n"; } /* foreach example 2: value (with key printed for illustration) */ $a = array (1, 2, 3, 17); $i = 0; /* for illustrative purposes only */ foreach($a as $v) { print "\$a[$i] => $v.\n"; $i++; } /* foreach example 3: key and value */ $a = array ( "one" => 1, "two" => 2, "three" => 3, "seventeen" => 17 ); foreach($a as $k => $v) { print "\$a[$k] => $v.\n"; }

Break & Continue -break ends execution of the current for, foreach while, do..while or switch structure. $arr = array ('one', 'two', 'three', 'four', 'stop', 'five'); while (list ($key, $val) = each ($arr)) { if ($val == 'stop') { break; /* You could also write 'break 1;' here. */ } echo "$val \n"; } /* note list() is a multiple assignment function; the key and value returned by each() are assigned to $key and $value. $key is not used in this example. - 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.

Switch if ($i == 0) { print "i equals 0"; } if ($i == 1) { print "i equals 1"; } if ($i == 2) { print "i equals 2"; } /* this is equivalent */ switch ($i) { case 0: print "i equals 0"; break; case 1: print "i equals 1"; break; case 2: print "i equals 2"; break; }

require() and include() require() includes and evaluates a specific file. require() and include() are identical in every way except how they handle failure. include() produces a Warning while require() results in a Fatal Error. <?php require 'prepend.php'; require $somefile; require ('somefile.txt'); ?> require_once() or include_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.

Running an Apache PHP web server on SNG you have an SNG account login to your account using telnet your home directory on sng is something like: /cc/staff1/l/lzwise/ (you can use pwd to find out the exact path to your directory) think of a number between 5000 and which no one else has thought of (to use as a port number) run the command makeserver and set the scratch directory run the command startserver – you may see this error: kill: : no such process - ignore it :- ) stop the server with the command stopserver

/usr/local/bin/makeserver.readme It creates serveral files/directories Files: (root = /scratch/username) – $root/apache/httpd.conf – $root/apache/stopserver – $root/apache/startserver Directories – $root/apache/logs – $root/apache/cgi-bin – $root/apache/htdocs All of the directories start empty. The access and error logs will be created in the logs directories once the server is running. Content should be added to the htdocs directory.

Examples of PHP Examples of PHP at zend.com - code galleryExamples of PHP at zend.com - code gallery – see code libraryhttp:// phttp:// p