Php
Php
• A PHP scripting block always starts with <?php and ends with
?>
<!DOCTYPE html>
<html>
<body>
<?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
Eg:
$color = "red";
PHP Operators
<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
• 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;
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
• 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
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>
Associative Arrays
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>";
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);
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
</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>
</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>
</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
Parameter Description
$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?
<?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
?>
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
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
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = “college";
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); ?>