1 PHP Guest Lecture by Ari Gilder Parts of this lecture adapted from the PHP Manual at

Slides:



Advertisements
Similar presentations
PHP I.
Advertisements

UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 3 PHP (2) : Functions, User Defined Functions & Environment Variables.
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
PHP (2) – Functions, Arrays, Databases, and sessions.
PHP Intro/Overview Squirrel Book pages Server-side Scripting Everything you need to know in one slide 1.Web server (with PHP “plug-in”) gets a.
 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.
Sys Prog & Scripting - HW Univ1 Systems Programming & Scripting Lecture 15: PHP Introduction.
COMP An Introduction to Computer Programming : University of the West Indies COMP6015 An Introduction to Computer Programming Lecture 03.
PHP Overview CS PHP PHP = PHP: Hypertext Preprocessor Server-side scripting language that may be embedded into HTML One goal is to get PHP files.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
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.
PHP == ‘ Hypertext Preprocessor ’ Open-source, server-side scripting language Used to generate dynamic web-pages PHP scripts reside between reserved PHP.
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.
AIT 616 Fall 2002 PHP. AIT 616 Fall 2002 PHP  Special scripting language used to dynamically generate web documents  Open source – Free!!!  Performs.
INTERNET APPLICATION DEVELOPMENT For More visit:
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.
PHP By Jonathan Foss.
Nael Alian Introduction to PHP
Week 9 PHP Cookies and Session Introduction to JavaScript.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
OOP with PHP Roman Bednarik
Chapter 8 Cookies And Security JavaScript, Third Edition.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
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.
Introduction to CS520/CS596_026 Lecture Two Gordon Tian Fall 2015.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
CSC 2720 Building Web Applications Server-side Scripting with PHP.
PHP Teresa Worner. What is it? PHP: Hypertext Preprocessor server-side scripting language open source cross-platform compatible with almost all servers.php.php3.phtml.
CS320 Web and Internet Programming Introduction to PHP Chengyu Sun California State University, Los Angeles.
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.
Just a Little PHP Programming PHP on the Server. Common Programming Language Features Comments Data Types Variable Declarations Expressions Flow of Control.
Introduction to PHP Advanced Database System Lab no.1.
Fall 2004CSI University of Ottawa Introduction to PHP Basic principles and syntax.
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.
David Lawrence 7/8/091Intro. to PHP -- David Lawrence.
הרצאה 4. עיבוד של דף אינטרנט דינמי מתוך Murach’s PHP and MySQL by Joel Murach and Ray Harris.  דף אינטרנט דינמי משתנה עפ " י הרצת קוד על השרת, יכול להשתנות.
Martin Kruliš by Martin Kruliš (v1.1)1.
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.
 Before you continue you should have a basic understanding of the following:  HTML  CSS  JavaScript.
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.
Creating FunctionstMyn1 Creating Functions Function can be divided into two groups: –Internal (built in) functions –User-defined functions.
NMD202 Web Scripting Week2. Web site
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,
PHP-Basic By- Tanvi Raval. Pre-requisites Before you continue you should have a basic understanding of the following: 1. HTML 2. JavaScript.
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.
Radoslav Georgiev Telerik Corporation
PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used, free, and efficient alternative.
PHP using MySQL Database for Web Development (part II)
CGS 3066: Web Programming and Design Spring 2017
Introduction to Dynamic Web Programming
CS 371 Web Application Programming
DBW - PHP DBW2017.
PHP Introduction.
PHP.
HYPERTEXT PREPROCESSOR BY : UMA KAKKAR
Lecture 5: Functions and Parameters
Intro to PHP.
Tutorial 6 PHP & MySQL Li Xu
PHP an introduction.
PHP By Prof. B.A.Khivsara Note: The material to prepare this presentation has been taken from internet and are generated only for students reference and.
Presentation transcript:

1 PHP Guest Lecture by Ari Gilder Parts of this lecture adapted from the PHP Manual at

2 What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a scripting language Often used server side There are extensions that allow client side as well Especially suitable for web development Can be embedded into HTML, like JSP Developed by Zend Technologies Most current versions are: 5.0.2, 4.3.9

3 What can PHP do? PHP has a tremendous number of built-in libraries, as well as separately downloadable ones APIs for almost any kind of database Image manipulation functions (using GD library) Encryption functions Regular expressions PDF creation XML parsing Even Java integration! Much, much more…

4 Advantages/Disadvantages PHP is an interpreted language – no compilation needed PHP is intended to serve large audiences, so the Zend Engine is fairly robust (can be enhanced) PHP is easy to learn, and very powerful It’s free! However: PHP4’s support for OOP is fledgling It’s just a scripting language – not often used for actual desktop applications

5 Using PHP PHP is most often found on UNIX environments There are Windows (and other OS) versions as well Apache and PHP work wonders There are some pre-compiled packages of Apache, PHP and MySQL available Primarily designed for the Web – mostly any modern browser can recognize PHP Can also run from command line

