SlideShare a Scribd company logo
Unit 5
Introduction
to PHP
PHP Basics:
Introduction to PHP
• a PHP file, PHP workings, running PHP.
▪ Basic PHP syntax
• variables, operators, if...else...and switch,
while, do while, and for.
▪ Some useful PHP functions
▪ How to work with
• HTML forms, cookies, files, time and date.
▪ How to create a basic checker for user-entered data
2
Server-Side Dynamic Web Programming
• CGI is one of the most common approaches to server-
side programming
▪ Universal support: (almost) Every server supports CGI
programming. A great deal of ready-to-use CGI code. Most APIs
(Application Programming Interfaces) also allow CGI
programming.
▪ Choice of languages: CGI is extremely general, so that programs
may be written in nearly any language. Perl is by far the most
popular, with the result that many people think that CGI means
Perl. But C, C++, Ruby, and Python are also used for CGI
programming.
▪ Drawbacks: A separate process is run every time the script is
requested. A distinction is made between HTML pages and code.
3
• Other server-side alternatives try to avoid the
drawbacks
▪ Server-Side Includes (SSI): Code is embedded in HTML pages,
and evaluated on the server while the pages are being served.
Add dynamically generated content to an existing HTML page,
without having to serve the entire page via a CGI program.
▪ Active Server Pages (ASP, Microsoft) : The ASP engine is
integrated into the web server so it does not require an additional
process. It allows programmers to mix code within HTML pages
instead of writing separate programs. (Drawback(?) Must be run
on a server using Microsoft server software.)
▪ Java Servlets (Sun): As CGI scripts, they are code that creates
documents. These must be compiled as classes which are
dynamically loaded by the web server when they are run.
▪ Java Server Pages (JSP): Like ASP, another technology that
allows developers to embed Java in web pages. 4
PHP
• developed in 1995 by Rasmus Lerdorf (member of the Apache Group)
▪ originally designed as a tool for tracking visitors at Lerdorf's Web site
▪ within 2 years, widely used in conjunction with the Apache server
▪ developed into full-featured, scripting language for server-side programming
▪ free, open-source
▪ server plug-ins exist for various servers
▪ now fully integrated to work with mySQL databases
• PHP is similar to JavaScript, only it’s a server-side language
▪ PHP code is embedded in HTML using tags
▪ when a page request arrives, the server recognizes PHP content via the file
extension (.php or .phtml)
▪ the server executes the PHP code, substitutes output into the HTML page
▪ the resulting page is then downloaded to the client
▪ user never sees the PHP code, only the output in the page
5
What do You Need?
• Install XAMMP
– You don't need to do anything special! *
– You don't need to compile anything or install any
extra tools!
– Create some .php files in your web directory - and the
server will parse them for you.
* Slightly different rules apply when dealing with
an SQL database (as will be explained when we get to
that point).
6
What is PHP?
• PHP == ‘Hypertext Preprocessor’
• 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
• 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
7
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
…
?>
8
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
*/
9
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.
10
Constants
A constant is an identifier (name) for a simple value.
A constant is case-sensitive by default.
By convention, constant identifiers are always uppercase.
<?php
// Valid constant names
define("FOO","something");
define("FOO2","something else");
define("FOO_BAR","something more");
// Invalid constant names (they shouldn’t
start with a number!)
define("2FOO","something");
// This is valid, but should be avoided:
// PHP may one day provide a “magical”
constant
// that will break your script
define("__FOO__", "something");
?>
You can
access
constants
anywhere in
your script
without
regard to
scope.
11
Operators
• Arithmetic Operators: +, -, *,/ , %, ++, --
• Assignment Operators: =, +=, -=, *=, /=, %=
• Comparison Operators: ==, !=, >, <, >=, <=
• Logical Operators: &&, ||, !
• String Operators: . and .= (for string concatenation)
Example Is the same
as
x+=y x=x+y
x-=y x=x-y
x*=y x=x*y
x/=y x=x/y
x%=y x=x%y
$a = "Hello ";
$b = $a . "World!"; // now $b contains
"Hello World!"
$a = "Hello ";
$a .= "World!";
12
Variable usage
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
$foo = ($foo * 7);// Multiplies foo by 7
$bar = ($bar * 7);// Invalid expression
?>
13
Basic PHP syntax
A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block
can be placed (almost) anywhere in an HTML document.
<html>
<!-- hello.php -->
<head><title>Hello World</title></head><body>
<p>This is going to be ignored by the PHP
interpreter.</p>
<?php echo "<p>While this is going to be
parsed.</p>"; ?>
<p>This will also be ignored by the PHP
preprocessor.</p>
<?php print(‘<p>Hello and welcome to <i>my</i>
page!</p>');
?>
<?php
//This is a comment
/* This is
a comment block*/
?>
</body></html>
The server executes the print and echo statements, substitutes output.
print and
echo
for output
a semicolon
(;) at the end of
each statement
// for a single-line
comment
/* and */ for a
large comment
block.
14
Scalars
All variables in PHP start with a $ sign symbol. A variable's type is determined by the
context in which that variable is used (i.e. there is no strong-typing in PHP).
<html><head></head> <!-- scalars.php --><body> <p>
<?php
$foo = true; if ($foo) echo "It is TRUE! <br />
n";
$txt='1234'; echo "$txt <br /> n";
$a = 1234; echo "$a <br /> n";
$a = -123; echo "$a <br /> n";
$a = 1.234; echo "$a <br /> n";
$a = 1.2e3; echo "$a <br /> n";
$a = 7E-10; echo "$a <br /> n";
echo 'Arnold once said: "I'll be back"', "<br />
n";
$snist = 'Sreenidhi Institute of Science and
Technology <br/>';
echo "Rahul studies in $snist";
$str1 = <<<EODTrue
Example of string
spanning multiple lines
using "heredoc" syntax. uses the angular
brackets...
EODTrue;
echo $str1,'<br/>';
?> </p></body></html>
Four scalar types:
boolean
true or false
integer,
float,
floating point
numbers
string
single quoted
double quoted
15
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
16
Echo example
• Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with 25
• PHP won't use additional processing to interpret what is inside the
single quote.
• When you use double quotes PHP has to parse to check if there are
any variables within the string.
• This is true for both variables and character escape-sequences (such as
“n” or “”)
<?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
?>
17
Arithmetic 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
?>
18
Concatenation
• Use a period to join strings into one.
<?php
$string1=“Hello”;
$string2=“PHP”;
$string3=$string1 . “ ” . $string2;
Print $string3;
?>
Hello PHP
19
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” 20
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;
}
21
If ... Else...
• If (condition)
{
Statements;
}
Else
{
Statement;
}
<?php
If($user==“John”)
{
Print “Hello John.”;
}
Else
{
Print “You are not John.”;
}
?>
No THEN in PHP
22
Conditionals: if else (Can execute a set of code depending on a
condition)
<html><head></head>
<!-- if-cond.php -->
<body>
<?php
$d=date("D");
echo $d, “<br/>”;
if ($d=="Fri")
echo "Have a nice weekend!
<br/>";
else
echo "Have a nice day! <br/>";
$x=10;
if ($x==10)
{
echo "Hello<br />";
echo "Good morning<br />";
}
?>
</body></html>
if (condition)
code to be executed if condition
is true;
else
code to be executed if condition
is false;
date() is a built-in PHP function that
can be called with many different
parameters to return the date
(and/or local time) in various formats
In this case we get a three letter
string for the day of the week.
23
Conditionals: switch
Can select one of many sets of lines to execute
<html><head></head><body>
<!–- switch-cond.php -->
<?php
$x = rand(1,5); // random integer
echo “x = $x <br/><br/>”;
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
break;
}
?></body></html>
switch (expression)
{
case label1:
code to be executed if
expression = label1;
break;
case label2:
code to be executed if
expression = label2;
break;
default:
code to be executed
if expression is
different
from both label1 and
label2;
break;
} 24
While 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
Arrays
In PHP, there are three types of arrays:
1. Indexed arrays - Arrays with a numeric index
2. Associative arrays - Arrays with named keys
3. Multidimensional arrays - Arrays containing
one or more arrays
26
Looping: for and foreach
Can loop depending on a "counter"
<?php
for ($i=1; $i<=5; $i++)
{
echo "Hello World!<br />";
}
?>
loops through a block of
code a specified number of
times
<?php
$a_array = array(1, 2, 3, 4);
foreach ($a_array as $value)
{
$value = $value * 2;
echo “$value <br/> n”;
}
?>
loops through a block of code
for each element in an array
<?php
$a_array=array("a","b","c");
foreach ($a_array as $key =>
$value)
{
echo $key." = ".$value."n";
}
?>
27
Arrays
An array in PHP is actually an ordered map. A map is a type that maps values to keys.
array() = creates arrays
<?php
$arr = array("foo" => "bar", 12 => true);
echo $arr["foo"]; // bar
echo $arr[12]; // 1
?>
key = either an integer or a string.
value = any PHP type.
<?php
array(5 => 43, 32, 56, "b" => 12);
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>
if no key given (as in example), the PHP
interpreter uses (maximum of the integer
indices + 1).
if an existing key, its value will be
overwritten.
<?php
$arr = array(5 => 1, 12 => 2);
foreach ($arr as $key => $value) { echo $key, ‘=>’,
$value); }
$arr[] = 56; // the same as $arr[13] = 56;
$arr["x"] = 42; // adds a new element
unset($arr[5]); // removes the element
unset($arr); // deletes the whole array
$a = array(1 => 'one', 2 => 'two', 3 => 'three');
unset($a[2]);
$b = array_values($a);
?>
can set values in an array
unset() removes a
key/value pair
*Find more on arrays
array_values() makes
reindexing effect (indexing numerically)
28
Using print_r() and array_values()
<html><body>
<?php
$a=array("Name"=>"SNIST","Year Started"=>"1997",
"Country"=>"India");
print_r(array_values($a));
?>
</body></html>
Array ( [0] => SNIST [1] => 1997 [2] => India )
29
Date Display
$datedisplay=date(“yyyy/m/d”);
Print $datedisplay;
# If the date is June 25th, 2012
# It would display as 2012/6/25
2012/25/6
$datedisplay=date(“l, F j, Y”);
Print $datedisplay;
# If the date is June 25th ,2012
# Monday, June 25th,2012
Monday, June 25,
2012
Refer the different notation of date:
https://www.w3schools.com/php/func_date_date_format.asp
30
Month, 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
31
Functions
• 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)
32
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
?>
33
User Defined Functions
Can define a function using syntax such as the following:
<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo "Example function.n";
return $retval;
}
?>
Can also define conditional
functions, functions within functions,
and recursive functions.
<?php
function square($num)
{
return $num * $num;
}
echo square(4);
?>
<?php
function small_numbers()
{
return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
echo $zero, $one, $two;
?>
Can return a value of any type
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
takes_array(array(1,2));
?>
34
Variable Scope
The scope of a variable is the context within which it is defined.
<?php
$a = 1; /* limited variable scope */
function Test()
{
echo $a;
/* reference to local scope
variable */
}
Test();
?>
The scope is local within functions,
and hence the value of $a is
undefined in the “echo”
statement.
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
global
refers to its
global
version.
<?php
function Test1()
{
static $a =
0;
echo $a;
$a++;
}
Test1();
Test1();
Test1();
?>
static
does not lose
its value.
Output: 012
35
Including Files
The include() statement includes and evaluates the specified file.
vars.php
<?php
$color = 'green';
$fruit = 'apple';
?>
test.php
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A
green apple
?>
*The scope of variables in “included” files depends on where the “include” file is added!
You can use the include_once, require, and require_once statements in similar ways.
test3.php
<?php
function foo()
{
global $color;
include ('vars.php');
echo "A $color $fruit";
}
/* vars.php is in the scope of
foo() so $fruit is NOT available
outside of this scope. $color is
because we declared it as global.
*/
foo(); // A green apple
echo "A $color $fruit"; // A green
?>
36
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 © 2001-2012 gsu</i></font><br>
<i>ALL RIGHTS RESERVED</i></font><br>
<i>URL: http://www.gsu.edu.edu</i></font><br>
37
PHP Program for File Upload
<!– index.html -- >
<html><body>
<form action="uploader.php" method="post" enctype="multipart/form-
data">
Select File:
<input type="file" name="fileToUpload"/>
<input type="submit" value="Upload File" name="submit"/>
</form>
</body></html>
38
When you make a POST request, you have to encode the data that forms the
body of the request in some way. HTML forms provide three methods of
encoding:
1. application/x-www-form-urlencoded 🡪the default
2. multipart/form-data 🡪 Use this when <input type="file"> is present
3. text/plain 🡪 Never use this.
uploader.php program
<!-- uploader.php -->
<?php
$target_path = "I:AAAphpFileUploads/"; //destination folder
$target_path = $target_path.basename( $_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "File uploaded successfully!";
} else{
echo "Sorry, file not uploaded, please try again!";
}
?>
39
move_uploaded_file() function: move an uploaded file to new location. If
the filename is not a valid upload file or cannot be moved for a reason, then no
action can occur and return false.
bool move_uploaded_file ( string $filename , string $destination )
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>
40
Setting a Cookie:
setcookie(name, value, expire, path, domain, secure, httponly);
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
41
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.
42
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>
43
Avoid Error PHP - Sessions
PHP Example: <?php
echo "Look at this nasty error below:<br />";
session_start();
?>
Error!
PHP Example: <?php
session_start();
echo "Look at this nasty error below:";
?>
Correct
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
44
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():
45
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>";
}
?>
46
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.
47
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.
48
• 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>
First PHP script
49
Example of parameter reading
• Consider:
• contents of php_exec/form.php...
• <html><body>
• <h1>Hi there</h1>
• <? if (!isset($_POST['foo'])): ?>
• <h1>'foo' is not set</h1>
• <? elseif
(!is_array($_POST['foo'])) : ?>
• <h1>'foo' has one value <?=
$_POST['foo'] ?> </h1>
• <? else: ?>
• <h1>'foo' has multiple values <?=
join(',',$_POST['foo']) ?> </h1>
• <? endif ?>
• </body></html>
• ...end of php_exec/form.php
• Call with form:
• contents of php_exec/form01.txt...
<form action='php_exec/form.php'
method='post'> <ul> <li> <input
type='checkbox' name='foo[]'
value='raisins'> raisins. <li> <input
type='checkbox' name='foo[]'
value='cranberries'> cranberries.
<li> <input type='checkbox'
name='foo[]' value='plums'>
plums. </ul> <input type='submit'>
</form> ...end of
php_exec/form01.txt
• Here is what it looks like:
– raisins.
– cranberries.
– plums.
50
Example – show data in the
tables
• Function: list all tables in your database.
Users can select one of tables, and show
all contents in this table.
• second.php
• showtable.php
51
second.php
<html><head><title>MySQL Table Viewer</title></head><body>
<?php
// change the value of $dbuser and $dbpass to your username and password
$dbhost = ‘ codd.cs…….. ';
$dbuser = 'nruan';
$dbpass = ‘*****************’;
$dbname = $dbuser;
$table = 'account';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db($dbname))
die("Can't select database");
52
second.php (cont.)
$result = mysql_query("SHOW TABLES");
if (!$result) {
die("Query to show fields from table failed");
}
$num_row = mysql_num_rows($result);
echo "<h1>Choose one table:<h1>";
echo "<form action="showtable.php" method="POST">";
echo "<select name="table" size="1" Font size="+2">";
for($i=0; $i<$num_row; $i++) {
$tablename=mysql_fetch_row($result);
echo "<option value="{$tablename[0]}" >{$tablename[0]}</option>";
}
echo "</select>";
echo "<div><input type="submit" value="submit"></div>";
echo "</form>";
mysql_free_result($result);
mysql_close($conn);
?>
</body></html>
53
showtable.php
<html><head>
<title>MySQL Table Viewer</title>
</head>
<body>
<?php
$dbhost = 'hercules.cs.kent.edu:3306';
$dbuser = 'nruan';
$dbpass = ‘**********’;
$dbname = 'nruan';
$table = $_POST[“table”];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
if (!mysql_select_db($dbname))
die("Can't select database");
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) die("Query to show fields from table failed!" . mysql_error());
54
showtable.php (cont.)
$fields_num = mysql_num_fields($result);
echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++) {
$field = mysql_fetch_field($result);
echo "<td><b>{$field->name}</b></td>";
}
echo "</tr>n";
while($row = mysql_fetch_row($result)) {
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>n";
}
mysql_free_result($result);
mysql_close($conn);
?>
</body></html>
55
Functions Covered
• mysql_connect() mysql_select_db()
• include()
• mysql_query() mysql_num_rows()
• mysql_fetch_array() mysql_close()
56
PHP Information
The phpinfo() function is used to output PHP information about the version
installed on the server, parameters selected when installed, etc.
<html><head></head>
<!– info.php
<body>
<?php
// Show all PHP information
phpinfo();
?>
<?php
// Show only the general information
phpinfo(INFO_GENERAL);
?>
</body>
</html>
INFO_GENERAL The configuration line,
php.ini location,
build date,
Web Server,
System and more
INFO_CREDITS PHP 4 credits
INFO_CONFIGURATION Local and master values
for php directives
INFO_MODULES Loaded modules
INFO_ENVIRONMENT Environment variable
information
INFO_VARIABLES All predefined variables
from EGPCS
INFO_LICENSE PHP license information
INFO_ALL Shows all of the above (default)
57
Server Variables
The $_SERVER array variable is a reserved variable that contains all server information.
<html><head></head>
<body>
<?php
echo "Referer: " . $_SERVER["HTTP_REFERER"] . "<br />";
echo "Browser: " . $_SERVER["HTTP_USER_AGENT"] . "<br />";
echo "User's IP address: " . $_SERVER["REMOTE_ADDR"];
?>
<?php
echo "<br/><br/><br/>";
echo "<h2>All information</h2>";
foreach ($_SERVER as $key => $value)
{
echo $key . " = " . $value . "<br/>";
}
?>
</body>
</html>
The $_SERVER is a super global variable, i.e. it's available in all scopes of a PHP script.
$_SERVER info
on php.net
58
File Open
The fopen("file_name","mode") function is used to open files in PHP.
<?php
$fh=fopen("welcome.txt","r");
?>
r Read only. r+ Read/Write.
w Write only. w+ Read/Write.
a Append. a+ Read/Append.
x Create and open for write only. x+ Create and open for read/write.
If the fopen() function is unable to open
the specified file, it returns 0 (false).
<?php
if
( !($fh=fopen("welcome.txt","r")) )
exit("Unable to open file!");
?>
For w, and a, if no file exists, it tries to create it
(use with caution, i.e. check that this is the case,
otherwise you’ll overwrite an existing file).
For x if a file exists, this function fails (and
returns 0).
59
File Workings
fclose() closes a
file.
feof() determines if the end is true.
fgetc() reads a single character
<?php
$myFile = "welcome.txt";
if (!($fh=fopen($myFile,'r')))
exit("Unable to open file.");
while (!feof($fh))
{
$x=fgetc($fh);
echo $x;
}
fclose($fh);
?>
<?php
$myFile = "welcome.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>
fgets() reads a line of data
fwrite(), fputs ()
writes a string with and without n
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or
die("can't open file");
$stringData = "New Stuff 1n";
fwrite($fh, $stringData);
$stringData = "New Stuff 2n";
fwrite($fh, $stringData);
fclose($fh);
?>
file() reads entire file into an array
<?php
$lines = file('welcome.txt');
foreach ($lines as $l_num => $line)
{
echo "Line #{$l_num}:“
.$line.”<br/>”;
}
?>
60
Form Handling
Any form element is automatically available via one of the built-in PHP variables (provided that
element has a “name” defined with it).
<html>
<-- form.html -->
<body>
<form action="welcome.php" method="POST">
Enter your name: <input type="text" name="name" /> <br/>
Enter your age: <input type="text" name="age" /> <br/>
<input type="submit" /> <input type="reset" />
</form>
</body>
</html>
<html>
<!–- welcome.php -->
<body>
Welcome <?php echo $_POST["name"].”.”; ?><br />
You are <?php echo $_POST["age"]; ?> years old!
</body>
</html>
$_POST
contains all POST data.
$_GET
contains all GET data.
61
Cookie Workings
setcookie(name,value,expire,path,domain) creates cookies.
<?php
setcookie("uname", $_POST["name"], time()+36000);
?>
<html>
<body>
<p>
Dear <?php echo $_POST["name"] ?>, a cookie was set on this
page! The cookie will be active when the client has sent the
cookie back to the server.
</p>
</body>
</html>
NOTE:
setcookie() must appear
BEFORE <html> (or
any output) as it’s part
of the header
information sent with
the page.
<html>
<body>
<?php
if ( isset($_COOKIE["uname"]) )
echo "Welcome " . $_COOKIE["uname"] . "!<br />";
else
echo "You are not logged in!<br />";
?>
</body>
</html>
use the cookie name as a
variable
isset()
finds out if a cookie is set
$_COOKIE
contains all COOKIE data.
62
Getting Time and Date
date() and time () formats a time or a date.
<?php
//Prints something like: Monday
echo date("l");
//Like: Monday 15th of January 2003 05:51:38 AM
echo date("l jS of F Y h:i:s A");
//Like: Monday the 15th
echo date("l the jS");
?>
date() returns a string
formatted according to the
specified format.
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60secs
echo 'Now: '. date('Y-m-d') ."n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."n";
?>
time() returns
current Unix
timestamp
63
Required Fields in User-Entered
Data
A multipurpose script which asks users for some basic contact information and
then checks to
see that the required fields have been entered.
<html>
<!-- form_checker.php COMP519 -->
<head>
<title>PHP Form example</title>
</head>
<body>
<?php
/*declare some functions*/
function print_form($f_name, $l_name, $email, $os)
{
?>
<form action="form_checker.php" method=“POST">
First Name: <input type="text" name="f_name" value="<?php echo $f_name?>“ /> <br/>
Last Name <b>*</b>:<input type="text" name="l_name" value="<?php echo $l_name?>“ /> <br/>
Email Address <b>*</b>:<input type="text" name="email" value="<?php echo $email?>“ /> <br/>
Operating System: <input type="text" name="os" value="<?php echo $os?>“ /> <br/><br/>
<input type="submit" name="submit" value="Submit“ /> <input type=“reset“ />
</form>
<?php
} //** end of “print_from” function
Print Function
64
Check and Confirm Functions
function check_form($f_name, $l_name, $email, $os)
{
if (!$l_name||!$email){
echo "<h3>You are missing some required fields!</h3>";
print_form($f_name, $l_name, $email, $os);
}
else{
confirm_form($f_name, $l_name, $email, $os);
}
} //** end of “check_form” function
function confirm_form($f_name, $l_name, $email, $os)
{
?>
<h2>Thanks! Below is the information you have sent to us.</h2>
<h3>Contact Info</h3>
<?php
echo "Name: $f_name $l_name <br/>";
echo "Email: $email <br/>";
echo "OS: $os";
} //** end of “confirm_form” function
65
Main Program
/*Main Program*/
if (!$_POST["submit"])
{
?>
<h3>Please enter your information</h3>
<p>Fields with a "<b>*</b>" are required.</p>
<?php
print_form("","","","");
}
else{
check_form($_POST["f_name"],$_POST["l_name"],$_POST["email"],$_POST["os"]);
}
?>
</body>
</html>
66

