Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
45 views

Lecture 3 PHP

PHP is a server-side scripting language commonly used for web development. It allows developers to add dynamic content to websites. Some key points: - PHP code is embedded into HTML and executed on the server to generate output. This output is then sent to the browser. - PHP supports many databases and is compatible with popular servers like Apache. It can run on various platforms. - PHP files have a .php extension and can contain text, HTML tags, and PHP scripts. Variables, functions, and other programming elements can be used. - Common control structures include if/else statements, loops like while and for, and switch statements to control program flow. Arrays are used to store multiple values.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Lecture 3 PHP

PHP is a server-side scripting language commonly used for web development. It allows developers to add dynamic content to websites. Some key points: - PHP code is embedded into HTML and executed on the server to generate output. This output is then sent to the browser. - PHP supports many databases and is compatible with popular servers like Apache. It can run on various platforms. - PHP files have a .php extension and can contain text, HTML tags, and PHP scripts. Variables, functions, and other programming elements can be used. - Common control structures include if/else statements, loops like while and for, and switch statements to control program flow. Arrays are used to store multiple values.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 66

What is PHP?

PHP stands for PHP: Hypertext Preprocessor


PHP is a server-side scripting language, like
ASP
PHP scripts are executed on the server
PHP supports many databases (MySQL,
Informix, Oracle, Sybase, Solid, PostgreSQL,
Generic ODBC, etc.)
PHP is an open source software
PHP is free to download and use
What is a PHP File?
PHP files can contain text, HTML tags
and scripts
PHP files are returned to the browser as
plain HTML 
PHP files have a file extension of ".php",
".php3", or ".phtml"
Why PHP?
PHP runs on different platforms
(Windows, Linux, Unix, etc.)
PHP is compatible with almost all servers
used today (Apache, IIS, etc.)
PHP is FREE to download from the
official PHP resource: www.php.net
PHP is easy to learn and runs efficiently
on the server side
PHP Syntax
PHP code is executed on the server, and the
plain HTML result is sent to the browser.
A PHP scripting block always starts with <?
php and ends with ?>. A PHP scripting block
can be placed anywhere in the document.
On servers with shorthand support enabled
you can start a scripting block with <? and end
with ?>.
There are two basic statements to output text with
PHP: echo and print. In the example above we have used
the echo statement to output the text "Hello World".
<html>
<body>
//hellow
<?php
echo "Hello World";
?>

</body>
</html>
Variables in PHP
 All variables in PHP start with a $ sign symbol.
 $var_name = value;
 <?php
$txt="Hello World!";
$x=16;
?>
 PHP is a Loosely Typed Language
 In PHP, a variable does not need to be declared before adding a value to it.
 In the example above, you see that you do not have to tell PHP which data
type the variable is.
 PHP automatically converts the variable to the correct data type,
depending on its value.
 In a strongly typed programming language, you have to declare (define)
the type and name of the variable before using it.
 In PHP, the variable is declared automatically when you use it.
Naming Rules for Variables
A variable name must start with a letter or an
underscore "_"
A variable name can only contain alpha-
numeric characters and underscores (a-z, A-Z,
0-9, and _ )
A variable name should not contain spaces. If
a variable name is more than one word, it
should be separated with an underscore
($my_string), or with capitalization
($myString)
String Variables in PHP
String variables are used for values that
contains characters.
In this chapter we are going to look at the
most common functions and operators used
to manipulate strings in PHP.
After we create a string we can manipulate it.
A string can be used directly in a function or
it can be stored in a variable.
<?php
$txt="Hello World";
echo $txt;
?>
The Concatenation Operator
The concatenation operator (.)  is used to
put two string values together.
<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?>
The strlen() function
<?php
echo strlen("Hello world!");
?>
The strpos() function is used to search for
character within a string.
If a match is found, this function will return
the position of the first match. If no match is
found, it will return FALSE.
<?php
echo strpos("Hello world!","world");
?>
PHP Operators

Operator Description Example Result


+ Addition x=2 4
x+2
- Subtraction x=2 3
5-x
* Multiplication x=4 20
x*5
/ Division 15/5 3
5/2 2.5
% Modulus (division remainder) 5%2 1
10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
Assignment operators
Operator Example Is The Same As
= x=y x=y
+= 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
%= x%=y x=x%y
Comparison and logical operators
perator Description Example
== is equal to 5==8 returns false
!= is not equal 5!=8 returns true
<> is not equal 5<>8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to 5>=8 returns false
<= is less than or equal to 5<=8 returns true

Operator Description Example


&& and x=6
y=3

