PHP (Hypertext Preprocessor)
-Gursharandeep kaur bajwa
(CTIEMT)
100220314317
IntroductionIntroduction

PHP is stands for ’Hypertext Preprocessor ’ used for making
dynamic web pages and interactive w...
PHP FilesPHP Files

PHP files can contain text, HTML Tags and scripts.

PHP files are returned to the browser as plain H...
“PHP is an HTML-embedded scripting language. Much of its syntax is
borrowed from C,Java & Perl with a couple of unique PHP...
Brief History of PHPBrief History of PHP
PHP (PHP: Hypertext Preprocessor) was created by Rasmus Lerdorf
in 1994. It was i...

PHP 5 (2004) adds Zend Engine II with object oriented programming,
robust XML support using the libxml2 library, SOAP ex...
PHP FeaturesPHP Features

Open source / Free software.

Cross Platform to develop, to deploy, and to use.

Power,Robust...
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 ta...
<body>
<?php
echo “Hi , I’m a PHP script! ”;
?>
</body>
</html>
2.Cross Platform
Run on almost any web server on several Operating Systems.
One of the strongest features is the wide rang...
3. Cost Benefits
PHP is free. Open Source code means that the entire PHP community
will contribute towards bug fixes. Ther...
DatatypesDatatypes

PHP stores whole numbers in a platform-dependent range.

This range is typically that of 32-bit sign...
What does PHP code look like?What does PHP code look like?

Structurally similar to C/C++

Supports procedural and objec...
Comments in PHPComments in PHP

Standard C, C++, and shell comment symbols
// C++ and Java-style comment
# Shell-style co...
Variables in PHPVariables in PHP

PHP variables must begin with a “$” sign

Case-sensitive ($Foo != $foo != $fOo)

Glob...
Variable usageVariable usage
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
$foo = ($foo * 7); ...
EchoEcho

The PHP command ‘echo’ is used to output the parameters passed
to it
--The typical usage for this is to send da...
Echo exampleEcho example

PHP scripts are stored as human-readable source code and are compiled
on-the-fly to an internal...
Arithmetic OperationsArithmetic Operations

$a - $b // subtraction

$a * $b // multiplication

$a / $b // division

$a...
ConcatenationConcatenation
<?php
$string1=“Hello”;
$string2=“PHP”;
$string3=$string1 . “ ” . $string2;
Print $string3;
?>
...
Escaping the CharacterEscaping the Character

If the string has a set of double quotation marks that must remain
visible,...
PHP Control StructuresPHP Control Structures

