php tutorial

48
PHP (Hypertext Preprocessor) -Gursharandeep kaur bajwa (CTIEMT) 100220314317

Upload: sharanbajwa

Post on 14-Nov-2014

1.199 views

Category:

Technology


6 download

DESCRIPTION

PHP Tutorial

TRANSCRIPT

Page 1: Php Tutorial

PHP (Hypertext Preprocessor)

-Gursharandeep kaur bajwa

(CTIEMT)100220314317

Page 2: Php Tutorial

IntroductionIntroduction PHP is stands for ’Hypertext Preprocessor ’ used for making

dynamic web pages and interactive web pages.

PHP is server side scripting language intented to help web developers build dynamic web pages.

PHP scripts are executed on the server.

PHP supports many databases (MySql ,Oracle,PostgreSQL,Generic ODBC etc).

PHP was created by Rasmus Lerdrof in 1995.

PHP originally stood for ”PERSONAL HOME PAGE”

PHP is an Open Source software.

PHP is free to download and use.

Page 3: Php Tutorial

PHP FilesPHP Files PHP files can contain text, HTML Tags and scripts.

PHP files are returned to the browser as plain HTML

PHP files have a file extension of ”.php”.

EXECUTION OF PHP PAGE

Page 4: Php Tutorial

“PHP is an HTML-embedded scripting language. Much of its syntax is

borrowed from C,Java & Perl with a couple of unique PHP-specific

features thrown in .The goal of the language is to allow web developers

to write dynamically generated pages quickly. ”

Page 5: Php Tutorial

Brief History of PHP Brief History of PHP PHP (PHP: Hypertext Preprocessor) was created by Rasmus Lerdorf

in 1994. It was initially developed for HTTP usage logging and server-side form generation in Unix

PHP 2 (1995) transformed the language into a Server-side embedded scripting language. Added database support, file uploads, variables, arrays, recursive functions, conditionals, iteration, regular expressions, etc.

PHP 3 (1998) added support for ODBC data sources, multiple platform support, email protocols (SNMP,IMAP), and new parser written by Zeev Suraski and Andi Gutmans .

PHP 4 (2000) became an independent component of the web server for added efficiency. The parser was renamed the Zend Engine. Many security features were added.

Page 6: Php Tutorial

PHP 5 (2004) adds Zend Engine II with object oriented programming, robust XML support using the libxml2 library, SOAP extension for interoperability with Web Services, SQLite has been bundled with PHP

Page 7: Php Tutorial

PHP FeaturesPHP Features Open source / Free software.

Cross Platform to develop, to deploy, and to use.

Power,Robust, Scalable.

Web development specific.

Can be Object Oriented.

It is faster to code and faster to execute.

Large, active developer community.

20 million websites

Support for PHP is free.

Great documentation in many language www.php.net/docs.php

Page 8: Php Tutorial

Why use PHP ?Why use PHP ? 1. Easy to use

Code is embedded into HTML. The PHP code is enclosed in special

start and end tags that allow you to jump into and out.

<html>

<head>

<title>Example</title>

</head>

Page 9: Php Tutorial

<body>

<?php

echo “Hi , I’m a PHP script! ”;

?>

</body>

</html>

Page 10: Php Tutorial

2.Cross Platform

Run on almost any web server on several Operating Systems.

One of the strongest features is the wide range of supported databases.

• Web Server : Apache, Microsoft IIS , Netscape Enterprise Server.

• Operating Systems : Unix (Solaris,Linux),Mac OS, Window NT/98/2000/XP/2003.

• Supported Databases : dBase,Empress,FilePro (read only), Hyperware, IBM DB2,InformixIngress,Frontbase,MySql,ODBC,Oracle etc.

Page 11: Php Tutorial

3. Cost Benefits

PHP is free. Open Source code means that the entire PHP community

will contribute towards bug fixes. There are several add-on technologies

(libraries) for PHP that are also free.

Page 12: Php Tutorial

DatatypesDatatypes PHP stores whole numbers in a platform-dependent range.

This range is typically that of 32-bit signed integers. Unsigned integers are converted to signed values in certain situations.

Arrays can contain elements of any type that handle in PHP .

Including resources, objects, and even other arrays.

PHP also supports strings, which can be used with single quotes, double quotes, or heredoc syntax.

Page 13: Php Tutorial

What does PHP code look like?What does PHP code look like?

Structurally similar to C/C++

Supports procedural and object-oriented paradigm (to some degree)

All PHP statements end with a semi-colon

Each PHP script must be enclosed in the reserved PHP tag

<?php …?>

Page 14: Php Tutorial

Comments in PHPComments in PHP

Standard C, C++, and shell comment symbols

// C++ and Java-style comment

# Shell-style comments

/* C-style comments These can span multiple lines */

Page 15: Php Tutorial

Variables in PHPVariables in PHP PHP variables must begin with a “$” sign

Case-sensitive ($Foo != $foo != $fOo)

Global and locally-scoped variables

-- Global variables can be used anywhere

-- Local variables restricted to a function or class

