0% found this document useful (0 votes)
11 views84 pages

Php

The document outlines the fundamentals of web programming using PHP, covering topics such as PHP syntax, variables, operators, conditional statements, loops, arrays, functions, and form handling. It also introduces concepts like the LAMP stack, cookies, and sessions, providing examples for various PHP functionalities. Additionally, it explains how to embed PHP scripts in HTML and manage user input through GET and POST methods.

Uploaded by

Renju Hhygfdo K
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)
11 views84 pages

Php

The document outlines the fundamentals of web programming using PHP, covering topics such as PHP syntax, variables, operators, conditional statements, loops, arrays, functions, and form handling. It also introduces concepts like the LAMP stack, cookies, and sessions, providing examples for various PHP functionalities. Additionally, it explains how to embed PHP scripts in HTML and manage user input through GET and POST methods.

Uploaded by

Renju Hhygfdo K
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/ 84

Web Programming Lab

CO1: Implement dynamic web pages using PHP


PHP
• PHP stands for Hypertext Preprocessor
• PHP is a server-side scripting language.
• Scripts are embedded into static HTML files
• 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
Web Server
• A web server is a computer that runs websites.

• The basic objective of the web server is to store,


process and deliver web pages to the users.

• When users enter a URL address, such as


www.google.com, into a web browser, they’re
requesting a specific document from the web server.
Lamp stack
• LAMP stack in Linux is used for creating a powerful web
server environment.
• LAMP stands for Linux, Apache web server, MySQL, and
PHP, and together they provide a robust platform for
developing and deploying web applications.
How a PHP script is embedded in a webpage and executed

• A PHP scripting block always starts with <?php and ends with
?>

• A PHP scripting block can be placed anywhere in the


document.

• A PHP file normally contains HTML tags, just like an HTML


file, and some PHP scripting code.

• The file must have a .php extension to execute


sample.php

<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>
Comments in PHP

• In PHP,
– Use // to make a single-line comment.
– /* and */ to make a large comment block
Variables in PHP

• All variables in PHP start with a $ sign symbol.


• The correct way of declaring a variable in PHP as
$var_name = value;

Eg:
$color = "red";
PHP Operators

• Operators are used to perform operations on variables and


values.
• PHP divides the operators in the following groups:
– Arithmetic operators
– Assignment operators
– Comparison operators
– Increment/Decrement operators
– Logical operators
– String operators
– Array operators
– Conditional assignment operators
a) Arithmetic Operators
Program: Sum of two variables

<html>
<body>
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
</body>
</html>
b)Assignment Operators
• The basic assignment operator in PHP is "=".
Example

<html>
<body>
<?php
$x = 15;
$x% = 4;
echo $x;
?>
</body>
</html>
(c)Comparison operators
(d) Increment / Decrement Operators
e) Logical Operators
• The PHP logical operators are used to combine conditional
statements.
Example
(f) String Operators

Example
<?php
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2;
?>
(g) Array Operators
PHP Conditional Statements

• In PHP we have the following conditional statements:


• if statement - executes some code if one condition is
true
• if...else statement - executes some code if a condition
is true and another code if that condition is false
• if...elseif....else statement - executes different codes
for more than two conditions.
• switch statement - select one of many blocks of code
to be executed
The if Statement

• Use the if statement to execute some code only if a specified condition is true.
• Syntax
if (condition) {
code to be executed if condition is true;
}
Eg:
<?php
$num = 14;

if ($num < 20) {


echo "Small No!";
}?>
The if...else Statement
• Use the if....else statement to execute some code if a condition is true and another
code if a condition is false.
• Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}

Example

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

• It executes different codes for more than two conditions.


Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition
is true;
} else {
code to be executed if all conditions are false;
}
Example
<?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!";
?>
The PHP Switch Statement

• Used to perform different actions based on different


conditions.
• Select one of many blocks of code to be executed.
Syntax
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;
}
PHP Loops
• In PHP, supports the following looping statements:
• while - loops through a block of code while a
specified condition is true
• do...while - loops through a block of code once, and
then repeats the loop as long as a specified condition
is true
• for - loops through a block of code a specified
number of times
• foreach - loops through a block of code for each
element in an array
The while Loop
• The while loop executes a block of code while a condition is true.
Syntax
while (condition)
{
code to be executed;
}
Example
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
The do - while Statement
• The do...while statement will always execute the block of code once, it will
then check the condition, and repeat the loop while the condition is true.
Syntax
do
{
code to be executed;
}
while (condition);
Example
<?php
$i = 1;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<=5);
?>
The for Loop