Control Structures: Are the structures within a language that allow us
to c...
If ... Else...If ... Else...
If (condition)
{
Statements;
}
Else
{
Statement;
}
<?php
If($user==“John”)
{
Print “Hello Joh...
While LoopsWhile Loops
While (condition)
{
Statements;
}
<?php
$count=0;
While($count<3)
{
Print “hello PHP. ”;
$count += ...
Date DisplayDate Display
$datedisplay=date(“yyyy/m/d”);
Print $datedisplay;
# If the date is April 1st
, 2009
# It would d...
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...
FunctionsFunctions

Functions MUST be defined before then can be called

Function headers are of the format
-- Note that...
Functions exampleFunctions example
<?php
// This is a function
function foo($arg_1, $arg_2)
{
$arg_2 = $arg_1 * $arg_2;
re...
Include FilesInclude Files
Include “opendb.php”;
Include “closedb.php”;
This inserts files; the code in files will be inse...
PHP FormsPHP Forms

Access to the HTTP POST and GET data is simple in PHPAccess to the HTTP POST and GET data is simple i...
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...
How To Create a Cookie?How To Create a Cookie?

The setcookie() function is used to create cookies.
Note: The setcookie()...
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...
How To Delete a Cookie ?How To Delete a Cookie ?

Cookies must be deleted with the same parameters as they
were set with....
What is a Session?

The session support allows you to register arbitrary numbers
of variables to be preserved across requ...
How to Create a Session ?

The session_start() function is used to create cookies.
<?php
session_start();
?>
How to Retrieve a Session Value ?

Register Session variable
-- session_register('var1','var2',...); // will also create ...
Storing Session Data

The $_SESSION superglobal array can be
used to store any session data.
e.g.
$_SESSION[‘name’] = $na...
Reading Session Data
Data is simply read back from the $_SESSION
superglobal array.
e.g.
$_SESSION[‘name’] = $name;
$_SESS...
How to Delete a Session Value ?

session_unregister(´varname´);
How to destroy a session:

session_destroy()
PHP DATABASE INTERACTION IN FIVE STEPS
1) Create the Connection
2) Select the Database
3) Perform Database Query
4) Use Re...
1. Connect with MySQL RDBMS
mysql_connect($hostName, $userName, $password) or
die("Unable to connect to host $hostName");
2. Connect with database
mysql_select_db($dbName) or die("Unable to select
database $dbName");
3. Perform Database Query
Queries: Nearly all table interaction and management is done through
queries:
Basic information ...
4. Process Results (if any)
• Many functions exist to work with database results
mysql_num_rows()
– Number of rows in the ...
Process Results Loop
• Easy loop for processing results:
$result = mysql_query($query;
$num_rows = mysql_num_rows($query);...
5. Closing Database Connection
• mysql_close()
– Closes database connection
– Only works for connections opened with mysql...
THAN ”Q”
Upcoming SlideShare
Loading in …5
×

Php Tutorial

2,408
-1

Published on

PHP Tutorial

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,408
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
125
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Php Tutorial

  1. 1. PHP (Hypertext Preprocessor) -Gursharandeep kaur bajwa (CTIEMT) 100220314317
  2. 2. 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.
  3. 3. 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
  4. 4. “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. ”
  5. 5. Brief History of PHPBrief 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.
  6. 6.  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
  7. 7. 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
  8. 8. 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>
  9. 9. <body> <?php echo “Hi , I’m a PHP script! ”; ?> </body> </html>
  10. 10. 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.
  11. 11. 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.
  12. 12. 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.
  13. 13. 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 … ?>
  14. 14. 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 */
  15. 15. 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.
  16. 16. Variable usageVariable usage <?php $foo = 25; // Numerical variable $bar = “Hello”; // String variable $foo = ($foo * 7); // Multiplies foo by 7 $bar = ($bar * 7); // Invalid expression ?>
  17. 17. 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
  18. 18. 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 Hello echo $foo,$bar; // Outputs 25Hello echo “5x5=”,$foo; // Outputs 5x5=25 echo “5x5=$foo”; // Outputs 5x5=25 echo ‘5x5=$foo’; // Outputs 5x5=$foo ?>
  19. 19. 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 ?>
  20. 20. ConcatenationConcatenation <?php $string1=“Hello”; $string2=“PHP”; $string3=$string1 . “ ” . $string2; Print $string3; ?> Hello PHP
  21. 21. 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”
  22. 22. 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; }
  23. 23. If ... Else...If ... Else... If (condition) { Statements; } Else { Statement; } <?php If($user==“John”) { Print “Hello John.”; } Else { Print “You are not John.”; } ?> No THEN in PHP
  24. 24. 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.
  25. 25. 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
  26. 26. 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
  27. 27. 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)
  28. 28. 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 ?>
  29. 29. Include FilesInclude Files Include “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>
  30. 30. 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>
  31. 31. 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.
  32. 32. 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> …
  33. 33. 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>
  34. 34. 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.
  35. 35. 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.
  36. 36. How to Create a Session ?  The session_start() function is used to create cookies. <?php session_start(); ?>
  37. 37. 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']++; ?>
  38. 38. Storing Session Data  The $_SESSION superglobal array can be used to store any session data. e.g. $_SESSION[‘name’] = $name; $_SESSION[‘age’] = $age;
  39. 39. Reading Session Data Data is simply read back from the $_SESSION superglobal array. e.g. $_SESSION[‘name’] = $name; $_SESSION[‘age’] = $age;
  40. 40. How to Delete a Session Value ?  session_unregister(´varname´); How to destroy a session:  session_destroy()
  41. 41. 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
  42. 42. 1. Connect with MySQL RDBMS mysql_connect($hostName, $userName, $password) or die("Unable to connect to host $hostName");
  43. 43. 2. Connect with database mysql_select_db($dbName) or die("Unable to select database $dbName");
  44. 44. 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);
  45. 45. 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
  46. 46. 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 }
  47. 47. 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
  48. 48. THAN ”Q”
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×