Unit-5-PHP
Unit-5-PHP
PHP Variables
A variable in PHP is the name of the memory location that holds data.
In PHP, a variable is declared using the $ sign followed by the variable name.
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)
Syntax:
$variablename=values;
Example:
Filename: variable.php
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
PHP has a total of eight data types which we use to construct our variables:
Example:
File name: datatypes.php
<!DOCTYPE html>
<html>
<body>
<?php
echo "String datatype...";
$a = "Virat Kohli is the captain of Indian Test Cricket Team!";
echo $a."<br><br>";
</body>
</html>
Example:2
<!DOCTYPE html>
<html>
<body>
<?php
$a=readline('Enter Name:');
?>
</body>
</html>
Example:3
<?php
// Input section
// $a = 10
$a = (int)readline('Enter an integer: ');
// $b = 9.78
$b = (float)readline('Enter a floating'
. ' point number: ');
If Statement
Syntax:
if ( expression ) {
// code to execute if the expression evaluates to true
}
Example:
<!DOCTYPE html>
<?php
$a=10;
$b=5;
if ($a > $b)
echo "a is bigger than b";
?>
</body>
</html>
Else Statement
Syntax:
if ( expression ) {
// code to execute if the expression evaluates to true
} else {
// code to execute in all other cases
}
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$a=10;
$b=20;
if ($a > $b) {
</body>
</html>
Elseif Statement
Syntax:
if ( expression ) {
// code to execute if the expression evaluates to true
}
elseif (another expression) {
// code to execute if the previous expression failed
// and this one evaluates to true
}
else {
// code to execute in all other cases
}
Example:
<!DOCTYPE html>
<html>
<?php
$a=10;
$b=20;
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
</body>
</html>
Switch Statement
Syntax:
switch ( expression ) {
case result1:
// execute this if expression results in result1
break;
case result2:
// execute this if expression results in result2
break;
default:
// execute this if no break statement
// has been encountered hitherto
}
Example:
<!DOCTYPE html>
<?php
$i=10;
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is greater than 3";
}
?>
</body>
</html>
Loops in PHP
In PHP, we have the following looping statements:
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the
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
while Loop
Syntax:
code;
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$a = 0;
while($a < 5) {
echo "Value: $a <br>";
$a++;
}
?>
</body>
</html>
do while Statement
Syntax:
do {
// code to be executed
} while ( expression );
<!DOCTYPE html>
<html>
<body>
<?php
$a = 10;
do {
echo "Value: $a <br>";
$a++;
} while ($a < 15);
?>
</body>
</html>
for loop:
Syntax:
for (initialization; condition; increment/decrement counter) {
code;
}
Example:
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
foreach loop
Syntax:
foreach ($array as $value) {
code;
}
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$topics = array("JavaScript", "HTML", "CSS");
</body>
</html>
1. Numeric/Indexed Arrays:
A numerical array is a type of array which can store strings, numbers, and objects.
PHP index is represented by number which starts from 0.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
// Numeric/ indexed arrays 1st way
1st way:
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
</body>
</html>
2nd way:
<!DOCTYPE html>
<html>
<body>
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
</body>
</html>
Example: associate_array1.php
<!DOCTYPE html>
<html>
<body>
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>";
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
$salary["Sonoo"]="550000";
$salary["Vimal"]="250000";
$salary["Ratan"]="200000";
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>";
?>
</body>
</html>
3. Multidimentional Arrays:
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>
</body>
</html>
Function Description
A function is a piece of code which takes one more input in the form of parameter and does
some processing and returns a value.
In PHP, the function name is any name that ends in an open and closed parenthesis.
A number cannot be the first character in a feature name. It can begin with a letter or an underscore.
Syntax:
function function_name()
//Statement to be executed
<!DOCTYPE html>
<html>
<body>
<?php
function welcMsg()
welcMsg();
?>
</body>
</html>
Function Arguments:
<!DOCTYPE html>
<html>
<body>
<?php
function StudentsName($firstname)
echo "$firstname<br>";
StudentsName("Janani");
StudentsName("Helen");
StudentsName("Stella");
StudentsName("Kamal");
StudentsName("Bablu");
?>
</body>
</html>
Arguments are generally passed by value in PHP, which ensures that the function uses a copy
of the value and the variable passed into the function cannot be modified.
Changes to the argument modify the variable passed in when a function argument is passed by
reference.
The & operator is used to convert a function argument into a reference.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
function addition(&$val) {
$val += 10;
$number =5;
addition($number);
?>
</body>
</html>
<?php
function circle($r){
return 3.14*$r*$r;
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
function setval(int $a = 5) {
setval(50);
setval();
setval(13);
setval(40);
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
// Sample string
$string = "Hello, World!";
// Validate substr()
$subString = substr($string, 7);
echo "Substring from position 7: " . $subString. "<br>";
// Validate str_replace()
$newString = str_replace("World", "PHP", $string);
echo "Replaced string: ". $newString. "<br>";
// Validate strpos()
$position = strpos($string, ",");
echo "Position of the comma: ". $position. "<br>";
// Validate str_split()
$charArray = str_split($string);
echo "Character array: ";
print_r($charArray);
echo "<br>";
// Validate strtolower()
$lowercaseString = strtolower($string);
echo "Lowercase string: ". $lowercaseString. "<br>";
// Validate strtoupper()
$uppercaseString = strtoupper($string);
echo "Uppercase string: ". $uppercaseString. "<br>";
// Validate explode()
$wordsArray = explode(" ", $string);
echo "Exploded array: ";
print_r($wordsArray);
// Validate implode()
$joinedString = implode("-", $wordsArray);
echo "Joined string: ". $joinedString. "<br>";
// Validate sprintf()
$formattedString = sprintf("Today is %s, %d %s", "Monday", 5, "June");
echo "Formatted string: ". $formattedString. "<br>";
// Validate ucfirst()
$ucFirstString = ucfirst($string);
echo "String with the first character capitalized: ". $ucFirstString. "<br>";
// Validate ucwords()
$ucWordsString = ucwords($string);
echo "String with each word's first character capitalized: ". $ucWordsString. "<br>";
?>
</body>
</html>
</body>
</html>
Example:
<!DOCTYPE html>
<html>
<body>
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// Get the name and email from $_POST
$name = $_POST["txtname"];
$email = $_POST["txtemail"];
if (empty($name))
{
echo "Name is required";
exit;
}
if (empty($email))
{
echo "Email is required";
exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo "Invalid email format";
exit;
}
// Provide feedback to the user
echo "Hello $name, your email is $email.";
}
if(move_uploaded_file($_FILES['myFile']['tmp_name'], $target_path))
{
echo "File uploaded successfully!";
}
else{
echo "Sorry, file not uploaded, please try again!";
}
?>
</body>
</html>
<?php
if (!isset($_FILES["myFile"]))
{
die("There is no file to upload.");
}
$filepath = $_FILES['myFile']['tmp_name'];
$fileSize = filesize($filepath);
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
$filetype = finfo_file($fileinfo, $filepath);
if ($fileSize === 0)
{
die("The file is empty.");
}
$allowedTypes = [
'image/png' => 'png',
if (!in_array($filetype, array_keys($allowedTypes)))
{
die("File not allowed.");
}
$filename = basename($filepath); // I'm using the original name here, but you can also change
the name of the file here
$extension = $allowedTypes[$filetype];
$targetDirectory = __DIR__ . "\uploads"; // __DIR__ is the directory of the current PHP file
if (!copy($filepath, $newFilepath))
{ // Copy the file, returns false if failed
die("Can't move file.");
}
unlink($filepath); // Delete the temp file
</body>
</html>
The first parameter is the date and time, and the second parameter is an instance of the
DateTimeZone class representing the desired timezone.
In this example, we created a DateTime object for the current date and time in the
'Europe/London' timezone.
Example:
<!DOCTYPE html>
<html>
<body>
Example:
<?php
$date=date_create("2018-07-27");
echo date_format($date,"Y/m/d");
?>
Output:
2018/07/27
Example:
echo date_default_timezone_get();
Output:
UTC
Example:
echo "old time ". date_default_timezone_get();
$timeZ = 'America/Chicago';
if( date_default_timezone_set( $timeZ) ){
echo " New time ". date_default_timezone_get();
}
Example:
<?php
date_default_timezone_set("America/chicago");
echo date_default_timezone_get();
?>
Output:
America/chicago
Example:
$date=date_create("2025-02-25");
echo date_format($date,"Y/m/d H:i:s");
Output:
2025/02/25 00:00:00
<?php
// Match any word that starts with "cat"
$pattern = "/\bcat\w*/i"; // The "i" modifier makes the match case-insensitive
$subject = "I like cats and caterpillars but not catacombs.";
if (preg_match($pattern, $subject, $matches)) {
echo "Match found: " . $matches[0] . "\n"; // Output: Match found: cats
} else {
echo "No match found.\n";
</body>
</html>
Try: The try block contains the code that may potentially throw an exception. All of the code
within the try block is executed until an exception is potentially thrown.
Throw: The throw keyword is used to signal the occurrence of a PHP exception. The PHP
runtime will then try to find a catch statement to handle the exception.
Catch: This block of code will be called only if an exception occurs within the try code block.
The code within your catch statement must handle the exception that was thrown.
Finally: In PHP 5.5, the finally statement is introduced. The finally block may also be
specified after or instead of catch blocks. Code within the finally block will always be
executed after the try and catch blocks, regardless of whether an exception has been thrown,
and before normal execution resumes. This is useful for scenarios like closing a database
connection regardless if an exception occurred or not.
Syntax:
try
Example:
<!DOCTYPE html>
<html>
<body>
<?php
try
{
// if some condition is met or not met ->
throw new Exception("I am the error message!");
// below lines are not executed ->
echo "I am not executed!";
}
catch(Exception $e)
{
echo " Exception caught - ", $e->getMessage();
}
finally
{
echo " I am executed in the end";
}
?>
</body>
</html>
try {
// run your code here
}
catch (Exception $e) {
echo $e->getMessage();
}
catch (InvalidArgumentException $e) {
echo $e->getMessage();
}
Example:
<!DOCTYPE html>
<html>
<body>
<?php
if ($file) {
$data = "Hello, World!\n";
fwrite($file, $data);
fclose($file);
echo "Data written to the file.";
} else {
echo "Error opening file.";
}
?>
</body>
</html>
if ($file) {
while (($line = fgets($file)) !== false) {
echo $line;
}
fclose($file);
}
?>
</body>
</html>
1. Hidden Field:
Use a hidden field to keep track of this value.
A hidden field behaves the same as a text field, except that the user cannot see it unless he
views the HTML source of the document that contains it.
Example:
Hidden_Field.html File:
<!DOCTYPE html>
<html>
<body>
<h1> First Number</h1>
</form>
</body>
</html>
Hidden_Field1.php File:
<!DOCTYPE html>
<html>
<input type="hidden" name="fn" value=" <?php echo $_POST['fn'] ?> " id="fn" >
</form>
</body>
</html>
Hidden_Field2.php File:
<!DOCTYPE html>
<html>
<body>
<?php
$ans = $_POST['fn'] + $_POST['sn'] ;
?>
<h1> Answer is .....</h1>
<?php
?>
</form>
</body>
</html>
Example:
Query_String.html File:
<!DOCTYPE html>
<html>
<title>Login form</title>
</head>
<body>
<form action="Query_String.php" method=”get”>
<table>
<tr>
<td>User name:</td><td> <input type="text" name="username" ></td>
</tr>
<tr>
<td>E-mail: </td><td><input type="text" name="email" ></td>
</tr>
<tr>
<td><input type="submit" name="sub" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
echo "<strong>Welcome ".$_GET['username']. "!</strong><br/>";
echo "Please remember this e-mail: ".$_GET['email']. " for later use.";
?>
</body>
</html>
3. Session
Sessions are states that are saved to the server (like a unique ID), or if a user is logged into their
account.
To start a session in PHP, we use the session_start() function. We store session data by using
the $_SESSION superglobal.
<!DOCTYPE html>
<html>
<title>Login form</title>
</head>
<body>
<table>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
</table>
</form>
</body>
</html>
// start a session
session_start();
?>
<html>
<body>
</body>
</html>
Session2.php File:
<?php
session_start();
?>
How to destroy a session
We can destroy a whole session completely with the session_destroy() function.
Example:
<?php
session_start();
?>
4. Cookie
Cookies are states that are saved to the user’s system, instead of the server. Unlike a session, a
cookie has a 1024-byte size limit.
The first argument, name, is mandatory for every cookie. The rest of the arguments are optional
Example:
<?php
?>
?>
?>
?>