• The for loop is used when you know in advance how many times the script
should run.
Syntax
for (init counter; test condition; increment)
{
code to be executed;
}

Example
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>
PHP Arrays

• An array is a special variable, which can hold more than one


value at a time.
• In PHP, array() function is used to create an array.
• Types of arrays:

– Numeric array/Indexed array - An array with a numeric


index
– Associative array - An array where each ID key is
associated with a value
Numeric Arrays/Indexed Arrays

• A numeric array stores each array element with a numeric


index.
• There are two ways to create indexed arrays.
– The index can be assigned automatically (the index
starts at 0)
Eg: $car = array(“Honda", "Volvo", "BMW", "Toyota");
– The index can be assigned manually:
Eg: $car[0]=“Honda";
$car[1]="Volvo";
$car[2]="BMW";
$car[3]="Toyota";
Example

<!DOCTYPE html>
<html>
<body>

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

</body>
</html>
Associative Arrays

• Use keys to access array values.


• There are two ways to create an associative array:

Method 1
• In this example we use an array to assign ages to
the different persons:
$ages = array("Peter"=>32, “Ben"=>30,
"Joe"=>34);
Method 2

$ages['Peter'] = "32";
$ages[‘Ben'] = "30";
$ages['Joe'] = "34";
The foreach Loop
• The foreach loop is used to loop through arrays.
• Works only on arrays, and is used to loop through
each key/value pair in an array.
Syntax
foreach ($array as $value)
{
code to be executed;
}
• For every loop iteration, the value of the current
array element is assigned to $value (and the array
pointer is moved by one) - so on the next loop
iteration, you'll be looking at the next array value.
Display array values

<?php
$size=array("Big","Medium","Short");
foreach( $size as $s )
{
echo "Size is: $s<br />";
}
?>
print_r()

<?php
$a = array("red", "green", "blue");
print_r($a);

echo "<br>";

$b = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");


print_r($b);
?>

Output:

Array ( [0] => red [1] => green [2] => blue )
Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )
count() or sizeof() function : which returns length of an array

<?php
$size=array("Big","Medium","Short");
echo count($size);
?>
Program to reverse an array

<?php
$array = array(1, 2, 3, 4);
$size = sizeof($array);

for($i=$size-1; $i>=0; $i--){


echo $array[$i];
}
?>
PHP Functions
• In PHP, there are more than 700 built-in functions.
• A function is a block of statements that can be used repeatedly in a program.
• A function will not execute automatically when a page loads.
• A function will be executed by a call to the function.
• A user-defined function start with the word function.
Syntax
function functionName(formal parameters)
{
code to be executed;
}
Example
<?php
function writeName()
{
echo “joan";
}
echo "My name is : ";
writeName();
?>
PHP Function Arguments

• Information can be passed to functions through arguments.


• An argument is just like a variable.
• Arguments are specified after the function name, inside the
parentheses.
Example
<?php
function function-name($fname, $year) {
echo "$fname born in $year <br>";
}

Name(“Arun", "1975");
Name(“Varun", "1978");
?>
Check odd or even
<?php
function oddeven(int $n)
{
if($n%2==0)
echo "$n is even";
else
echo "$n is odd";
}
$n=(int)readline("Enter a number");
oddeven($n);
?>
Form Handling
• Two most common methods for form
handling
1. get – used to request data from a
specified resource.
2. Post – used to send data to server to
create/ update a resource.
$_GET and $_POST
• $_GET and $_POST are global variables
used to collect form-data or retrieve
information from forms, like user input.
PHP $_POST

• It collect form data after submitting an HTML


form with method="post".
• $_POST is also used to pass variables.
PHP Form Handling using post method

PHP Form Handling


Example - HTML form with two input fields and a submit button
in an html file:
<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 and click on the submit button, the form
data is sent to a PHP file, called "welcome.php":

"welcome.php"

<html>
<body>

Welcome <?php echo $_POST["fname"]; ?>!<br />


You are <?php echo $_POST["age"]; ?> years old.

</body>
</html>

Output
Welcome John!
You are 28 years old.
• The HTML code of the form element is :
• <form method="post" action="">
• The $_SERVER["PHP_SELF"] sends the submitted
form data to the page itself.
• The htmlspecialchars() function converts special
characters to HTML entities.
PHP $_SERVER
• It holds information about headers, paths, and script locations.
Example
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
test_get.php
<html>
<body>

<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>

</body>
</html>
PHP $_POST
• It collect form data after submitting an HTML form with
method="post".
• $_POST is also used to pass variables.
Example
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { // collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else { echo $name; }
}
?>
</body> </html>
PHP $_GET
• It collect form data after submitting an HTML form with
method="get".
• $_GET can also collect data sent in the URL.
Example - An HTML page that contains a hyperlink with parameters:
<html>
<body>

<a href="test.php?subject=PHP&web=nptel.com">Test $GET</a>

</body>
</html>

When a user clicks on the link "Test $GET", the parameters "subject"
and "web" are sent to "test_get.php", and we can then access their
values in "test_get.php" with $_GET.
PHP include and require Statements
• To insert the content of one PHP file into another PHP file
(before the server executes it).
• The include and require statements are identical, except upon
failure.
• require will produce a fatal error (E_COMPILE_ERROR) and
stop the script.
• include will produce a warning (E_WARNING) and the script
will continue.
Syntax
include 'filename';
or
require 'filename';
Example - include
<html>
<body> footer.php
<h1>Welcome to my home
<?php
page!</h1> echo "<p>Copyright © 1999-
<p>Some text.</p> 2022
<?php include 'footer.php';?> </p>";
?>
</body>
</html>

Output
Welcome to my home
page!
Some text.
Copyright © 1999-2022
PHP Date() Function

• Used to format a time and/or date.


• It also formats a timestamp to a more readable date and time.
• Syntax
date(format,timestamp)

Parameter Description

format Required. Specifies the format of the timestamp

timestamp Optional. Specifies a timestamp. Default is the current


date and time
PHP Date()

• The required format parameter in the date()


function specifies how to format the date/time.
• 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)
• Other characters, like"/", ".", or "-" can also be
inserted between the letters to add additional
formatting:
Web Programming Lab
CO2: Develop web applications in PHP using
cookie, session, file and database.
Cookie and Session
• Cookie - store the state of PHP application on
the user's browser .

• Session - store the state of PHP application on


the server .
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, cookie can be created and
retrieved.
How to Create a Cookie?

• The setcookie() function is used to set a cookie.


Syntax
setcookie(name, value, expire);
Example:
• In the example below, we will create a cookie named "user" and assign the
value "Alex " to it.
• We also specify that the cookie should expire after one hour. (time()
function returns current time.
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
How to Retrieve a Cookie Value?

• The PHP $_COOKIE variable is used to retrieve


a cookie value. In the example below, we
retrieve the value of the cookie named "user"
and display it on a page:
• <?php
// Print a cookie
echo $_COOKIE["user"];
• ?>
Question: Create a cookie and display its
value.
<?php

$cookie_name = "user";
$cookie_value = "John ";
setcookie($cookie_name, $cookie_value, time() + 3600);

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];
}
?>
How to Delete a Cookie?

• When deleting a cookie you should assure that


the expiration date is in the past.
• <?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
PHP Sessions

• A PHP session variable is used to store


information about, or change settings for a
user session in server.
• Session variables hold information about one
single user, and are available to all pages of
one application.
• Sessions work by creating a unique id (UID) for
each visitor and store variables based on this
UID.
PHP Session Variables

• A PHP session solves this problem by allowing


you to store user information on the server for
later use (i.e. username, shopping items, etc).
• However, session information is temporary
and will be deleted after the user has left the
website.
Starting a PHP Session

• Before you can store user information in your


PHP session, you must first start up the
session.
• The session_start() function must appear
BEFORE the <html> tag:
<?php
session_start();
?>
<html>
Storing a Session Variable
The correct way to store and retrieve session variables is to use the $_SESSION
variable:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html><body>

<?php
// Set session variables
$_SESSION[" user"] = "john";
echo "Session variables are set.";
?>
</body></html>
Retrieve session values
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Hello " . $_SESSION["user"] . ".<br>";
?>

</body>
</html>
Question: Create a session on web page1 and then
display the session value in webpage2 (link should be
provided from webpage1 to webpage2)
<?php <?php
// Start the session session_start();
?>
session_start();
<!DOCTYPE html>
?> <html>
<!DOCTYPE html> <body>
<html><body>
<?php
// Echo session variables that were set on
<?php
previous page
// Set session variables echo "Hello " . $_SESSION["user"] . ".<br>";
$_SESSION[" user"] = "john"; ?>
echo "Session variables are set.";
?> </body>
</html>
</body></html>
Destroying a Session

• If you wish to delete some session data, you can use the
unset() or the session_destroy() function.
• The unset() function is used to free the specified session
variable:
<?php
unset($_SESSION['user']);
?>
• You can also completely destroy the session by calling the
session_destroy() function:
<?php
session_destroy();
?>
PHP File Handling
• The file operations in PHP are :
1. Open File
2. Read File
3. Write File
4. Append File , and
5. Delete File
Opening a File
• The fopen() function` is used to open files in PHP.
Syntax - fopen (filename , mode);

• The first parameter of this function contains the name of the file
to be opened and the second parameter specifies in which mode
the file should be opened. die() function exit with a message.
Example :

<?php

$file=fopen("welcome.txt","r") or die("Unable to open file!");

?>
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
Read/Append. Preserves file content by writing to the
a+ 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
Closing a File

• The fclose() function is used to close an open file.


• It requires the name of the file we want to close
Syntax – fclose (“filename”);
Example
<?php
$file = fopen("test.txt","r");

//some code to be executed

fclose($file);
?>
PHP Read File - fread()
• fread() function is used to read the content of the file.
• It accepts two arguments - resource and file size.
• First parameter contains the name of the file to read from and
the second parameter specifies the maximum number of bytes
to read.
Syntax : fread ( resource $handle , int $length )

Example
fread($myfile,filesize("webdictionary.txt"));
PHP Write File

• fwrite() function is used to write content of the string into file.


The first parameter of fwrite() contains the name of the file to
write to and the second parameter is the string to be written.
• Syntax : fwrite ( $file , $string);
• Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open
file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
PHP Append to File

• Append data into file by using “a or a+” mode in fopen()


function.
• The "a" mode appends text to the end of the file, while the "w"
mode overrides (and erases) the old content of the file.
Example
<?php
$myfile = fopen("newfile.txt", "a") or die("Unable to open
file!");
$txt = "Donald Duck\n";
fwrite($myfile, $txt);
$txt = "Goofy Goof\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
PHP and database
(mysql)
Operations
1. Create a table in a database.
2. Insert to a table.
3. Display contents of table.
Question 1 : create a connection between
php and mysql

<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = “college";

$conn = new mysqli($servername, $username,


$password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Question 2 : create a table in database myDB.
<?php // sql to create table
$servername="localhost"; $sql = "create table student(admn_no int(6)
primary key,name varchar(30) not
$username ="root"; null,class varchar(10),branch
$password ="password"; varchar(50))";
$dbname =“college";
if ($conn->query($sql) === TRUE)
{
// Create connection echo "Table customer created successfully";
$conn = new mysqli($servername, }
$username, $password, else {
$dbname); echo "Error creating table: " . $conn->error;
// Check connection }

if ($conn->connect_error) {
$conn->close();
die("Connection failed: " . $conn- ?>
>connect_error);
}
Question 3 : insert a record to student table
<?php if($conn->query($sql) === TRUE)
$servername ="localhost"; {
$username ="root"; echo "New record created successfully<br>";
$password ="password"; }
$dbname ="college"; else
{
echo "Error: " . $sql . "<br>" . $conn->error;
$conn = new mysqli($servername,$username,$password,
}
$dbname);
$sql = "SELECT admn_no,name,class,branch FROM student";
if($conn->connect_error) $result = $conn->query($sql);
{
die("Connection failed: " . $conn->connect_error); if ($result->num_rows > 0)
} {
while($row = $result->fetch_assoc())
$admn = $_POST['admnno']; {
echo "Admn no: " . $row["admn_no"]. "<br>";
$name=$_POST['name'];
echo "Name: " . $row["name"]. "<br>";
$class=$_POST['class']; echo "Class: " . $row["class"]. "<br>";
$branch=$_POST['branch']; echo "Branch: " . $row["branch"]. "<br>";
}
$sql = "INSERT INTO student VALUES }
('$admn','$name','$class','$branch')"; else
{
echo "0 results";
}
?>
Question 4 : search record from student
table.
<?php if ($result->num_rows > 0)
$servername ="localhost"; {
$username ="root"; while($row = $result->fetch_assoc())
$password ="password";
{
$dbname ="college";
echo "Admn no: " . $row["admn_no"].
"<br>";
$conn = new mysqli($servername,$username,
$password,$dbname); echo "Name: " . $row["name"]. "<br>";
if($conn->connect_error) echo "Class: " . $row["class"]. "<br>";
{ echo "Branch: " . $row["branch"]. "<br>";
die("Connection failed: " . $conn- }
>connect_error); }
}
else
$admn=$_POST['admnno'];
{
$sql = "SELECT * FROM student where echo "0 results";
admn_no=$admn"; }
$result = $conn->query($sql); ?>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy