Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 59

Chapter 1

 Client-Side Scripting Language


 Basics of PHP
What is PHP?
 PHP stands for ‘Hypertext Pre-processor’
 Open-source, server-side scripting language
 Used to generate dynamic web-pages
 PHP scripts reside between reserved PHP tags
 This allows the programmer to embed PHP

scripts within HTML pages


PreProcessor
 PreProcessor means it processes what will
appear as Hypertext before the hypertext
appears on the screen.
 This means it will allow you to do
programming, loops, database search, before
the script generates the HTML that will
appear on the screen.
Scripting languages
 A scripting language is:
 cross-platform since interpreter is easy to port
 designed to support a specific task – PHP -> Web
support
 un-typed variables (but values are typed)
 implicit variable declaration
 implicit type conversion
 stored only as script files
 compiled on demand
 may run on the server (PHP) or the client (Javascript)
What is Server Side Scripting

 A Server is a program that sits and listens, it


waits for an input to come from a line that open
to the Internet. Once it gets that input it
responds by starting a program.
 You can place two types of files on the server.
1. HTML files, XHTML or XML all of which display
their code at the client system.
2. Server Side scripts like PHP, ASP, etc. where
the output of these scripts are displayed on the
clients system.
How Does it work?
 The server has an interpreter (a program)
that takes the script you write as input, and it
executes all the commands that are enclosed
in the script type tags. For php these are <?
php ?>
 Executing may display data, or perform
comparisons, or loops. It may also access a
database, to search for values and display
the results on the screen.
What you need:
 You will need three components to work with
PHP server side scripting;
 Web Server: e.g.Apache server
 Database: e.g. MySql database
 PHP interpreter

Or Third Party Software like:


 WAMP, LAMP, XAMP, Vertrigo….
What is PHP (cont’d)
 Interpreted language, scripts are parsed at run-
time rather than compiled beforehand
 Executed on the server-side
 Source-code not visible by client
 ‘View Source’ in browsers does not display the PHP
code
 Various built-in functions allow for fast
development
 Compatible with many popular databases
What does PHP code look like?
 Structurally similar to C/C++
 Supports procedural and object-oriented
paradigm
 All PHP statements end with a semi-colon
 Each PHP script must be enclosed in the
reserved PHP tag

<?php

?>
PHP Basics…

 The Script Tags


 All PHP code is contained in one of several script
tags:Z
 <?
// Some code
?>
 <?php
// Some code here
?>
Cont’d…

 The Script Tags (cont.)


 <script language=“PHP">
// Some code here
</script>
 ASP-style tags
 Introduced in 3.0; may be removed in the future
 <%
// Some code here
%>
Examples

 Hello World!: An Example


 Like Perl, there is more than one way to do it
 <?php echo “Hello World!”; ?>
 <?php
$greeting = “Hello World!”
printf(“%s”, $greeting);
php?>
 <script language=“PHP”>
$hello = “Hello”;
$world = “World!”;
print $hello . $world
</script>
Cont’d…
 PHP is looselly typed Scripting Language. Thus it
supporte data types like int, float, String.
 Operators
 Contains all of the operators like in C and java
Comments 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 */
PHP Control Structures…..

Operator Meaning
== Is Equal to
!= Not Equal to
< Is less than
<= Is less than or equal to
> Is Greater than
>= Is Greater than or equal to
&& and And
|| or Or

15
Variables 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.
Variable usage

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

$foo = ($foo * 7); // Multiplies foo by 7