(x < 10 && y > 1) returns true


|| or x=6
y=3

(x==5 || y==5) returns false


! not x=6
y=3

!(x==y) returns true


PHP If...Else Statements
 The if Statement
 if (condition) code to be executed if condition is true;
 <html>
<body>

<?php
$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
?>

</body>
</html>
The if...else Statement
 if (condition)
  code to be executed if condition is true;
else
  code to be executed if condition is false;
 <html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
  echo "Have a nice weekend!";
else
  echo "Have a nice day!";
?>
</body>
</html>
 <html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
  {
  echo "Hello!<br />";
  echo "Have a nice weekend!";
  echo "See you on Monday!";
  }
?>
</body>
</html>
The if...elseif....else  Statement
 if (condition)
  code to be executed if condition is true;
elseif (condition)
  code to be executed if condition is true;
else
  code to be executed if condition is false;
 <html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
  echo "Have a nice weekend!";
elseif ($d=="Sun")
  echo "Have a nice Sunday!";
else
  echo "Have a nice day!";
?>
</body>
</html>
The PHP Switch Statement
switch (n)
{
case label1:
  code to be executed if n=label1;
  break;
case label2:
  code to be executed if n=label2;
  break;
default:
  code to be executed if n is different from
both label1 and label2;
}
<html>
<body>
<?php
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";
}
?>
</body>
</html>
The while Loop
 while (condition)
 {
  code to be executed;
 }
 <html>
<body>
<?php
$i=1;
while($i<=5)
  {
  echo "The number is " . $i . "<br />";
  $i++;
  }
?>
</body>
</html>
The do...while Statement
 do
 {
  code to be executed;
  }
while (condition);
 <html>
<body>
<?php
$i=1;
do
  {
  $i++;
  echo "The number is " . $i . "<br />";
  }
while ($i<=5);
?>
</body>
</html>
The for Loop
 for (init; condition; increment)
 {
  code to be executed;
 }
 <html>
<body>
<?php
for ($i=1; $i<=5; $i++)
 {
  echo "The number is " . $i . "<br />";
 }
?>
</body>
</html>
The foreach loop is used to loop through arrays.
 foreach ($array as $value)
 {
  code to be executed;
 }
 <html>
<body>
<?php
$x=array("one","two","three");
foreach ($x as $value)
 {
  echo $value . "<br />";
 }
?>
</body>
</html>
PHP Arrays
In PHP, there are three kind of arrays:
Numeric array - An array with a numeric
index
Associative array - An array where each ID
key is associated with a value
Multidimensional array - An array
containing one or more arrays
Numeric Arrays
$cars=array("Saab","Volvo","BMW","Toyota");
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
<?php
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota"; 
echo $cars[0] . " and " . $cars[1] . " are Swedish
cars.";
?>
Associative Arrays
each ID key is associated with a value.
$ages = array("Peter"=>32, "Quagmire"=>30,
"Joe"=>34);
<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";

echo "Peter is " . $ages['Peter'] . " years old.";


?>
Multidimensional Arrays
$families = array
  (
  "Griffin"=>array  (  "Peter", "Lois","Megan"  ),
  "Quagmire"=>array ( "Glenn"  ),
  "Brown"=>array  ("Cleveland", "Loretta", "Junior")
  );
echo "Is " . $families['Griffin'][2] . 
" a part of the Griffin family?";
Output=Is Megan a part of the Griffin family?
PHP Functions
 function functionName()
{
code to be executed;
}
 <html>
<body>
<?php
function writeName()
{
echo “james";
}
echo "My name is ";
writeName();
?>
</body>
</html>
Adding parameters
 <html>
<body>
<?php
function writeName($fname)
{
echo $fname . " Refsnes.<br />";
}
echo "My name is ";
writeName("Kai Jim");
echo "My sister's name is ";
writeName("Hege");
echo "My brother's name is ";
writeName("Stale");
?>
</body>
</html>
 <html>
<body>
<?php
function writeName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br />";
}
echo "My name is ";
writeName("Kai Jim",".");
echo "My sister's name is ";
writeName("Hege","!");
echo "My brother's name is ";
writeName("Ståle","?");
?>
</body>
</html>
PHP Functions - Return values
 <html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
PHP Forms and User Input
 <html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
 When a user fills out the form above and click on the submit button, the
form data is sent to a PHP file, called "welcome.php":
 <html>
<body>
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
PHP $_GET Function
 The built-in $_GET function is used to collect values from
a form sent with method="get".
 Information sent from a form with the GET method is
