LAB 4
PHP BASICS
PART-I
August 23, 2023
2
• Real-time dynamic websites can not be created using
only HTML and CSS.
• Why?
• HTML itself can’t process the data
• We need a scripting language like PHP, PERL etc.
Let’s see
“what is PHP?”
3
PHP
• Pre-Hypertext Processor or PHP: Hypertext Processor
• HTML-embedded server-side scripting language used for Web
Development
• PHP scripts are executed on the server
• Open-source software supporting many databases (MySQL,
Informix, Oracle, Sybase, PostgreSQL, Generic ODBC, etc.)
• Much of its syntax is borrowed from C, Java and Perl
• Allows web developers to write dynamically generated pages
quickly
• Runs on different platforms and is compatible with almost all
servers used today
4
How Does PHP Works?
1. The web browser sends an HTTP request to the web server for a
website whose first page is index.php.
2. The PHP preprocessor that locates on the web server processes
PHP code to generate the HTML document.
3. The web server sends the HTML document back to the web
browser, e.g., index.php.
https://www.phptutorial.net/php-tutorial/what-is-php/
5
https://slideplayer.com/slide/12915376/
6
How Does PHP Works
Plain HTML
Pages
Gets executed
on SERVER
7
Example PHP
8
Learn PHP !
• Extension: file_name.php
• Content: text, HTML tags and PHP scripts.
• PHP code must be contained within the tags:
<?php and ?>
• PHP statement ends with a semicolon ‘;’
• Example:
<?php
PHP Statement 1;
…
PHP Statement n;
?>
9
‘Echo’ Command
• Used to output text to the web browser.
PHP Statement Output
echo "Have a nice day."; Have a nice day.
echo "<h5>Have a nice day.</h5>"; Have a nice day.
$var_1 = 4; 4
echo $var_1;
echo "This ", "string ", “is ", "made ", This string is made with multiple
"with multiple parameters."; parameters.
$str_1 = "Have a nice day"; Have a nice day Beena.
echo "$str_1 Beena.";
$str_1 = "Have a nice day"; $str_1 Beena.
echo '$str_1 Beena.';
Notice the difference between the usage of single and double quotes.
10
‘Echo’ Example
<html> Instructions to run file1.php:
<head> 1) Files will run on local server (xampp)
<title> which is installed on your PCs and
can be accessed by localhost.
My First PHP Page
2) Keep the file in C:\ xampp\htdocs
</title> folder.
</head> 3) Run files on web browser by typing
<body> localhost/file1.php.
<?php
echo "<h1>Welcome to my first PHP page.</h1>";
?>
</body>
</html>
11
Comments
• Single Line → // or #
• Multi Line → /* … */
• Example:
<?php
// This is a single line comment.
# This is another single line comment.
/* This is a multiple
line comment. */
?>
12
Variables
PHP variables:
• Starts with the $ sign, followed by the name of the variable
• Name may start with a letter or underscore "_".
• Are comprised of alpha-numeric characters and
underscores. a-z, A-Z, 0-9, or _ .
• Are case-sensitive and need not be declared.
Syntax:
• $variable_name = Value;
Example:
• $_hello = "Hello World!";
• $first_number = 4;
• $num2 = 8;
13
Example - Variables
<html>
<head><title>Variable Example</title></head>
<body>
<?php
$str1 = "Hello all. My name is Amit Jain.";
$num = 35;
echo $str1;
echo "<br>";
echo "I am $num years old.";
?>
</body></html>
14
Operators in PHP
Let $a = 5; and $b = 2;
Operator Meaning Example
. Concatenation echo "Hello!"."<br />"."How are you.";
= Assignment $var_1 = 4;
Arithmetic Operators
+ Addition $a + $b =5+2=7
- Subtraction $a - $b =5-2=3
* Multiplication $a * $b = 5 * 2 = 10
/ Division $a / $b =5/2=2
% Modulus $a % $b =5%2=1
15
Contd…
Operator Meaning Example Equivalent
Operation
+= Plus Equals $a += 2; $a = $a + 2;
-= Minus Equals $a -= 2; $a = $a – 2;
*= Multiply Equals $a *= 2; $a = $a * 2;
/= Divide Equals $a /= 2; $a = $a / 2;
%= Modulo Equals $a %= 2; $a = $a % 2;
.= Concatenate Equals $a .= "hello"; $a = $a . "hello";
++ Pre/Post Increment $a++; or ++$a; $a = $a + 1;
-- Pre/Post Decrement $a--; or --$a; $a = $a - 1;
16
Comparison Operators
Let $a = 4; and $b = 6;
Operator Meaning Example Result
== Equal To $a == $b False
!= or <> Not Equal To $a != $b True
< Less Than $a < $b True
> Greater Than $a > $b False
<= Less Than or Equal To $a <= $b True
>= Greater Than or Equal To $a >= $b False
17
Logical Operators
Let $a = 4; and $b = 6;
Operator Meaning Example Result
&& AND $a == 4 && $b == 6 True
|| OR $a != 4 || $b == 6 True
! NOT !($a == $b) True
18
Arrays
• It’s a special variable, which can store multiple variable
values (elements) under a single name.
• Each element in the array has its own index so that it can
be easily accessed.
• Types:
– Numeric Arrays → index-value pairs.
– Associative Arrays → ID key-value pair.
– Multidimensional Arrays → one or more arrays.
19
Contd…
• Numeric Arrays
$name=array(“Amit",“Jain");
or
$name[0] = “Amit";
$name[1] = “Jain";
• Associative Arrays : (ID key => element_value)
$name=array("First" => “Amit", "Last" => “Jain");
or
$name['First'] = “Amit";
$name['Last'] = “Jain";
20
Contd…
• Multidimensional Arrays
$name = array
(
“Amit" => array (10, 8, 9, 9),
“Ram" => array (7, 5, 8, 8),
“Priya" => array (8, 9, 10, 9)
);
21
Example – Arrays
<html> echo $name[1];
<head><title> echo "<br>";
Array Example print_r($name);
</title></head> echo "<br>";
<body> echo $name1['First'];
<?php echo " ";
$name[0] = “Amit"; echo $name1['Last'];
$name[1] = “Jain"; echo "<br>";
$name1['First'] = “Amit"; print_r($name1);
$name1['Last'] = “Jain"; ?>
echo $name[0]; </body>
echo " "; </html>
22
Contd…
The print_r() function is used to print
human-readable information about a variable.
23
Forms - Revisited
• Forms provides a way to capture user input from a web page and
sends it to the server.
• Forms contains other elements like textbox, radio buttons,
checkbox, buttons etc. in the web page to capture the user input.
• HTML forms are placed on a web page by using <form> tag. This
tag contains other form elements.
• The <form> tag uses the ‘action’ attribute to identify to where to
send the data and ‘method’ attribute to identify how to get the data.
• It contains a SUBMIT button to send the data from one web page
to server.
• HTML itself can’t process the data. Hence the scripting language
such as PHP, PERL etc. are needed.
Method
Get: Post:
• The form data is appended to the • The form data is not appended to the
URL specified in the action attribute URL.
when submitted. • The values are sent in what are known
• It is ideal for: as HTTP headers.
– short forms (such as search boxes) • Use it if your form:
– when you are just retrieving data – allows users to upload a file
from the web server (not sending – is very long
information that should be added to
– contains sensitive data (e.g., passwords)
or deleted from a database)
– adds information to, or deletes
• It is useful for form submissions information from, a database
where a user wants to bookmark the
• Form submissions with the "post"
result.
method cannot be bookmarked.
• There is a limit to how much data
• It does not have size limitations for
you can place in a URL
sending the data.
• Never use the “get” method to pass
• The "post" method is more robust and
sensitive information
secure than “get”.
• Default if method attribute not used.
25
$_GET and $_POST in PHP
• They are predefined associative arrays.
• $_GET and $_POST collect values in a form with
method="get" and method="post" respectively.
• Names used in forms serve as the keys in these
associative arrays.
26
Example – GET
Form.html getMethod.php
<html> <html>
<head><title> <head><title>
Get Method Example Directed From Get Method Example
</title></head> </title></head>
<body> <body>
<form action="getMethod.php" Welcome
method="get"> <?php
First Name: <input type="text" echo $_GET["fname"];
name="fname" /> <br> echo " ";
Last Name: <input type="text" echo $_GET["lname"];
name="lname" />
echo ".";
<input type="submit" />
?>
</form>
</body></html>
</body></html>
27
Contd…
getMethod.php?fname=Amit&lname=Jain
28
Example – POST
Form.html postMethod.php
<html> <html>
<head><title> <head><title>
Post Method Example Directed From Post Method Example
</title></head> </title></head>
<body> <body>
<form action="postMethod.php" Welcome
method="post"> <?php
First Name: <input type="text" echo $_POST["fname"];
name="fname" /> <br> echo " ";
Last Name: <input type="text" echo $_POST["lname"];
name="lname" />
echo ".";
<input type="submit" />
?>
</form>
</body></html>
</body></html>
29
Contd…
postMethod.php
30
Strings in PHP
Function Example
Creation $str1 = "Hello!";
Concatenation $str1 = "Hello!";
$str2 = “Amit";
echo $str1. " " . $str2;
String Length strlen("Hello!"); =6
Searching strpos("Hello! Amit",“Amit"); = 7
31
Contd…
Check postMethod.php and Replace
<?php
echo $_POST["fname"]; It works both ways
echo " ";
echo $_POST["lname"];
echo ".";
?>
<?php
echo $_POST["fname"]." ".$_POST["lname"].".";
?>
32
Example - String
• Update postMethod.php
<?php
echo $_POST["fname"]." ".$_POST["lname"].".";
echo "<br>Length of your first name: ".
strlen($_POST["fname"]);
echo "<br>Length of your last name: ".
strlen($_POST["lname"]);
echo "<br>Your first name contains ‘m' at position:
". strpos($_POST["fname"],“m");
?>
33
Contd…
34
Example – String Operators
• postMethod.php
<?php
$fnlen = strlen($_POST["fname"]);
$lnlen = strlen($_POST["lname"]);
$len = $fnlen + $lnlen;
echo $_POST["fname"]." ".$_POST["lname"].".";
echo "<br>Length of your first name: ".$fnlen;
echo "<br>Length of your last name: ".$lnlen;
echo "<br>Total length: ".$len;
echo "<br>Your first name contains ‘m' at position:
".strpos($_POST["fname"],“m");
?>
35
Contd…
36
Control Structure in PHP
• If…Else statement
• Switch statement
• For Loop
• While Loop
• Do-while Loop
• For Loop
• Foreach Loop
37
Conditional Statements
1. If Statement 2. If / else Statement
Syntax: Syntax:
if ( condition true ) if ( condition true )
{ {
PHP statements; PHP statements;
} }
else // condition false
{
PHP statements;
}
38
Contd…
3. Elseif Statement
Syntax:
if ( condition1 true ){
PHP statements;
}elseif (condition2 true){
PHP statements;
}…
…
}else{
PHP statements;
}
39
Contd…
4. Switch Statement
Syntax:
switch ($var){ default:
case label1: PHP statements;
PHP statements; break;
break; }
…
case labeln:
PHP statements;
break;
40
A Simple example using text field element :
<html>
<head> <title>Login</title> </head>
<body>
<form method="post" action="login.php">
Please log in.<br/>
Username: <input name="username" type="text" /><br />
Password: <input name="password" type="password" /><br/>
<input name="submit" type="submit" />
</form>
</body> </html>
<?php
if($_POST['username'] == “amitjain" && $_POST['password'] ==
“password123")
{ echo("Welcome, Amit Jain."); }
else
{ echo("You're not Amit Jain!"); }
?>
41
Looping Statements
while Loop do…while Statement
Syntax: Syntax:
while ( condition true ) do
{ {
PHP statements; PHP statements;
} }
while ( condition true )
42
Contd…
for Loop
Syntax:
for (initial value;
condition;
increment)
{
PHP statements;
}
43
Example: Table Generator
<html>
Form.html
<head>
<title>
Loop Example
</title>
</head>
<body>
<center><form action="loop.php" method="post">
Generate <input type="text" name="mul" />
multiples of <input type="text" name="num" />
<br><input type="submit" />
</form></center>
</body></html>
44
Example: Table Generator
<html><body><center><?php loop.php
$mul = $_POST["mul"];
$num = $_POST["num"];
echo '<table align=\"center\ border= 2">';
for ( $i = 1; $i <= $mul; $i++) {
echo "<tr><td>";
echo $num." x ".$i;
echo "</td><td> =
</td> <td> ";
echo $num * $i;
echo "</td></tr>";}
echo "</table>";
?></center></body></html>
45
foreach Loop
• Used to loop through arrays.
• Syntax:
foreach($array as $value)
{
PHP statements;
}
• For every loop iteration, the value of the current array
element is assigned to $value and the array pointer is
moved by one, until it reaches the last array element - so
on the next loop iteration, we can look at the next array
value.
46
Example of foreach (using numeric array)
<html>
<head><title>
foreach Example
</title></head>
<body>
<?php
$marks = array(10, 8, 9, 10, 9);
echo 'Below is the list of marks in science:<br>';
foreach ( $marks as $i) {
echo $i."<br>"; } ?>
</body></html>
47
Example of foreach (using associative array)
<html>
<head><title>
foreach Example
</title></head>
<body>
<?php
$marks = array("Anuj"=>10, "Bharat"=>8, "Deep"=>9,
"Eshita" =>10, "Garima"=>9);
echo 'Below is the list of marks in science:<br>';
foreach ( $marks as $name => $i) {
echo $name." = ".$i."<br>“;}
?></body></html>
48
include
• Takes file name as an input and inserts the contents of the
specified PHP file into the issuing PHP script.
• Used to insert same PHP, HTML, or text segment on
multiple pages of a website, for example, a menu.
• Saves lot of time.
• Syntax:
include("file_name.php");
49
Example - include
welcome.php postMethod.php
<html>
<body>
<center><h2> Welcome
</h2></center> <?php
<center><h4> This is an include("welcome.php");
example for include. You …
can add the common
parts using this …
command. ?>
</h4></center>
</body>
</html>
50
Contd…
51
require
• It is same as the include command.
• But it stops the execution of a PHP script if necessary
files are missing or misnamed, which doesn’t happen in
the case of include command.
• Syntax:
require("file_name.php");
HTML FORM ELEMENT INTERACTION
• The PHP script
– running at server, Revisit
– receives the data from the form and
– uses it to perform an action such as updating database contents,
sending database format, user authentication etc.
• To create a form and point it to a PHP document, the HTML tag
<form> is used and an action is specified as follows:
<form method="post" action="action.php">
<!-- Your form here -->
</form>
⚫ All fields in the form are stored in the variables $_GET or $_POST,
depending on the method used to submit the form
⚫ Difference
⚫ GET submits all the values in the URL, while
⚫ POST submits values transparently through HTTP headers.
<html> <body>
<form action="drop_radio.php" method="post"> Form Revisited:
<table border=1>
<tr><td> Courses : </td> Radio Buttons &
<td align = 'right'> <select name = "courses">
<option value = "CS301">CS301</option>
Drop Down Lists
<option value = "EC301">EC301</option>
<option value = "CS611">CS611 </option>
<option value = "EC612">EC612 </option>
</select></td>
</tr>
<tr><td> Course Category </td>
<td align ='right'>
<input type = "radio" name = "category" value="full-time” checked="checked"/>Full time
<input type = "radio" name = "category" value="part-time" /> part time</br>
</td>
</tr>
<tr><td></td>
<td align = 'right'><input type = "submit" name="submit” value="GO"/></td>
</tr>
</table></form>
</body></html>
PHP Code that handles the previous form:
<html>
<body>
<?php
if($_POST["courses"]=='CS301' OR $_POST["courses"] == 'EC301')
{ $ctype='UG Course'; }
else
{ $ctype='PG Course'; }
if($_POST["category"]=='full-time')
{ $catg='full time';}
else
{ $catg='part time';}
echo "</b> You are registered for a ".$ctype.":".$_POST["courses"]."</b></br>";
echo "This is a <b>".$catg."course</b>";
?>
</body>
</html>
EX: CHECK BOXES
<body>
<form action="check_multilist.php" method="post"> & MULTILISTS
<table border=1>
<tr><td> Select your favorite server side language:</td><td align = 'right'>
<select name = "lang[]" multiple="multiple">
<option value = "C"> C </option>
<option value = "Perl"> Perl </option>
<option value = "Servlets"> Servlets </option>
<option value = "PHP"> PHP </option>
<option value = "ASP"> ASP </option>
<option value = "JSP"> JSP </option>
</select></td></tr>
<tr><td> Select your favorite Operating Systems: </td> <td align = 'left'>
<input type = "checkbox" name = "OS[]" value="Windows XP" checked="checked"/>
Windows XP</br>
<input type = "checkbox" name = "OS[]" value="Windows 7" /> Windows 7</br>
<input type = "checkbox" name = "OS[]" value="Linux"/> Linux</br>
<input type = "checkbox" name = "OS[]" value="Unix"/> Unix</br>
</td></tr>
<tr><td></td><td align = 'right'><input type = "submit"
name="submit"value="GO"/></td></tr>
</table>
</form></body>
PHP Code that handles the previous form:
<?php
$lang = $_POST['lang'];
$OS = $_POST['OS'];
$count = count ($lang);
echo "<b> Your Favorite Language(s) are: </b></br>";
for($i = 0; $i< $count; $i++)
{
echo ($i + 1 . "." . $lang[$i] . "<br/>");
}
echo "</br></br><b> Your Favorite Operating System(s) are: </b></br>";
$count = count($OS);
for($i = 0; $i < $count ; $i++)
{
echo($i + 1 . "." . $OS[$i] . "<br/>");
}
?>
57
Ready for Assignments …
Assignment 5
on submit Form
Assignment 6
on submit Form