$bar = ($bar * 7); // Invalid expression
?>
PHP Constants
 Constants define a string or numeric value
 Constants do not begin with a dollar sign

 Examples:

 define(“COMPANY”, “Acme Enterprises”);


 define(“YELLOW”, “#FFFF00”);
 define(“PI”, 3.14);
 define(“NL”, “<br>\n”);

E.g. print(“Company name: “ . COMPANY . NL);


Echo
 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
PHP - Forms
•Access to the HTTP POST and GET data is simple in PHP
•The 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>

http://www.cs.kent.edu/~nruan/form.php
Echo example
<?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
?>

 Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with 25
 Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP
 This is true for both variables and character escape-sequences (such as “\
n” or “\\”)
Arithmetic Operations
<?php
$a=15;
$b=30;
$total=$a+$b;
Print $total;
Print “<p><h1>$total</h1>”;
// total is 45
?>

 $a - $b // subtraction
 $a * $b // multiplication
 $a / $b // division
 $a += 5 // $a = $a+5 Also works for *= and /=
Concatenation

 Use a period to join strings into one.


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

Hello PHP
Escaping 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”
PHP 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;
}
If ... Else...
 If (condition)
{ <?php
If($user==“John”)
Statements;{ Print “Hello John.”;
} }
Else
Else {
Print “You are not John.”;
{ }
?>
Statement;
}
No THEN in PHP
While Loops
<?php
{While (condition) $count=0;
While($count<3)
{
Print “hello PHP. ”;
Statements; $count += 1;
// $count = $count + 1;
} // or
// $count++;
?>

hello PHP. hello PHP. hello PHP.


 for(initialization; condition; increament
/decreament)
 { <?php
 Blcks of statements for($count=0;$count<3;$count++)
{
Print “hello PHP. ”;
$count += 1;
 } // $count = $count + 1;
// or
// $count++;
?>

hello PHP. hello PHP. hello PHP.


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

$datedisplay=date(“l, F m, Y”);
Wednesday, April 1, 2009 Print $datedisplay;
# If the date is April 1st, 2009
# Wednesday, April 1, 2009
Functions
 Functions MUST be defined before then can be
called
 Function headers are of the format
function functionName($arg_1, $arg_2, …, $arg_n)
 Note that no return type is specified
 Unlike variables, function names are not case
sensitive (foo(…) == Foo(…) == FoO(…))
Functions 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
?>
Arrays

 An array is traditionally defined as a group of


items that share certain characteristics, such
as similarity…
 An array in PHP is actually an ordered map.
A map is a type that maps values to keys.
 To create and Array use array() construct.
 Syntax: array( key => value, ...)
 // key may be an integer or string
 // value may be any value
Arrays
 Arrays in PHP are quite versatile
 We can use them as we use traditional
arrays, indexing on integer values
 We can use them as hashes by associating a
key with a value in an arbitrary index of the
array
 In either case we access the data via
subscripts
 In the first case the subscript is the integer index
 In the second case the subscript is the key value
 We can even mix the two if we'd like
33
Arrays….

 PHP arrays are a cross between numbered


arrays and associative arrays.
 This means that you can use the same
syntax and functions to deal with either type
of array, including arrays that are:
 Indexed from 0
 Indexed by strings
 Indexed with non-continuous numbers
 Indexed by a mix of numbers and strings

34
Arrays….
In the example below, three literal arrays are declared as follows:
1. A numerically indexed array with indices running from 0 to 4.
2. An associative array with string indices.
3. A numerically indexed array, with indices running from 5 to 7.
<?php
$array1 = array(2, 3, 5, 7, 11);
$array2 = array("one" => 1,
"two" => 2,
"three" => 3);
$array3 = array(5 => "five", "six", "seven");
Print ($array1[3], $array2["one"], $array3[6]);
?>

35
Arrays….
 From the above example, the indices in the array1 are
implicit, while the indices in array2 are explicit.
 When specifically setting the index to a number N with
the =>operator, the next value has the index N+1 by default.
 Explicit indices do not have to be listed in sequential order.
You can also mix numerical and string indexes, but it is not
recommended.
 Assigning a collection of values to an array variable is
simple using the array() construct:
 $colors = array("blue","indigo","yellow");
 Or, if you know that you want to create an array $colors but don't yet know what
values to fill it with, create an empty array:
 $colors = array();

36
Arrays….
 Adding new values to the array is a breeze:
 $colors[] = "hunter green";
 Now the array $colors contains four values.
 Often times, you need to access a single item in an array,
such as for output or a calculation.
 To do this, we can output the second color in the array via the
key 1: print $colors[1];
...will output indigo.
 Next, it makes sense to use keys which are labels more meaningful
than a mere index (if you describe for example the car):
$colors = array("exterior"=>"blue",
 "trim"=>"indigo",
 "fabric"=>"yellow",
 "dashboard"=>"hunter green");

37
Arrays….
 It's now easy to output the fabric color of this car, because fabric is a
key in the list:
 print $colors[fabric];

...will output yellow.


 Next, we wanted to output each of the items in $colors, along with
the key associated with that item.
 These returned values are assigned on-the-fly to $key and $value.

foreach ($colors as $key=>$value) {


print "$colors[\"$key\"]== $value<br>"; }
 The similar result is courtesy of the list() function:

while (list($key,$value) = each($colors)) {


print "$key: $value<BR>"; }

38
Arrays….
 In the browser, the above code would output:
exterior: blue
trim: indigo
fabric: yellow
dashboard: hunter green
 Simply, use PHP's ksort() function to sort $colors by key,
and then step through the array as before:
ksort ($colors);
while (list($key,$value) = each($colors)) {
print "$key: $value<BR>"; }

39
Arrays….

 There are various predefined sort functions in


PHP
 sort (rsort for reverse)
 Sorts arrays of numbers numerically
 Sorts arrays of strings alphabetically
 If mixed, the strings count as 0
 Reindexes array so that keys start at 0 and increment
from there
 asort
 Same as sort but retains the original key values (arsort
for reverse)
40
Include Files
Include “opendb.php”;
Include “closedb.php”;
This inserts files; the code in files will be inserted into current code.
This will 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>
The use of include()
 Besides breaking up PHP code into multiple blocks, it is also
possible to include code from external files into your pages.
 Sometimes you wish to keep bits of code in its own file - for
instance, HTML code that makes up a repeating element such as a
logo or footer, or PHP code that makes up a function that you might
want to use in several different pages.
 suppose we break out the footer into its own file, and the initial PHP
block into its own file:

 setdate.php:
 <?php $today=getdate(time());?>

 footer.php:
<!-- begin footer --><SMALL>Today is <?php print $today[weekday];?></SMALL>

42
The use of include()…..
 Now, we can use PHP's include() function to pull the above
files into our example page:
<?php
include ("setdate.php");
?>
<H2>Today's Headline:</H2>
<P ALIGN="center">
<?php
print "World Peace Declared";
?>
</P><HR>
<?php include ("footer.php");
?>
 The most common use for the include() function is,
as seen above, to reuse certain components across
several pages. Files called by include() can have
other extensions like html, php3 and so on.

43
WHY PHP – Sessions ?
Whenever you want to create a website that allows you to store and display
information about a user, determine which user groups a person belongs to,
utilize permissions on your website or you just want to do something cool on
your site, PHP's Sessions are vital to each of these features.

Cookies are about 30% unreliable right now and it's getting worse every day.
More and more web browsers are starting to come with security and privacy
settings and people browsing the net these days are starting to frown upon
Cookies because they store information on their local computer that they do
not want stored there.

PHP has a great set of functions that can achieve the same results of
Cookies and more without storing information on the user's computer. PHP
Sessions store the information on the web server in a location that you chose
in special files. These files are connected to the user's web browser via the
server and a special ID called a "Session ID". This is nearly 99% flawless in
operation and it is virtually invisible to the user.
PHP - Sessions
•Sessions store their identifier in a cookie in the client’s browser
•Every page that uses session data must be proceeded by the
session_start() function
•Session variables are then set and retrieved by accessing the global
$_SESSION[]

•Save it as session.php
<?php
session_start();
if (!$_SESSION["count"])
$_SESSION["count"] = 0;
if ($_GET["count"] == "yes")
$_SESSION["count"] = $_SESSION["count"] + 1;
echo "<h1>".$_SESSION["count"]."</h1>";
?>
<a href="session.php?count=yes">Click here to count</a>

http://www.cs.kent.edu/~nruan/session.php
Avoid Error PHP - Sessions
PHP Example: <?php
echo "Look at this nasty error below:<br />";
session_start();
?>
Error!

Warning: Cannot send session cookie - headers already sent by


(output started at session_header_error/session_error.php:2)
in session_header_error/session_error.php on line 3
Warning: Cannot send session cache limiter - headers already
sent (output started at
session_header_error/session_error.php:2) in
session_header_error/session_error.php on line 3

PHP Example: <?php


session_start();
echo "Look at this nasty error below:";
?>
Correct
Destroy PHP - Sessions
Destroying a Session
why it is necessary to destroy a session when the session will get destroyed
when the user closes their browser. Well, imagine that you had a session
registered called "access_granted" and you were using that to determine
if the user was logged into your site based upon a username and
password. Anytime you have a login feature, to make the users feel
better, you should have a logout feature as well. That's where this cool
function called session_destroy() comes in handy. session_destroy() will
completely demolish your session (no, the computer won't blow up or self
destruct) but it just deletes the session files and clears any trace of that
session.
NOTE: If you are using the $_SESSION superglobal array, you must clear
the array values first, then run session_destroy.
Here's how we use session_destroy():
Destroy PHP - Sessions
<?php
// start the session
session_start();
header("Cache-control: private"); //IE 6 Fix
$_SESSION = array();
session_destroy();
echo "<strong>Step 5 - Destroy This Session </strong><br />";
if($_SESSION['name']){
echo "The session is still active";
} else {
echo "Ok, the session is no longer active! <br />";
echo "<a href=\"page1.php\"><< Go Back Step 1</a>";
}
?>

http://www.cs.kent.edu/~nruan/session_destroy.php
PHP Overview
 Easy learning
 Syntax Perl- and C-like syntax. Relatively
easy to learn.
 Large function library
 Embedded directly into HTML
 Interpreted, no need to compile
 Open Source server-side scripting language
designed specifically for the web.
PHP Overview (cont.)
 Conceived in 1994, now used on +10 million web
sites.
 Outputs not only HTML but can output XML,
images (JPG & PNG), PDF files and even Flash
movies all generated on the fly. Can write these
files to the file system.
 Supports a wide-range of databases (20+ODBC).
 PHP also has support for talking to other services
using protocols such as LDAP, IMAP, SNMP,
NNTP, POP3, HTTP.
First PHP script
 Save as sample.php:
<!– sample.php -->
<html><body>
<strong>Hello World!</strong><br />
<?php
echo “<h2>Hello, World</h2>”; ?>
<?php
$myvar = "Hello World";
echo $myvar;
?>
</body></html>
http://www.cs.kent.edu/~nruan/sample.php
PHP Control Structures

 PHP includes if and elseif conditionals, as well as while and for


loops, all with syntax similar to C.
 The example below introduces these four constructs:

<?php
// Conditionals
if ($a) {
print "a is true<BR>\n";
} elseif ($b) {
print "b is true<BR>\n";
} else {
print "neither a or b is true<BR>\n";
}

52
PHP Control Structures….
// Loops
do {
$c = test_something();
} while ($c);
while ($d) {
print "ok<BR>\n";
$d = test_something();
}
for ($i = 0; $i < 10; $i++) {
print "i=$i<BR>\n";
}
?>
53
PHP Control Structures…

IF statement
 Normal if..then..else statement

 Ex.
if ($a<5) {
$b=$a+10;
}
else {
$b=$a*2;
}

54
PHP Control Structures…..

Operator Meaning
== Is Equal to
!= Not Equal to
< Is less than
<= Is less than or equal to
> Is Greater than
>= Is Greater than or equal to
&& and And
|| or Or

55
PHP Control Structures…..

For loop
 Normal for loop: for (starting value;ending

value;increment)
 Ex.

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


echo $i;
} While Loop

56
PHP Control Structures….

Normal while loop


 while (something is true) {

some statements
}
Ex.
$i=0;
while ($i<10){
echo $i;
$i++;
}

57
PHP Control Structures….
 Again, these are similar to those in C++ / Java
 if, while, do, for, switch are virtually identical to those
in C++ and Java
 PHP allows for an alternative syntax to designate a
block in the if, while, for and switch statements
 Open the block with : rather than {
 Close the block with endif, endwhile, endfor, endswitch
 Advantage to this syntax is readability
 Now instead of seeing a number of close braces, we
see different keywords to close different types of control
structures

58
PHP Expressions and Operators
 Similar to those in C++ / Java / Perl
 Be careful with a few operators
 / in PHP is always floating point division
 To get integer division, we must cast to int
$x = 15;
$y = 6;
echo ($x/$y), (int) ($x/$y), "<BR />";
 Output is 2.5 2

59

You might also like