visible to everyone (it will be displayed in the browser's
address bar) and has limits on the amount of information to
send.
 When to use method="get"?
 When using method="get" in HTML forms, all variable
names and values are displayed in the URL.
 Note: This method should not be used when sending
passwords or other sensitive information!
 However, because the variables are displayed in the URL,
it is possible to bookmark the page. This can be useful in
some cases.
 Note: The get method is not suitable for very large variable
values.
PHP $_POST Function
The built-in $_POST function is used to collect values
from a form sent with method="post".
Information sent from a form with the POST method is
invisible to others and has no limits on the amount of
information to send.
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.
When to use method="post"?
Information sent from a form with the
POST method is invisible to others and
has no limits on the amount of
information to send.
However, because the variables are not
displayed in the URL, it is not possible to
bookmark the page.
PHP Date Function
date(format, timestamp)
format - Always required. Specifies the format of
the timestamp
timestamp - Optional. Specify UNIX time stamp.
If not passed, the current timestamp is used.
Here are some characters that can be used:
d - Represents the day of the month (01 to 31)
m - Represents a month (01 to 12)
Y - Represents a year (in four digits)
<?php
echo date("Y/m/d") . "<br />";
echo date("Y.m.d") . "<br />";
echo date("Y-m-d")
?>
2010/12/20
2010.12.20
2010-12-20
What is a cookie?
A cookie is often used to store data which
can be used to identify a user, for
example, person's username.
Cookie is a small flat file which sits on
user’s computer. Each time that user
requests a page or goes to a webpage, all
cookie information is sent too. This is
used to identify who you are.
How to Create a Cookie?
 The setcookie() function is used to set a cookie.
 Note: The setcookie() function must appear BEFORE the <html> tag.
Syntax: setcookie(name, value, expire, path, domain);
 $name - name of the cookie. Example: "username"
 $value - value of the cookie. Example: "john"
 $expire - time (in UNIX timestamp) when the cookie will expire. Example:
time()+"3600". Cookie is set to expire after one hour.
 $path - path on the server where cookie will be available.
For example, if the path is set to "/", the cookie will be available through out the
whole site. If the cookie is set to say "/news/", the cookie will only be available
under /news/ and all its sub-directories.
If no path is given, cookie in created under the current directory.
 $domain - domain where cookie will be available. Instead of path you can use
domain settings.
For example, if the domian is set to ".yourdomian.com", the cookie will be
available within the domain nd all its sub-domains, example
news.yourdomain.com.
If the cookie is set say "www.yourdomian.com" the cookie will be available
under all www sub-domains, example " www.yourdomian.com/news“
<?php setcookie("username", "john", time()+3600); ?
> <html> <body> </body> </html>
<?php setcookie("username", "john", time() +
(60*60*24*365));
?>
The PHP $_COOKIE variable is used to retrieve a
cookie value.
<?php echo $_COOKIE["username"]; ?>
Will print “john”
print the entire $_COOKIE array
<?php echo "<pre>"; print_r($_COOKIE);
echo "</pre>"; ?>
Array ( [username] => john )
Deleting a Cookie:
<?php setcookie("username", "john",
time()-(60*60*24*365)); ?>
PHP Sessions
 Sessions are used to store information which can be used
through-out the application for the entire time the user is logged
in or running the application. Each time a user visits your
website, you can create a session for that user to store
information pertaining to that user.
 Unlike other applications, in web applications, all the stored
variables and objects are not globally available throughout all
pages (unless sent through POST or GET methods to the next
page), so to tackle this problem sessions are utilized.
 A usage of sessions would be for example, storing products in a
shopping cart. On your favorite merchant site, when you, the
user, clicks on "add to shopping cart", the product information
is then stored in a session (using session variables) which is
then available on the server for later use for the entire the time
you browse the website.
<?php session_start(); ?>
<html>
<body>
</body>
</html>
When you start a session a unique session id
(PHPSESSID) for each visitor/user is created. You
can access the session id using the PHP predefined
constant PHPSESSID.
The code above starts a session for the user on the
server, and assign a session id for that user's
session.
Storing information in a session
<?php session_start();
$_SESSION["username"] = "johny";
$_SESSION["color"] = "blue"; ?>
Retrieving stored session information
<?php session_start();
echo $_SESSION["username"];
echo "<br/>";
echo $_SESSION["color"]; ?>
Destroying/deleting session information
Remember sessions are destroyed automatically
after user leaves your website or closes the
browser, but if you wish to clear a session variable
yourself, you can simple use the unset() function to
clean the session variable.
<?php session_start();
unset($_SESSION["username"]);
unset($_SESSION["color"]); ?>
<?php session_destroy(); ?> destroy all session
variables in one go,
Difference  between Session and Cookie
 If you set the variable to "cookies", then your users  will not have