More Related Content

Similar to Unit 5-PHP Declaring variables, data types, array, string, operators, Expression, control statement, function, Reading data from form controls like text boxes (20)

Basics PHP
Basics PHPBasics PHP
Basics PHP
Alokin Software Pvt Ltd
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
HambardeAtharva
 
Php introduction
Php introductionPhp introduction
Php introduction
krishnapriya Tadepalli
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
SHARANBAJWA
 
Introduction to PHP.pptx
Introduction to PHP.pptxIntroduction to PHP.pptx
Introduction to PHP.pptx
SherinRappai
 
Synapseindia reviews sharing intro on php
Synapseindia reviews sharing intro on phpSynapseindia reviews sharing intro on php
Synapseindia reviews sharing intro on php
SynapseindiaComplaints
 
Synapseindia reviews sharing intro on php
Synapseindia reviews sharing intro on phpSynapseindia reviews sharing intro on php
Synapseindia reviews sharing intro on php
SynapseindiaComplaints
 
PHP ITCS 323
PHP ITCS 323PHP ITCS 323
PHP ITCS 323
Sleepy Head
 
Web Design & Development - Session 7
Web Design & Development - Session 7Web Design & Development - Session 7
Web Design & Development - Session 7
Shahrzad Peyman
 
php.pptx
php.pptxphp.pptx
php.pptx
nusky ahamed
 