6 The hardest program ever. <?php echo “Hello World”; //well, duh print “I can do this too.”; //look Ma, no parenthesis! ?>

7 Basic Syntax There are a few ways of inserting PHP into HTML: This is the recommended way of inserting PHP Works with XML and XHTML compliant documents Looks like a Processing Instruction Most common method, but requires short_tags option to be enabled /* insert PHP code */

8 Comments There are a few acceptable comment styles: /* Using C-style comments */ // Using C++-style comments # Using UNIX-style comments The C++ style is recommended, UNIX style discouraged C++ style comments go to the end of the line, or the end of the current block of PHP code. Hello World

9 Variables and Types PHP variables are usually scalars, like $myVar There are four scalar types: boolean integer string float Two compound types: array object Two special types: resource NULL

10 Variables and Types, II Casting: (string) 50 will evaluate as “50” Typing: settype($myInt, “string”) sets the type of $myInt to a string Identity comparison: If $a=50 and $b=“50”, then $a == $b However, !($a === $b), or, $a !== $b

11 Variable variables A rather useful feature, much like pointers in C $message = “PHP rocks”; $a = $message; //$a == “PHP rocks” $b = “message”; echo $$b;//prints “PHP rocks” $myString = “average”;//can have variable $func = “myString”;//functions too! echo $$func(0, 1); //prints out 0.5

12 Operators PHP has more or less the same set of operators as C or Java Some new ones:. is the concatenation operator === is identity is error suppression (legal before any expression) Won’t suppress parse errors `$command` is the shell execution operator ( `` ) Will run $command at the shell; return value is command output Disabled in PHP Safe Mode Be VERY, VERY CAREFUL with its use!!!

13 Control Structures Same control structures as Java, plus a few more declare(directive) statement Used for setting execution directives for a block of code (i.e. ticks) foreach($arr as $key=>$val) Within the body of the loop, $key and $val are local variables containing the key/value of the current element. Can be used on arrays and objects File inclusion: include() or include_once() require() or require_once() These are language constructs, so they don’t need ()’s