to log in each time they enter your community.
 The cookie will stay in place within the user’s browser until it is
deleted by the user.
 But Sessions are popularly used, as there is a chance of your
cookies getting blocked if the user browser security setting is set
high.
 If you set the variable to "sessions", then user activity will be
tracked using browser sessions, and your users will have to log in
each time they re-open their browser. Additionally, if you are
using the "sessions" variable, you need to secure the "sessions"
directory, either by placing it above the web root or by requesting
that your web host make it a non-browsable directory.
 The Key difference would be cookies are stored in your hard disk
whereas a session aren't stored in your hard disk. Sessions are
basically like tokens, which are generated at authentication. A
session is available as long as the browser is opened.
PHP: Multidimensional Arrays
Title Price Number
rose 1.25 15
Daisy 0.75 25
Orchid 1.15 7
<?php 
$shop =array( array("rose", 1.25 , 15),
              array("daisy", 0.75 , 25),
                array("orchid", 1.15 , 7) 
             ); 
?>
<?php 
$shop = array( array( Title => "rose", 
                      Price => 1.25,
                      Number => 15 
                    ),
               array( Title => "daisy", 
                      Price => 0.75,
                      Number => 25,
                    ),
               array( Title => "orchid", 
                      Price => 1.15,
                      Number => 7 
                    )
             );
?>
Three-dimensional Arrays
Each element can be referenced by its layer, row,
and column.
<?php 
$shop = array( array(array("rose", 1.25, 15),
                     array("daisy", 0.75, 25),
                     array("orchid", 1.15, 7) 
                   ),
              array( array("rose", 1.25, 15),
                    array("daisy", 0.75, 25),
                    array("orchid", 1.15, 7) 
                   ),
              array( array("rose", 1.25, 15),
                    array("daisy", 0.75, 25),
                     array("orchid", 1.15, 7) 
                   )
             );
?>
PHP implode() Function
implode(separator,array),  returns a string
from the elements of an array.
<?php
$arr =
array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
?>
PHP explode() Function
explode(separator,string,limit), breaks a string
into an array.
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
PHP File Handling
how to create a file?
$ourFileName = "testFile.txt";
$fileptr = fopen($ourFileName, 'w') or
exit("Unable to open file!");
fclose($fileptr);
The file opening modes:
 Modes Description
 r Read only. Starts at the beginning of the file
 r+ Read/Write. Starts at the beginning of the file
 w Write only. Opens and clears the contents of file; or
creates a new file if it doesn't exist
 w+ Read/Write. Opens and clears the contents of file; or
creates a new file if it doesn't exist
 a Append. Opens and writes to the end of the file or
creates a new file if it doesn't exist
 a+ Read/Append. Preserves file content by writing to the end
of the file
 x Write only. Creates a new file. Returns FALSE and an
error if file already exists
 x+ Read/Write. Creates a new file. Returns FALSE and an
error if file already exists
The feof() function checks if the "end-of-file"
(EOF) has been reached. Syntax: feof(file)
The fgets() function is used to read a single line
from a file. Syntax : fgets(file,length), length is in
bytes.
The fgetc() function is used to read a single
character from a file. Syntax: fgetc(file)
The file_exists() function checks whether or not a
file or directory exists.
The filesize() function returns the size of the
specified file.
The fread() reads from an open file.
fread(file,length)
The fseek() function seeks in an open file.
fseek(file,offset,whence)
SEEK_SET - Set position equal to offset. Default
SEEK_CUR - Set position to current location plus
offset
SEEK_END - Set position to EOF plus offset
The ftell() function returns the current position in
an open file
exit(),and die(): Terminates execution of the script
<?php
$file = fopen("test.txt","r");

// print current position


echo ftell($file);

// change current position


fseek($file,"15");

// print current position again


echo "<br />" . ftell($file);

fclose($file);
?>
The fwrite() writes to an open file.
The function will stop at the end of the file or
when it reaches the specified length, whichever
comes first.
This function returns the number of bytes
written, or FALSE on failure.
fwrite(file,string,length)
The fputs() writes to an open file.
fputs(file,string,length)
Php file creation
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or exit("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);
?>
Read the file

$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
Append data in php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open
file");
$stringData = "New Stuff 1\n"; fwrite($fh,
$stringData);
$stringData = "New Stuff 2\n"; fwrite($fh,
$stringData);
fclose($fh);

You might also like