0% found this document useful (0 votes)
6 views

Chapter 1_Php Language

This document outlines a course on PHP language, detailing objectives, assessments, and fundamental concepts of web programming. It covers topics such as client-server models, PHP syntax, variables, arrays, conditional statements, and looping structures. The document also includes examples and explanations of PHP functions and how to create dynamic web content using PHP.

Uploaded by

iqmal.real
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Chapter 1_Php Language

This document outlines a course on PHP language, detailing objectives, assessments, and fundamental concepts of web programming. It covers topics such as client-server models, PHP syntax, variables, arrays, conditional statements, and looping structures. The document also includes examples and explanations of PHP functions and how to create dynamic web content using PHP.

Uploaded by

iqmal.real
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 58

SPG0473

Web Programming
PHP Language
NORULMUBARAKAH IBRAHIM
TTO ROOM:L10 08
TTO, Industrial Electronics
German Malaysian Institute
Objectives
Upon completion of this subject, the students
should be able to:
Understand the process of Client and Server
Understand the working model of HTML and
PHP
Create your own web site make connection
to database
Course Assessment
Test
Test 1 - 10%
Test 2 – 10%
Practical test 3 – 10%
 End Module Test
Group Assig. 30%
PBL 1 - 15%
PBL 2 - 15%  Attitude
10%
Concept of CLIENT and SERVER

Using port number??


What is PHP?
 PHP is an acronym for "PHP: Hypertext
Preprocessor“

 PHP is a widely-used, open source


scripting language

 PHP scripts are executed on the server

 PHP is free to download and use


What is a PHP File?
 PHP files can contain text, HTML, CSS,
JavaScript, and PHP code

 PHP code is executed on the server,


and the result is returned to the
browser as plain HTML

 PHP files have extension ".php


What Can PHP Do?
• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and
close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your
database
• PHP can encrypt data
How to begin with PHP?
You must know the basic of HTML before
proceed to PHP language
You must first have access to either of the
following:
Apache – as a web server
MySql – as a database
Dreamweaver – design development
Xampp – software package that
include Apache & Mysql
How to save PHP pages?

Save your php pages as .php (e.g index.php)


Save at  C:\xampp\htdocs\index.php
Use your browser to access the file
E.g http://localhost/hello.php
PHP - Syntax
• Syntax - The rules that must be followed to write
properly structured code.
• A PHP scripting block always starts with <?php and
ends with ?>
• we recommend that you use the standard form (<?php)
rather than the shorthand form.

PHP Code:
<?Php
……
?>
Example of simple PHP script
Each code line in PHP must
end with a semicolon;
to output text with PHP: echo
<?php
echo "Hello World"; or print
?>
PHP Variables
 Variables are used for storing a values, like text
strings, numbers or arrays.
 When a variable is set it can be used over and
over again in your script
 All variables in PHP start with a $ sign symbol.
 The correct way of setting a variable in PHP:

$var_name = value;
Variables…cont
creating a variable with a string and
number.
 a variable does not need to be declared
<?php before being set.
$txt = "Hello World!";  PHP automatically converts the variable
$number = 16;
to the correct data type.
?>
Variable Naming Rules
must start with a letter or an underscore "_"
can only contain alpha-numeric characters and
underscores (a-Z, 0-9, and _ )
should not contain spaces. If a variable name is more
than one word, it should be separated with
underscore ($my_string), or with capitalization
($myString)
String in Variables
A string variable is used to store and manipulate a
piece of text.
String variables are used for values that contains
character strings.
Below, the PHP script assigns the string "Hello
World" to a string variable called $txt:

Output:
<?php
$txt="Hello World"; Hello World
echo $txt;
?>
The Concatenation Operator
There is only one string operator in PHP.
The concatenation operator (.) is used to put two string
values together.
To concatenate two variables together, use the dot (.)
operator:

<?php Output:
$txt1="Hello World";
$txt2=1234; Hello World 1234
echo $txt1 . " " . $txt2;
?>
Task-sample output
NorulMubarakah

Welcome to SPG 0473


Your CGPA is 3.59

Thank you.
PHP Strings

A string is a sequence of characters,


like "Hello world!".
PHP String Functions:
we will look at some commonly used
functions to manipulate strings
Using the strlen() function

The strlen() function is used to find the length of


a string.
Let's find the length of our string "Hello world!":

Output:
<?php
echo strlen("Hello world!"); 12
?>
Using the strpos() function
The strpos() function is used to search for a string or
character within a string.
If a match is found in the string, this function will return
the position of the first match. If no match is found, it will
return FALSE.
Let's see if we can find the string "world" in our string:

Output:
<?php
echo strpos("Hello world!“,”world”); 6
?>
PHP Operators
PHP Operators…cont
PHP If...Else Statement
Conditional Statements
Very often when you write code, you want to perform
different actions for different decisions.
You can use conditional statements in your code to do
this.
 if...else statement - use this statement if you want to
execute a set of code when a condition is true and
another if the condition is not true
 elseif statement - used with the if...else statement to
execute a set of code if one of several condition are
true
If…Else Statement…cont
The If...Else Statement
If you want to execute some code if a condition is true
and another code if a condition is false, use the
if....else statement.
Syntax Example

<?php
$d=“Fri”;
If (condition) if ($d=="Fri")
code to be execute if condition is true; echo "Have a nice weekend!";
else
else echo "Have a nice day!";
Code to be execute if condition is false; ?>
The ElseIf Statement
If you want to execute some code if one of
several conditions are true use the elseif
statement
Syntax Example
If (condition) <?php
code to be execute if condition is true; $d="sun";
Elseif (condition) if ($d=="Fri")
code to be execute if condition is true; echo "Have a nice weekend!";
Elsels elseif ($d==“sun”)
code to be execute if condition is false; echo "Have a nice sunday!";
else
Echo “have a nice day”;
?>
The Switch Statement
If you want to select one of many blocks of code to be
executed, use the Switch statement.
The switch statement is used to avoid long blocks of
if..elseif..else code.
switch (expression)
{
Syntax
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; }
Switch Statement…cont
echo "Traveling to $destination<br />";
switch ($destination)
Example1 {  The value of $destination
case "Las Vegas":
echo "Bring an extra $500";
was Tokyo.
break;  The switch operating
case "Amsterdam":
echo "Bring an open mind"; search for a case that
break; match a value.
case "Egypt":
echo "Bring 15 bottles of SPF 50 Sunscreen";  A Break;to prevent the
break; other cases is being
case "Tokyo": execute
echo "Bring lots of money";
break;
case "Caribbean Islands":
echo "Bring a swimsuit";
break;
Output
Default: echo “Rest at home”;
Traveling to Tokyo
} Bring lots of money
PHP Arrays
An array stores multiple values in
one single variable
An array is a special variable, which
can hold more than one value at a
time.
An array can hold many values under
a single name, and you can access
the values by referring to an index
number.
Create an Array in PHP
 In PHP, the array() function is used to create an
array.
 there are three types of arrays:
• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing
one or more arrays
Numeric Arrays
A numeric array stores each element with a numeric ID
key.
A numeric array stores each element with a numeric
ID key.
There are different ways to create a numeric array.
Example 1 Example 2
in this example the ID key In this example we assign
is automatically assigned: the ID key manually:

$names[0] = “Peter”;
$names=array(“Peter”,”John”,”Joe”); $names[1] = ”John”;
$names[2] =” Joe”;
Numeric Arrays

The ID keys can be <?php


used in a script: $names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
Echo $names[1] . " and " .
$names[2] ." are ". $names[0] .
"'s neighbors";
?>

Output:
Quagmire and Joe are Peter's neighbors
Associative Arrays
each ID key is associated with a value.
When storing data about specific named values, a numerical
array is not always the best way to do it.
With associative arrays we can use the values as keys and
assign values to them.
Example1

In this example we use an array to assign ages to the different persons:


$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);

Example2
The different way of= creating
$ages['Peter'] "32"; an array
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
Associative Array
The ID keys can be used in a script:
<?php $ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
echo "Peter is " . $ages['Peter'] . " years old.";
?>

Output: Peter is 32 years old.


Multidimensional arrays
A multidimensional array is an array
containing one or more arrays
PHP array able to store like table
below
Multidimensional arrays
We can store the data from the table above in a two-
dimensional array, like this:
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);

Now the two-dimensional $cars array contains four


arrays, and it has two indices: row and column.
To get access to the elements of the $cars array we
must point to the two indices (row and column):
<?php
Multidimensional arrays
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
Full Program Multidimentional arrays
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);

echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";


echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
PHP Looping
Looping
Very often when you write code, you want the same
block of code to run a number of times. You can use
looping statements in your code to perform this.
In PHP we have the following looping statements:
 While –loops through a block of code if and as long as a