Certain variable names reserved by PHP

-- Form variables ($_POST, $_GET)

-- Server variables ($_SERVER)

-- Etc.

Page 16: Php Tutorial

Variable usageVariable usage

<?php$foo = 25; // Numerical variable$bar = “Hello”; // String variable

$foo = ($foo * 7); // Multiplies foo by 7$bar = ($bar * 7); // Invalid expression ?>

Page 17: Php Tutorial

EchoEcho

The PHP command ‘echo’ is used to output the parameters passed to it

--The typical usage for this is to send data to the client’s web-browser

Syntax

-- void echo (string arg1 [, string argn...])

-- In practice, arguments are not passed in parentheses since echo

is a language construct rather than an actual function

Page 18: Php Tutorial

Echo exampleEcho example

PHP scripts are stored as human-readable source code and are compiled on-the-fly to an internal format that can be executed by the PHP engine.

Code optimizers aim to reduce the runtime of the compiled code by reducing its size and making other changes that can reduce the execution time with the goal of improving performance.

<?php$foo = 25; // Numerical variable$bar = “Hello”; // String variable

echo $bar; // Outputs Helloecho $foo,$bar; // Outputs 25Helloecho “5x5=”,$foo; // Outputs 5x5=25echo “5x5=$foo”; // Outputs 5x5=25echo ‘5x5=$foo’; // Outputs 5x5=$foo?>

Page 19: Php Tutorial

Arithmetic OperationsArithmetic Operations

$a - $b // subtraction

$a * $b // multiplication

$a / $b // division

$a += 5 // $a = $a+5 Also works for *= and /=

<?php$a=15;$b=30;$total=$a+$b;Print $total;Print “<p><h1>$total</h1>”;// total is 45

?>

Page 20: Php Tutorial

ConcatenationConcatenation

<?php$string1=“Hello”;$string2=“PHP”;$string3=$string1 . “ ” . $string2;Print $string3;?>

Hello PHP

Page 21: Php Tutorial

Escaping the CharacterEscaping the Character If the string has a set of double quotation marks that must remain

visible, use the \ [backslash] before the quotation marks to ignore and display them.

<?php$heading=“\”Computer Science\””;Print $heading;?>

“Computer Science”

Page 22: Php Tutorial

PHP Control StructuresPHP Control Structures Control Structures: Are the structures within a language that allow

us to control the flow of execution through a program or script.

Grouped into conditional (branching) structures (e.g. if/else) and repetition structures (e.g. while loops).

Example if/else if/else statement:

if ($foo == 0) {

echo ‘The variable foo is equal to 0’;

}

else if (($foo > 0) && ($foo <= 5)) {

echo ‘The variable foo is between 1 and 5’;

}

else {

echo ‘The variable foo is equal to ‘.$foo;

}

Page 23: Php Tutorial

If ... Else...If ... Else...If (condition)

{

Statements;

}

Else

{

Statement;

}

<?phpIf($user==“John”){

Print “Hello John.”;}Else{

Print “You are not John.”;}?>

No THEN in PHP

Page 24: Php Tutorial

While LoopsWhile Loops

While (condition)

{

Statements;

}