14 Functions Declared using the function keyword, like JavaScript PHP4 supports both variable number of arguments, as well as default argument values PHP4 does not support function overloading function foo($arg_1, &$arg_2, /*..., */ $arg_n) { echo "Example function.\n"; $arg_2 = “new value”; //& passes $arg_2 by ref return $retval; }

15 Functions, II PHP supports two types of conditional functions: $makefoo=true; //no foo() here, yet if ($makefoo) { function foo() { echo “foo() function only accessible once program execution reaches here.\n"; } } function foo() { function bar() { echo "I don't exist until foo() is called.\n"; } } //bar() doesn’t exist yet foo(); //now bar() exists bar();

16 Arrays Arrays declared using the array() function Example: $arr = array(“apples”, “bananas”); You can assign keys to a value $arr = array(“red”=>“apples”, “yellow”=>“bananas”); And you can add arrays by the next highest index: $arr = array(1 => “bananas”, 0 => “apples”); $arr[] = “oranges”; //$arr[2] contains oranges You can delete an element: unset($arr[2]); //this function works on all vars

17 Array operators Let’s say $a and $b are arrays: $a + $b is their union Appends the right array to the left array The left array’s keys are not overwritten if there is a conflict $a == $b checks that they have the same elements $a === $b checks they have the same elements, in the same order, and their keys and values are identical Same with $a != $b, $a <> $b, $a !== $b

18 Built-in array functions Along with its extensive API, PHP has a vast number of functions for operating on arrays Sorting functions: sort(), rsort(), ksort(), krsort(), asort(), arsort(), usort(), uksort(), uasort() in_array($needle, $haystack, true) Checks if $needle is in array $haystack, and makes sure types are equal (third parameter default is false ) count($arr) returns length of the array array_pop(), array_push(), array_rand() array_multisort() Sorts multiple arrays in tandem, or multi-dimensional arrays Weirdest function I know – often works how you want, though

19 Some other useful API functions date($format [, $timestamp]) $format is a string composed from the formatting components listed in the PHP manual If $timestamp is not present, it defaults to time() (the current UNIX timestamp) define(“THE_ANSWER”, 42) is_array(), is_bool(), is_file(), is_int(), etc. phpinfo() Prints out PHP information, compiled libraries Very useful diagnostic tool for checking GET/POST values

20 Some useful String functions implode($glue, $arr) Fuses the elements of $arr with $glue as a separator explode($sep, $str) Opposite of implode – splits a string into an array nl2br($str) Converts newlines in a string to tags strstr($haystack, $needle) Returns substring starting from first occurrence of $needle till the end of $haystack, or false if not found

21 Interacting with HTML PHP can generate an HTML file which the client views Since PHP is server-side, all the PHP code is executed first, and the only output is HTML (or binary...) You can print out variable contents in the HTML: ”> Part of doing that requires actually processing data! How do we get data from an HTML form?

22 Sample HTML Form – login.html User name: Password:

23 Processing script – login.php <?php if(empty($_POST[“user”]) || empty($_POST[“pass”]) { die(“You didn’t enter a user and a password!”); } if(lookup_user($_POST[“user”], $_POST[“pass”])) { echo “Welcome to the administration.”; include “adminfile.php”; } else { die(“Bad user or password error.”); } ?>

24 Superglobals What’s this $_POST[“user”] thing? $_POST is a superglobal array, i.e. it is an array of data passed to the PHP script that is available anywhere in the script. Prior to PHP 4.1.0, it used to be $HTTP_POST_VARS There are other superglobal arrays: $GLOBALS – all variables defined in the global scope $_SERVER – server variables, viewable on phpinfo() $_GET – all form fields or querystrings passed by GET $_COOKIE – all cookie values $_FILES – information about uploaded files $_ENV – environment variables, viewable on phpinfo() $_REQUEST – union of $_GET, $_POST, $_COOKIE (GPC order) $_SESSION – contains session variables

25 Session Tracking As in Java Servlets, sessions can be tracked via hidden HTML forms or by cookies PHP also has its own method of session tracking A unique session ID is generated for every user This ID can be propagated across pages in two ways: Cookies (most common) URL query string Append the predefined constant SID after the ? of a URL URL method is more prone to security vulnerability

26 Session Tracking, II All session data (besides ID) is stored on the server In order to initialize or continue a session, the best way is to explicitly use the session_start() function at the top of your page. Session variables are accessed or set by $_SESSION Example: $_SESSION[“user”] = $_POST[“user”]; Then, on another page, after you call session_start() you can access $_SESSION[“user”] Objects and arrays can be stored in sessions A call to session_destroy() will erase all data from the session

27 Classes and Objects in PHP4 PHP’s evolution seems to be largely defined by its support for OOP In PHP4, there are no modifiers ( public, private, etc) Classes can be defined anywhere But, you can’t break up a class definition (i.e. define a class in one block of PHP and its methods in another block) Single inheritance is supported, but no interfaces No real distinction between static/dynamic methods No destructors

28 Some Object Syntax \n"; } function B() { echo "I am a regular function named B in class A. \n"; echo "I am not a constructor in A. \n"; } } class B extends A { function C() { echo "I am a regular function. \n"; } } // This will call B() as a constructor. $b = new B;//no () required ?>

29 Constructor oddities What will be printed from the previous block of code? The answer: it depends. In PHP3: ‘A constructor is a function of the same name as the class.’ In PHP4: ‘A constructor is a function of the same name as the class it is being defined in.’ PHP5 has an entirely different way of handling constructors Note: neither PHP3 nor PHP4 will automatically call the constructors of the base class (Java does) – unless the child class contains no constructor. It is your responsibility to propagate constructor calls upstream

30 Object fields & methods Fields can be declared at the top of a class definition using the var keyword (i.e. var $internalArray; ) Fields defined with var can only be initialized to constants To access an object field or method: $myObj->myMethod(42); $myObj->myVar = 5; CAUTION: DO NOT DO NOT DO NOT say $myObj->$myVar unless you know what you are doing!!! You can also use the scope resolution operator ( :: ) to access methods/fields “statically” MathStuff::stdDev($array_o_nums);

31 A few other keywords The $this variable (just like in Java) The parent keyword (should only be used when defining a class’ methods) If B extends A, and both contain a method called example, you can have B::example() say parent::example() [which is analogous to A::example() ] The magic functions __sleep() and __wakeup() These are used for preparing an object to be serialized or unserialized (like restoring a database connection) Can be overridden if you want specific functionality

32 Some additional features in PHP5 Different syntax for constructors (but backwards- compatible) – looks for __construct() method Allows destructors with a __destruct() method Allows modifiers – public, private, protected Supports static keyword const (fields) and final (methods & classes) keywords Supports interfaces and abstract classes Exceptions Reflection MUCH MORE!!!

33 Database Connectivity PHP supports nearly any type of database on the market Most common database used with PHP is MySQL Interactions with databases are what make PHP such a powerful language Large stores of persistent data Shopping carts, molecule databases, etc. Actions are executed via SQL queries to the database engine I won’t go into much detail…

34 A Taste of MySQL mysql_connect($dbhost, $dbuser, $dbpass […]) Returns a link id resource $dbhost is most often “localhost” mysql_query($query [, $linkid]) Returns a result id resource $query is specified in SQL syntax Example: SELECT * FROM users WHERE username=‘ari’ mysql_fetch_array($result) Returns an associative array with keys being field names $result is a result id resource

35 Conclusion PHP is a very extensive language, with support for a huge number of APIs for databases, XML, images, etc. The old XML parser in PHP4 is a SAX-like parser PHP5 introduces SimpleXML for a DOM-like structure PHP also does have APIs for actual DOM, XSL, etc. PHP combines a lot of useful features from various languages (C++/Java/Perl) PHP is weakly-typed, but this also allows for more flexible code But beware: it also allows for bad coding habits to develop!

36 The End