specified condition is true
do...while - loops through a block of code once,
and then repeats the loop as long as a special
condition is true
for - loops through a block of code a specified
number of times
The while Statement
The while statement will execute a block of code
if and as long as a condition is true.
Syntax while ( conditional statement is true)
{ //do this code; }

Example1 <?php
$i=0;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
The do...while Statement
The do...while statement will execute a block of code at
least once - it then will repeat the loop as long as a
condition is true.
The following example will increment the value of i at
least once, and it will continue incrementing the variable i
as long as it has a value of less than 5:
Syntax do { code to be executed; <?php
} $x = 1;
while (condition); do {
echo "The number is: $x <br>";
$x++;
Example1 } while ($x <= 5);
?>
The for Statement
The for statement is used when you know how
many times you want to execute a statement or
a list of statements.
Example1 <?php
Syntax for ($i=0; $i<=5; $i++)
{
for (initialization; condition; increment) echo "Hello World!<br />";
{ }
code to be executed; ?>
}
PHP Functions
Create a PHP Function
A function is a block of code that can be
executed whenever we need it.
Creating PHP functions:
All functions start with the word "function()"
Name the function - It should be possible to
understand what the function does by its
name. The name can start with a letter or
underscore (not a number)
Add a "{" and "}"
Example of function
A simple function that writes my name
when it is called: <html>
<body>
Example2
<?php
<html> function writeMyName()
Example1 <body> {
<?php echo "Kai Jim Refsnes";
function writeMyName() }
{ echo "Hello world!<br />";
echo "Kai Jim Refsnes"; echo "My name is ";
writeMyName();
}
echo ".<br />That's right, ";
writeMyName();
writeMyName();
?> echo " is my name.";
</body> ?>
</html> </body>
</html>
Function…Adding parameter
Example1

<html>
<body>
<?php
function writeMyName($fname)
{
echo $fname . " Refsnes.<br />";
}
echo "My name is ";
writeMyName("Kai Jim");
echo "My name is ";
writeMyName("Hege");
echo "My name is ";
writeMyName("Stale");
?>
</body>
</html>
PHP Functions
Functions can also be used to return values.
Example1 <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
The PHP $_GET and $_POST variables are
used to retrieve information from forms, like user
input.
PHP Form Handling
The most important thing to notice when dealing with
HTML forms and PHP is that any form element in a
HTML page will automatically be available to your
PHP scripts.
PHP Forms and User Input
Example1: welcome.html

<html>  The example HTML page above contains


<body> two input fields and a submit button.
<form action="welcome.php" method="post">
Name: <input type="text" name=“fname" />  When the user fills in this form and click
Age: <input type="text" name="age" /> on the submit button, the form data is
<input type="submit" /> sent to the "welcome.php" file.
</form>
</body>
</html>
<html>
Example2: <body>
Welcome <?php echo $_POST[“fname"]; ?>.<br />
welcome.php
You are <?php echo $_POST["age"]; ?> years old.
</body> </html>
PHP $_POST and $_GET
$_POST $_GET
The $_POST variable is used to The $_GET variable is used to collect
collect values from a form with values from a form with method="get".
method="post".
The $_POST variable is an array of The $_GET variable is an array of
variable names and values sent by the HTTP variable names and values sent by the
POST method. HTTP GET method.
Information sent from a form with the Information sent from a form with the
POST method is invisible to others. GET method is visible to everyone
has no limits on the amount of information has limits on the amount of information
to send. to send (max. 100 characters).

http://localhost/welcome.php http://localhost/welcome.php?
name=Peter&age=37
The $_REQUEST Variable

The PHP $_REQUEST variable contains the contents of


both $_GET, $_POST, and $_COOKIE.
The PHP $_REQUEST variable can be used to get the
result from form data sent with both the GET and POST
methods.
Example
Welcome <?php echo $_REQUEST["name"]; ?>.<br />
You are <?php echo $_REQUEST["age"]; ?> years old!
PHP Cookies
What is a Cookie?
A cookie is often used to identify a user. A
cookie is a small file that the server embeds
on the user's computer.
Each time the same computer requests a
page with a browser, it will send the cookie
too.
With PHP, you can both create and retrieve
cookie values.
PHP Cookies…cont
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, secure, httponly);
PHP Cookies…cont
PHP Create/Retrieve a Cookie
• The following example creates a cookie named
"user" with the value "John Doe". The cookie will
expire after 30 days (86400 * 30).
• The "/" means that the cookie is available in
entire website
• We then retrieve the value of the cookie "user"
(using the global variable $_COOKIE).
• We also use the isset() function to find out if the
cookies is set
PHP Cookies…cont
Example Cookies
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 864
?>
<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>
PHP Sessions
A session is a way to store information (in
variables) to be used across multiple
pages.
Unlike a cookie, the information is not
stored on the users computer.
Session stored user information to be used
across multiple pages (e.g. username,
favorite color, etc). By default, session
variables last until the user closes the
browser.
Start a PHP Session

A session is started with the


session_start()
Session variables are set with the
PHP global variable: $_SESSION.
Session Example
<?php
// Start the session Note: The session_start()function
session_start(); must be the very first thing in your
?> document. Before any HTML tags.
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>
Session also can be modify and destroy
Use session_destroy(); to
destroy session

You might also like