<?php$count=0;While($count<3){

Print “hello PHP. ”;$count += 1;// $count = $count + 1;// or// $count++;

?>

hello PHP. hello PHP. hello PHP.

Page 25: Php Tutorial

Date DisplayDate Display

$datedisplay=date(“yyyy/m/d”);Print $datedisplay;# If the date is April 1st, 2009# It would display as 2009/4/1

$datedisplay=date(“l, F m, Y”);

Print $datedisplay;

# If the date is April 1st, 2009

# Wednesday, April 1, 2009

2009/4/1

Wednesday, April 1, 2009

Page 26: Php Tutorial

Month, Day & Date Format SymbolsMonth, Day & Date Format Symbols

M Jan

F January

m 01

n 1

Day of Month d 01

Day of Month J 1

Day of Week l Monday

Day of Week D Mon

Page 27: Php Tutorial

FunctionsFunctions Functions MUST be defined before then can be called

Function headers are of the format

-- Note that no return type is specified

Unlike variables, function names are not case sensitive (foo(…) == Foo(…) == FoO(…))

function functionName($arg_1, $arg_2, …, $arg_n)

Page 28: Php Tutorial

Functions exampleFunctions example

<?php

// This is a function

function foo($arg_1, $arg_2)

{ $arg_2 = $arg_1 * $arg_2;

  return $arg_2;}

$result_1 = foo(12, 3); // Store the function

echo $result_1; // Outputs 36

echo foo(12, 3); // Outputs 36

?>

Page 29: Php Tutorial

Include FilesInclude FilesInclude “opendb.php”;

Include “closedb.php”;

This inserts files; the code in files will be inserted into current code. Thiswill provide useful and protective means once you connect to a database, as well as for other repeated functions.

Include (“footer.php”);

The file footer.php might look like:

<hr SIZE=11 NOSHADE WIDTH=“100%”>

<i>Copyright © 2008-2010 KSU </i></font><br>

<i>ALL RIGHTS RESERVED</i></font><br>

<i>URL: http://www.kent.edu</i></font><br>

Page 30: Php Tutorial

PHP FormsPHP Forms Access to the HTTP POST and GET data is simple in PHPAccess to the HTTP POST and GET data is simple in PHP

The global variables $_POST[] and $_GET[] contain the request dataThe global variables $_POST[] and $_GET[] contain the request data

<?php

if ($_POST["submit"])

echo "<h2>You clicked Submit!</h2>";

else if ($_POST["cancel"])

echo "<h2>You clicked Cancel!</h2>";

?>

<form action="form.php" method="post">

<input type="submit" name="submit" value="Submit">

<input type="submit" name="cancel" value="Cancel">

</form>

Page 31: Php Tutorial

What is a cookie ? What is a cookie ?

A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests for a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

Page 32: Php Tutorial

How To Create a Cookie?How To Create a Cookie? The setcookie() function is used to create cookies.

Note: The setcookie() function must appear BEFORE the <html> tag.

setcookie(name, [value], [expire], [path], [domain], [secure]);

This sets a cookie named "uname" - that expires after ten hours. <?php setcookie("uname", $name, time()+36000); ?> <html> <body> …

Page 33: Php Tutorial

How To Retrieve a Cookie Value?How To Retrieve a Cookie Value? To access a cookie you just refer to the cookie name as a

variable or use $_COOKIE array

Tip: Use the isset() function to find out if a cookie has been set.

<html> <body>

<?php

if (isset($uname))

echo "Welcome " . $uname . "!<br />";

else

echo "You are not logged in!<br />"; ?>

</body> </html>

Page 34: Php Tutorial

How To Delete a Cookie ?How To Delete a Cookie ?

Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string (""), and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client.

Page 35: Php Tutorial

What is a Session?

The session support allows you to register arbitrary numbers of variables to be preserved across requests.

A visitor accessing your web site is assigned an unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.

Tip: Use the isset() function to find out if a cookie has been set.

Page 36: Php Tutorial

How to Create a Session ? The session_start() function is used to create cookies.

<?php

session_start();

?>

Page 37: Php Tutorial

How to Retrieve a Session Value ? Register Session variable

-- session_register('var1','var2',...); // will also create a session

-- PS:Session variable will be created on using even if you will not register it!

Use it

<?php session_start();

if (!isset($_SESSION['count'])) $_SESSION['count'] = 0; else

$_SESSION['count']++; ?>

Page 38: Php Tutorial

Storing Session Data

The $_SESSION superglobal array can be used to store any session data.

e.g.

$_SESSION[‘name’] = $name;

$_SESSION[‘age’] = $age;

Page 39: Php Tutorial

Reading Session Data

Data is simply read back from the $_SESSION

superglobal array.

e.g.

$_SESSION[‘name’] = $name;

$_SESSION[‘age’] = $age;

Page 40: Php Tutorial

How to Delete a Session Value ?

session_unregister(´varname´);

How to destroy a session:

session_destroy()

Page 41: Php Tutorial

PHP DATABASE INTERACTION IN FIVE STEPS

1) Create the Connection

2) Select the Database

3) Perform Database Query

4) Use Returned Data (if any)

5) Close Connection

Page 42: Php Tutorial

1. Connect with MySQL RDBMS

mysql_connect($hostName, $userName, $password) or die("Unable to connect to host $hostName");

Page 43: Php Tutorial

2. Connect with database

mysql_select_db($dbName) or die("Unable to select database $dbName");

Page 44: Php Tutorial

3. Perform Database Query

Queries: Nearly all table interaction and management is done through

queries:

Basic information searches

$query = "SELECT FirstName, LastName, DOB, Gender FROM Patients WHERE Gender = '$Gender‘ ORDER BY FirstName DESC";$Patients = mysql_query($SQL);

Editing, adding, and deleting records and tables

$query = "INSERT INTO Patients (FirstName, LastName) VALUES('$firstName', '$lastName')";$Patients = mysql_query($SQL);

Page 45: Php Tutorial

4. Process Results (if any)• Many functions exist to work with database results

mysql_num_rows()

– Number of rows in the result set

– Useful for iterating over result set

mysql_fetch_array()

– Returns a result row as an array

– Can be associative or numeric or both (default)

– $row = mysql_fetch_array($query);

– $row[‘column name’] :: value comes from database row with specified column name

Page 46: Php Tutorial

Process Results Loop

• Easy loop for processing results:

$result = mysql_query($query;

$num_rows = mysql_num_rows($query);

for ($i=0; $i<$num_rows; $i++) {

$row = mysql_fetch_array($result);

// take action on database results here

}

Page 47: Php Tutorial

5. Closing Database Connection

• mysql_close()

– Closes database connection

– Only works for connections opened with mysql_connect()

– Connections opened with mysql_pconnect() ignore this call

– Often not necessary to call this, as connections created by mysql_connect are closed at the end of the script anyway

Page 48: Php Tutorial

THAN ”Q”