Lecture8
Lecture8Lecture8
Lecture8
Majid Taghiloo
 
introduction to php and its uses in daily
introduction to php and its uses in dailyintroduction to php and its uses in daily
introduction to php and its uses in daily
vishal choudhary
 
PHP Programming and its Applications workshop
PHP Programming and its Applications workshopPHP Programming and its Applications workshop
PHP Programming and its Applications workshop
S.Mohideen Badhusha
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.ppt
MercyL2
 
introduction_php.ppt
introduction_php.pptintroduction_php.ppt
introduction_php.ppt
ArunKumar313658
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbai
Vibrant Technologies & Computers
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.ppt
GiyaShefin
 
Web Application Development using PHP Chapter 1
Web Application Development using PHP Chapter 1Web Application Development using PHP Chapter 1
Web Application Development using PHP Chapter 1
Mohd Harris Ahmad Jaal
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
mohamed ashraf
 
05php
05php05php
05php
Shahid Usman
 

Recently uploaded (20)

Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
Quiz Club of PSG College of Arts & Science
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
National Information Standards Organization (NISO)
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
Ad

Unit 5-PHP Declaring variables, data types, array, string, operators, Expression, control statement, function, Reading data from form controls like text boxes

  • 2. PHP Basics: Introduction to PHP • a PHP file, PHP workings, running PHP. ▪ Basic PHP syntax • variables, operators, if...else...and switch, while, do while, and for. ▪ Some useful PHP functions ▪ How to work with • HTML forms, cookies, files, time and date. ▪ How to create a basic checker for user-entered data 2
  • 3. Server-Side Dynamic Web Programming • CGI is one of the most common approaches to server- side programming ▪ Universal support: (almost) Every server supports CGI programming. A great deal of ready-to-use CGI code. Most APIs (Application Programming Interfaces) also allow CGI programming. ▪ Choice of languages: CGI is extremely general, so that programs may be written in nearly any language. Perl is by far the most popular, with the result that many people think that CGI means Perl. But C, C++, Ruby, and Python are also used for CGI programming. ▪ Drawbacks: A separate process is run every time the script is requested. A distinction is made between HTML pages and code. 3
  • 4. • Other server-side alternatives try to avoid the drawbacks ▪ Server-Side Includes (SSI): Code is embedded in HTML pages, and evaluated on the server while the pages are being served. Add dynamically generated content to an existing HTML page, without having to serve the entire page via a CGI program. ▪ Active Server Pages (ASP, Microsoft) : The ASP engine is integrated into the web server so it does not require an additional process. It allows programmers to mix code within HTML pages instead of writing separate programs. (Drawback(?) Must be run on a server using Microsoft server software.) ▪ Java Servlets (Sun): As CGI scripts, they are code that creates documents. These must be compiled as classes which are dynamically loaded by the web server when they are run. ▪ Java Server Pages (JSP): Like ASP, another technology that allows developers to embed Java in web pages. 4
  • 5. PHP • developed in 1995 by Rasmus Lerdorf (member of the Apache Group) ▪ originally designed as a tool for tracking visitors at Lerdorf's Web site ▪ within 2 years, widely used in conjunction with the Apache server ▪ developed into full-featured, scripting language for server-side programming ▪ free, open-source ▪ server plug-ins exist for various servers ▪ now fully integrated to work with mySQL databases • PHP is similar to JavaScript, only it’s a server-side language ▪ PHP code is embedded in HTML using tags ▪ when a page request arrives, the server recognizes PHP content via the file extension (.php or .phtml) ▪ the server executes the PHP code, substitutes output into the HTML page ▪ the resulting page is then downloaded to the client ▪ user never sees the PHP code, only the output in the page 5
  • 6. What do You Need? • Install XAMMP – You don't need to do anything special! * – You don't need to compile anything or install any extra tools! – Create some .php files in your web directory - and the server will parse them for you. * Slightly different rules apply when dealing with an SQL database (as will be explained when we get to that point). 6
  • 7. What is PHP? • PHP == ‘Hypertext Preprocessor’ • 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 • 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 7
  • 8. 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 … ?> 8
  • 9. 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 */ 9
  • 10. 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. 10
  • 11. Constants A constant is an identifier (name) for a simple value. A constant is case-sensitive by default. By convention, constant identifiers are always uppercase. <?php // Valid constant names define("FOO","something"); define("FOO2","something else"); define("FOO_BAR","something more"); // Invalid constant names (they shouldn’t start with a number!) define("2FOO","something"); // This is valid, but should be avoided: // PHP may one day provide a “magical” constant // that will break your script define("__FOO__", "something"); ?> You can access constants anywhere in your script without regard to scope. 11
  • 12. Operators • Arithmetic Operators: +, -, *,/ , %, ++, -- • Assignment Operators: =, +=, -=, *=, /=, %= • Comparison Operators: ==, !=, >, <, >=, <= • Logical Operators: &&, ||, ! • String Operators: . and .= (for string concatenation) Example Is the same as x+=y x=x+y x-=y x=x-y x*=y x=x*y x/=y x=x/y x%=y x=x%y $a = "Hello "; $b = $a . "World!"; // now $b contains "Hello World!" $a = "Hello "; $a .= "World!"; 12
  • 13. Variable usage <?php $foo = 25; // Numerical variable $bar = “Hello”; // String variable $foo = ($foo * 7);// Multiplies foo by 7 $bar = ($bar * 7);// Invalid expression ?> 13
  • 14. Basic PHP syntax A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed (almost) anywhere in an HTML document. <html> <!-- hello.php --> <head><title>Hello World</title></head><body> <p>This is going to be ignored by the PHP interpreter.</p> <?php echo "<p>While this is going to be parsed.</p>"; ?> <p>This will also be ignored by the PHP preprocessor.</p> <?php print(‘<p>Hello and welcome to <i>my</i> page!</p>'); ?> <?php //This is a comment /* This is a comment block*/ ?> </body></html> The server executes the print and echo statements, substitutes output. print and echo for output a semicolon (;) at the end of each statement // for a single-line comment /* and */ for a large comment block. 14
  • 15. Scalars All variables in PHP start with a $ sign symbol. A variable's type is determined by the context in which that variable is used (i.e. there is no strong-typing in PHP). <html><head></head> <!-- scalars.php --><body> <p> <?php $foo = true; if ($foo) echo "It is TRUE! <br /> n"; $txt='1234'; echo "$txt <br /> n"; $a = 1234; echo "$a <br /> n"; $a = -123; echo "$a <br /> n"; $a = 1.234; echo "$a <br /> n"; $a = 1.2e3; echo "$a <br /> n"; $a = 7E-10; echo "$a <br /> n"; echo 'Arnold once said: "I'll be back"', "<br /> n"; $snist = 'Sreenidhi Institute of Science and Technology <br/>'; echo "Rahul studies in $snist"; $str1 = <<<EODTrue Example of string spanning multiple lines using "heredoc" syntax. uses the angular brackets... EODTrue; echo $str1,'<br/>'; ?> </p></body></html> Four scalar types: boolean true or false integer, float, floating point numbers string single quoted double quoted 15
  • 16. 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 16
  • 17. Echo example • Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with 25 • PHP won't use additional processing to interpret what is inside the single quote. • When you use double quotes PHP has to parse to check if there are any variables within the string. • This is true for both variables and character escape-sequences (such as “n” or “”) <?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 ?> 17
  • 18. Arithmetic 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 ?> 18
  • 19. Concatenation • Use a period to join strings into one. <?php $string1=“Hello”; $string2=“PHP”; $string3=$string1 . “ ” . $string2; Print $string3; ?> Hello PHP 19
  • 20. 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” 20
  • 21. 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; } 21
  • 22. If ... Else... • If (condition) { Statements; } Else { Statement; } <?php If($user==“John”) { Print “Hello John.”; } Else { Print “You are not John.”; } ?> No THEN in PHP 22
  • 23. Conditionals: if else (Can execute a set of code depending on a condition) <html><head></head> <!-- if-cond.php --> <body> <?php $d=date("D"); echo $d, “<br/>”; if ($d=="Fri") echo "Have a nice weekend! <br/>"; else echo "Have a nice day! <br/>"; $x=10; if ($x==10) { echo "Hello<br />"; echo "Good morning<br />"; } ?> </body></html> if (condition) code to be executed if condition is true; else code to be executed if condition is false; date() is a built-in PHP function that can be called with many different parameters to return the date (and/or local time) in various formats In this case we get a three letter string for the day of the week. 23
  • 24. Conditionals: switch Can select one of many sets of lines to execute <html><head></head><body> <!–- switch-cond.php --> <?php $x = rand(1,5); // random integer echo “x = $x <br/><br/>”; switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; break; } ?></body></html> switch (expression) { case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break; default: code to be executed if expression is different from both label1 and label2; break; } 24
  • 25. While 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
  • 26. Arrays In PHP, there are three types of arrays: 1. Indexed arrays - Arrays with a numeric index 2. Associative arrays - Arrays with named keys 3. Multidimensional arrays - Arrays containing one or more arrays 26
  • 27. Looping: for and foreach Can loop depending on a "counter" <?php for ($i=1; $i<=5; $i++) { echo "Hello World!<br />"; } ?> loops through a block of code a specified number of times <?php $a_array = array(1, 2, 3, 4); foreach ($a_array as $value) { $value = $value * 2; echo “$value <br/> n”; } ?> loops through a block of code for each element in an array <?php $a_array=array("a","b","c"); foreach ($a_array as $key => $value) { echo $key." = ".$value."n"; } ?> 27
  • 28. Arrays An array in PHP is actually an ordered map. A map is a type that maps values to keys. array() = creates arrays <?php $arr = array("foo" => "bar", 12 => true); echo $arr["foo"]; // bar echo $arr[12]; // 1 ?> key = either an integer or a string. value = any PHP type. <?php array(5 => 43, 32, 56, "b" => 12); array(5 => 43, 6 => 32, 7 => 56, "b" => 12); ?> if no key given (as in example), the PHP interpreter uses (maximum of the integer indices + 1). if an existing key, its value will be overwritten. <?php $arr = array(5 => 1, 12 => 2); foreach ($arr as $key => $value) { echo $key, ‘=>’, $value); } $arr[] = 56; // the same as $arr[13] = 56; $arr["x"] = 42; // adds a new element unset($arr[5]); // removes the element unset($arr); // deletes the whole array $a = array(1 => 'one', 2 => 'two', 3 => 'three'); unset($a[2]); $b = array_values($a); ?> can set values in an array unset() removes a key/value pair *Find more on arrays array_values() makes reindexing effect (indexing numerically) 28
  • 29. Using print_r() and array_values() <html><body> <?php $a=array("Name"=>"SNIST","Year Started"=>"1997", "Country"=>"India"); print_r(array_values($a)); ?> </body></html> Array ( [0] => SNIST [1] => 1997 [2] => India ) 29
  • 30. Date Display $datedisplay=date(“yyyy/m/d”); Print $datedisplay; # If the date is June 25th, 2012 # It would display as 2012/6/25 2012/25/6 $datedisplay=date(“l, F j, Y”); Print $datedisplay; # If the date is June 25th ,2012 # Monday, June 25th,2012 Monday, June 25, 2012 Refer the different notation of date: https://www.w3schools.com/php/func_date_date_format.asp 30
  • 31. Month, 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 31
  • 32. Functions • 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) 32
  • 33. 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 ?> 33
  • 34. User Defined Functions Can define a function using syntax such as the following: <?php function foo($arg_1, $arg_2, /* ..., */ $arg_n) { echo "Example function.n"; return $retval; } ?> Can also define conditional functions, functions within functions, and recursive functions. <?php function square($num) { return $num * $num; } echo square(4); ?> <?php function small_numbers() { return array (0, 1, 2); } list ($zero, $one, $two) = small_numbers(); echo $zero, $one, $two; ?> Can return a value of any type <?php function takes_array($input) { echo "$input[0] + $input[1] = ", $input[0]+$input[1]; } takes_array(array(1,2)); ?> 34
  • 35. Variable Scope The scope of a variable is the context within which it is defined. <?php $a = 1; /* limited variable scope */ function Test() { echo $a; /* reference to local scope variable */ } Test(); ?> The scope is local within functions, and hence the value of $a is undefined in the “echo” statement. <?php $a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } Sum(); echo $b; ?> global refers to its global version. <?php function Test1() { static $a = 0; echo $a; $a++; } Test1(); Test1(); Test1(); ?> static does not lose its value. Output: 012 35
  • 36. Including Files The include() statement includes and evaluates the specified file. vars.php <?php $color = 'green'; $fruit = 'apple'; ?> test.php <?php echo "A $color $fruit"; // A include 'vars.php'; echo "A $color $fruit"; // A green apple ?> *The scope of variables in “included” files depends on where the “include” file is added! You can use the include_once, require, and require_once statements in similar ways. test3.php <?php function foo() { global $color; include ('vars.php'); echo "A $color $fruit"; } /* vars.php is in the scope of foo() so $fruit is NOT available outside of this scope. $color is because we declared it as global. */ foo(); // A green apple echo "A $color $fruit"; // A green ?> 36
  • 37. 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 © 2001-2012 gsu</i></font><br> <i>ALL RIGHTS RESERVED</i></font><br> <i>URL: http://www.gsu.edu.edu</i></font><br> 37
  • 38. PHP Program for File Upload <!– index.html -- > <html><body> <form action="uploader.php" method="post" enctype="multipart/form- data"> Select File: <input type="file" name="fileToUpload"/> <input type="submit" value="Upload File" name="submit"/> </form> </body></html> 38 When you make a POST request, you have to encode the data that forms the body of the request in some way. HTML forms provide three methods of encoding: 1. application/x-www-form-urlencoded 🡪the default 2. multipart/form-data 🡪 Use this when <input type="file"> is present 3. text/plain 🡪 Never use this.
  • 39. uploader.php program <!-- uploader.php --> <?php $target_path = "I:AAAphpFileUploads/"; //destination folder $target_path = $target_path.basename( $_FILES['fileToUpload']['name']); if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) { echo "File uploaded successfully!"; } else{ echo "Sorry, file not uploaded, please try again!"; } ?> 39 move_uploaded_file() function: move an uploaded file to new location. If the filename is not a valid upload file or cannot be moved for a reason, then no action can occur and return false. bool move_uploaded_file ( string $filename , string $destination )
  • 40. 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> 40
  • 41. Setting a Cookie: setcookie(name, value, expire, path, domain, secure, httponly); <?php $cookie_name = "user"; $cookie_value = "John Doe"; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day ?> <html> <body> <?php if(!isset($_COOKIE[$cookie_name])) { echo "Cookie named '" . $cookie_name . "' is not set!"; } else { echo "Cookie '" . $cookie_name . "' is set!<br>"; echo "Value is: " . $_COOKIE[$cookie_name]; } ?> </body> </html> 41
  • 42. 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. 42
  • 43. 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> 43
  • 44. Avoid Error PHP - Sessions PHP Example: <?php echo "Look at this nasty error below:<br />"; session_start(); ?> Error! PHP Example: <?php session_start(); echo "Look at this nasty error below:"; ?> Correct 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 44
  • 45. 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(): 45
  • 46. 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>"; } ?> 46
  • 47. 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. 47
  • 48. 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. 48
  • 49. • 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> First PHP script 49
  • 50. Example of parameter reading • Consider: • contents of php_exec/form.php... • <html><body> • <h1>Hi there</h1> • <? if (!isset($_POST['foo'])): ?> • <h1>'foo' is not set</h1> • <? elseif (!is_array($_POST['foo'])) : ?> • <h1>'foo' has one value <?= $_POST['foo'] ?> </h1> • <? else: ?> • <h1>'foo' has multiple values <?= join(',',$_POST['foo']) ?> </h1> • <? endif ?> • </body></html> • ...end of php_exec/form.php • Call with form: • contents of php_exec/form01.txt... <form action='php_exec/form.php' method='post'> <ul> <li> <input type='checkbox' name='foo[]' value='raisins'> raisins. <li> <input type='checkbox' name='foo[]' value='cranberries'> cranberries. <li> <input type='checkbox' name='foo[]' value='plums'> plums. </ul> <input type='submit'> </form> ...end of php_exec/form01.txt • Here is what it looks like: – raisins. – cranberries. – plums. 50
  • 51. Example – show data in the tables • Function: list all tables in your database. Users can select one of tables, and show all contents in this table. • second.php • showtable.php 51
  • 52. second.php <html><head><title>MySQL Table Viewer</title></head><body> <?php // change the value of $dbuser and $dbpass to your username and password $dbhost = ‘ codd.cs…….. '; $dbuser = 'nruan'; $dbpass = ‘*****************’; $dbname = $dbuser; $table = 'account'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if (!$conn) { die('Could not connect: ' . mysql_error()); } if (!mysql_select_db($dbname)) die("Can't select database"); 52
  • 53. second.php (cont.) $result = mysql_query("SHOW TABLES"); if (!$result) { die("Query to show fields from table failed"); } $num_row = mysql_num_rows($result); echo "<h1>Choose one table:<h1>"; echo "<form action="showtable.php" method="POST">"; echo "<select name="table" size="1" Font size="+2">"; for($i=0; $i<$num_row; $i++) { $tablename=mysql_fetch_row($result); echo "<option value="{$tablename[0]}" >{$tablename[0]}</option>"; } echo "</select>"; echo "<div><input type="submit" value="submit"></div>"; echo "</form>"; mysql_free_result($result); mysql_close($conn); ?> </body></html> 53
  • 54. showtable.php <html><head> <title>MySQL Table Viewer</title> </head> <body> <?php $dbhost = 'hercules.cs.kent.edu:3306'; $dbuser = 'nruan'; $dbpass = ‘**********’; $dbname = 'nruan'; $table = $_POST[“table”]; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if (!$conn) die('Could not connect: ' . mysql_error()); if (!mysql_select_db($dbname)) die("Can't select database"); $result = mysql_query("SELECT * FROM {$table}"); if (!$result) die("Query to show fields from table failed!" . mysql_error()); 54
  • 55. showtable.php (cont.) $fields_num = mysql_num_fields($result); echo "<h1>Table: {$table}</h1>"; echo "<table border='1'><tr>"; // printing table headers for($i=0; $i<$fields_num; $i++) { $field = mysql_fetch_field($result); echo "<td><b>{$field->name}</b></td>"; } echo "</tr>n"; while($row = mysql_fetch_row($result)) { echo "<tr>"; // $row is array... foreach( .. ) puts every element // of $row to $cell variable foreach($row as $cell) echo "<td>$cell</td>"; echo "</tr>n"; } mysql_free_result($result); mysql_close($conn); ?> </body></html> 55
  • 56. Functions Covered • mysql_connect() mysql_select_db() • include() • mysql_query() mysql_num_rows() • mysql_fetch_array() mysql_close() 56
  • 57. PHP Information The phpinfo() function is used to output PHP information about the version installed on the server, parameters selected when installed, etc. <html><head></head> <!– info.php <body> <?php // Show all PHP information phpinfo(); ?> <?php // Show only the general information phpinfo(INFO_GENERAL); ?> </body> </html> INFO_GENERAL The configuration line, php.ini location, build date, Web Server, System and more INFO_CREDITS PHP 4 credits INFO_CONFIGURATION Local and master values for php directives INFO_MODULES Loaded modules INFO_ENVIRONMENT Environment variable information INFO_VARIABLES All predefined variables from EGPCS INFO_LICENSE PHP license information INFO_ALL Shows all of the above (default) 57
  • 58. Server Variables The $_SERVER array variable is a reserved variable that contains all server information. <html><head></head> <body> <?php echo "Referer: " . $_SERVER["HTTP_REFERER"] . "<br />"; echo "Browser: " . $_SERVER["HTTP_USER_AGENT"] . "<br />"; echo "User's IP address: " . $_SERVER["REMOTE_ADDR"]; ?> <?php echo "<br/><br/><br/>"; echo "<h2>All information</h2>"; foreach ($_SERVER as $key => $value) { echo $key . " = " . $value . "<br/>"; } ?> </body> </html> The $_SERVER is a super global variable, i.e. it's available in all scopes of a PHP script. $_SERVER info on php.net 58
  • 59. File Open The fopen("file_name","mode") function is used to open files in PHP. <?php $fh=fopen("welcome.txt","r"); ?> r Read only. r+ Read/Write. w Write only. w+ Read/Write. a Append. a+ Read/Append. x Create and open for write only. x+ Create and open for read/write. If the fopen() function is unable to open the specified file, it returns 0 (false). <?php if ( !($fh=fopen("welcome.txt","r")) ) exit("Unable to open file!"); ?> For w, and a, if no file exists, it tries to create it (use with caution, i.e. check that this is the case, otherwise you’ll overwrite an existing file). For x if a file exists, this function fails (and returns 0). 59
  • 60. File Workings fclose() closes a file. feof() determines if the end is true. fgetc() reads a single character <?php $myFile = "welcome.txt"; if (!($fh=fopen($myFile,'r'))) exit("Unable to open file."); while (!feof($fh)) { $x=fgetc($fh); echo $x; } fclose($fh); ?> <?php $myFile = "welcome.txt"; $fh = fopen($myFile, 'r'); $theData = fgets($fh); fclose($fh); echo $theData; ?> fgets() reads a line of data fwrite(), fputs () writes a string with and without n <?php $myFile = "testFile.txt"; $fh = fopen($myFile, 'a') or die("can't open file"); $stringData = "New Stuff 1n"; fwrite($fh, $stringData); $stringData = "New Stuff 2n"; fwrite($fh, $stringData); fclose($fh); ?> file() reads entire file into an array <?php $lines = file('welcome.txt'); foreach ($lines as $l_num => $line) { echo "Line #{$l_num}:“ .$line.”<br/>”; } ?> 60
  • 61. Form Handling Any form element is automatically available via one of the built-in PHP variables (provided that element has a “name” defined with it). <html> <-- form.html --> <body> <form action="welcome.php" method="POST"> Enter your name: <input type="text" name="name" /> <br/> Enter your age: <input type="text" name="age" /> <br/> <input type="submit" /> <input type="reset" /> </form> </body> </html> <html> <!–- welcome.php --> <body> Welcome <?php echo $_POST["name"].”.”; ?><br /> You are <?php echo $_POST["age"]; ?> years old! </body> </html> $_POST contains all POST data. $_GET contains all GET data. 61
  • 62. Cookie Workings setcookie(name,value,expire,path,domain) creates cookies. <?php setcookie("uname", $_POST["name"], time()+36000); ?> <html> <body> <p> Dear <?php echo $_POST["name"] ?>, a cookie was set on this page! The cookie will be active when the client has sent the cookie back to the server. </p> </body> </html> NOTE: setcookie() must appear BEFORE <html> (or any output) as it’s part of the header information sent with the page. <html> <body> <?php if ( isset($_COOKIE["uname"]) ) echo "Welcome " . $_COOKIE["uname"] . "!<br />"; else echo "You are not logged in!<br />"; ?> </body> </html> use the cookie name as a variable isset() finds out if a cookie is set $_COOKIE contains all COOKIE data. 62
  • 63. Getting Time and Date date() and time () formats a time or a date. <?php //Prints something like: Monday echo date("l"); //Like: Monday 15th of January 2003 05:51:38 AM echo date("l jS of F Y h:i:s A"); //Like: Monday the 15th echo date("l the jS"); ?> date() returns a string formatted according to the specified format. <?php $nextWeek = time() + (7 * 24 * 60 * 60); // 7 days; 24 hours; 60 mins; 60secs echo 'Now: '. date('Y-m-d') ."n"; echo 'Next Week: '. date('Y-m-d', $nextWeek) ."n"; ?> time() returns current Unix timestamp 63
  • 64. Required Fields in User-Entered Data A multipurpose script which asks users for some basic contact information and then checks to see that the required fields have been entered. <html> <!-- form_checker.php COMP519 --> <head> <title>PHP Form example</title> </head> <body> <?php /*declare some functions*/ function print_form($f_name, $l_name, $email, $os) { ?> <form action="form_checker.php" method=“POST"> First Name: <input type="text" name="f_name" value="<?php echo $f_name?>“ /> <br/> Last Name <b>*</b>:<input type="text" name="l_name" value="<?php echo $l_name?>“ /> <br/> Email Address <b>*</b>:<input type="text" name="email" value="<?php echo $email?>“ /> <br/> Operating System: <input type="text" name="os" value="<?php echo $os?>“ /> <br/><br/> <input type="submit" name="submit" value="Submit“ /> <input type=“reset“ /> </form> <?php } //** end of “print_from” function Print Function 64
  • 65. Check and Confirm Functions function check_form($f_name, $l_name, $email, $os) { if (!$l_name||!$email){ echo "<h3>You are missing some required fields!</h3>"; print_form($f_name, $l_name, $email, $os); } else{ confirm_form($f_name, $l_name, $email, $os); } } //** end of “check_form” function function confirm_form($f_name, $l_name, $email, $os) { ?> <h2>Thanks! Below is the information you have sent to us.</h2> <h3>Contact Info</h3> <?php echo "Name: $f_name $l_name <br/>"; echo "Email: $email <br/>"; echo "OS: $os"; } //** end of “confirm_form” function 65
  • 66. Main Program /*Main Program*/ if (!$_POST["submit"]) { ?> <h3>Please enter your information</h3> <p>Fields with a "<b>*</b>" are required.</p> <?php print_form("","","",""); } else{ check_form($_POST["f_name"],$_POST["l_name"],$_POST["email"],$_POST["os"]); } ?> </body> </html> 66