PHP File - PHP - Merged
PHP File - PHP - Merged
Introduction to PHP
History and Evolution: PHP was originally created by Rasmus Lerdorf in 1994 as a set of
Common Gateway Interface (CGI) binaries written in C. PHP stands for "PHP: Hypertext
Preprocessor," a recursive acronym. It was designed for web development, offering a simpler
way to generate dynamic web pages compared to traditional CGI scripts.
Comparing PHP to External Systems: PHP has the capability to interface with external systems
such as databases (MySQL, PostgreSQL), cloud storage, and other services. Its ability to
seamlessly interact with hardware and software makes it a popular choice for building full-stack
applications.
PHP Scripting: PHP scripts are executed on the server side, making it easy to produce dynamic
content on a website. PHP code is embedded within HTML using <?php ?> tags.
Basic PHP Development: The development of PHP programs involves understanding its basic
syntax, setting up the development environment (XAMPP, WAMP), and executing scripts.
Testing for Data Types: PHP has built-in functions like gettype() and is_*() to test and return the
type of variable being used.
Changing Variable Types: PHP allows implicit and explicit type casting. Implicit type conversion
happens automatically, whereas explicit conversion requires the developer to cast a value from
one type to another using casting operators (int), (string) etc.
Dynamic Variables: PHP variables are dynamically typed, which means that you don’t need to
declare the type of a variable before assigning a value. This flexibility is a hallmark of PHP’s
design.
In PHP, data types refer to the classification or categorization of data items. It helps the PHP interpreter
know how the programmer intends to use the data and how memory is allocated for it. PHP is a loosely
typed language, meaning that variable types do not need to be explicitly declared—they are determined
automatically based on the value assigned. PHP provides several built-in data types that are used to
construct variables.
### 1. **Integer**
An **integer** is a whole number without a decimal point. It can be positive or negative, or zero. PHP
interprets integers in decimal, octal, or hexadecimal notation. The range of an integer depends on the
platform—typically, a 32-bit signed integer ranges from -2,147,483,648 to 2,147,483,647.
- **Examples**:
```php
```
A **float** (also known as **double**) is a number that has a decimal point or a number in exponential
form. Floats are used when more precision is needed for large or small numbers.
- **Examples**:
```php
### 3. **String**
A **string** is a sequence of characters, where characters can be letters, numbers, or other symbols.
Strings in PHP are enclosed in single quotes (`'`) or double quotes (`"`). Strings can be manipulated in
various ways using built-in functions.
- **Examples**:
```php
```
- **Functions**:
---
### 4. **Boolean**
A **boolean** is the simplest data type in PHP, representing two possible values: **TRUE** or
**FALSE**. Booleans are often used in control structures like `if`, `while`, etc.
- **Examples**:
```php
$boolVar = true;
$boolVar2 = false;
### 5. **Array**
An **array** is a data structure that can store multiple values in a single variable. PHP arrays can store
different types of data, and they can be either **indexed** (with numeric keys) or **associative** (with
named keys).
- **Examples**:
- **Indexed Array**:
```php
```
- **Associative Array**:
```php
```
- **Multidimensional Arrays**: These are arrays that contain other arrays, which can be used to
represent more complex data structures.
- **Functions**:
---
### 6. **Object**
An **object** is an instance of a class in PHP. Objects are used to store complex data and behaviors
(methods) related to that data. Classes are blueprints for objects, containing properties (variables) and
methods (functions).
- **Example**:
```php
class Car {
var $color;
---
### 7. **NULL**
A variable of data type **NULL** represents a variable with no value. It is explicitly assigned by setting a
variable to `NULL` or when a variable is created without assigning it a value.
- **Examples**:
```php
$nullVar = NULL;
### 8. **Resource**
A **resource** is a special variable that holds a reference to an external resource, such as a database
connection, a file handle, or a connection to a remote server. Resources are not directly manipulated by
users—they are created and managed through specific PHP functions.
- **Examples**:
```php
```
- **Common Resources**:
---
- **Type Juggling**: PHP automatically converts between data types when it makes sense. For instance,
if you try to add a string and an integer, PHP will attempt to convert the string into an integer before
performing the addition.
Example:
```php
```
- **Type Casting**: You can manually change the type of a variable by casting it. PHP supports type
casting to integer, float, string, and other types.
Example:
```php
$var = "10";
### Conclusion
PHP’s flexibility with data types, particularly its dynamic typing system, makes it a powerful language for
web development. However, it’s essential to understand how different data types interact and how to
manage them effectively to avoid errors in your code. With built-in functions for type testing, conversion,
and manipulation, PHP provides developers with the tools to handle variables of different types in a
seamless and efficient way.
Control Statements
If, Elseif, Else Statements: Control structures that allow conditional execution of code blocks.
Switch Statements: Used to perform different actions based on multiple possible conditions of a
variable. It's more readable than multiple if-else conditions when handling many discrete cases.
Loops (While, Do-While, For Loops): Used to execute a block of code repeatedly.
o While Loop: Continues executing as long as a condition is true.
o Do-While Loop: Executes at least once before checking the condition.
o For Loop: Ideal for iterating a set number of times.
Functions
Defining and Using Functions: Functions allow you to encapsulate code into reusable
blocks.
Returning Values: Functions can return values to be used elsewhere in the program
using the return statement.
Passing Arguments to Functions: PHP supports passing both by value and by reference.
String Manipulation
o Multidimensional Arrays: Arrays within arrays, allowing more complex data structures.
Handling Forms in PHP: PHP is often used to handle HTML form submissions. Data from forms is
captured using $_GET and $_POST superglobal arrays.
Super Global Variables: Variables like $_GET, $_POST, $_SESSION, $_FILES, and
$_COOKIE are used to handle form data and user sessions.
Redirecting Pages: After form submission, PHP can be used to redirect users to another
page using header().
File Handling
Opening and Closing Files: Files are opened using fopen() and closed using fclose().
Reading and Writing Files: fread() reads data from a file, and fwrite() writes data to
a file.
Uploading and Downloading Files: Handling file uploads is managed via HTML forms
with the enctype="multipart/form-data" attribute, and PHP processes the upload
using the $_FILES superglobal.
Directory Operations: PHP allows for creating, reading, and removing directories
through functions like mkdir(), rmdir(), and scandir().
Relational Databases (RDBMS): Databases like MySQL follow a relational model, organizing data
in tables with relationships between them.
MySQLi and PDO: PHP offers two ways to connect to MySQL databases—MySQLi and PDO (PHP
Data Objects). Both allow for secure interaction with databases using prepared statements to
prevent SQL injection.
Performing CRUD Operations: PHP scripts can perform Create, Read, Update, and Delete (CRUD)
operations on a database. SQL queries like INSERT, SELECT, UPDATE, and DELETE are used in conjunction
with PHP.
Inserting Data: The INSERT INTO query is used to add new records.
Deleting Data: The DELETE query removes records from the database.
INDEX
1. Take values from the user and compute sum,
subtraction, multiplication, division, and exponent of
variables
<?php
$num1 = 10; // Example values
$num2 = 5;
Output:
<?php
// Circle
$radius = 5;
$circleArea = pi() * $radius *
$radius; echo "Area of Circle:
$circleArea<br>";
// Rectangle
$length = 10;
$width = 5;
$rectangleArea = $length * $width;
echo "Area of Rectangle: $rectangleArea<br>";
// Triangle
$base = 5;
$height = 7;
$triangleArea = 0.5 * $base *
$height; echo "Area of Triangle:
$triangleArea<br>";
// Square
$side = 4;
$squareArea = $side * $side;
echo "Area of Square: $squareArea<br>";
// Trapezoid
$a = 5;
$b = 7;
$trapezoidArea = 0.5 * ($a + $b) *
$height; echo "Area of Trapezoid:
$trapezoidArea<br>";
// Parallelogram
$base = 8;
$parallelogramArea = $base * $height;
echo "Area of Parallelogram: $parallelogramArea<br>";
?>
Output:
<?php
$a = 1;
$b = -5;
$c = 6;
$discriminant = $b * $b - 4 * $a * $c;
if ($discriminant > 0) {
$root1 = (-$b + sqrt($discriminant)) / (2 * $a);
$root2 = (-$b - sqrt($discriminant)) / (2 * $a);
<?php
$side1 = 5;
$side2 = 5;
$side3 = 7;
Output:
<?php
$num = 5;
for ($i = 1; $i <= 10; $i++) {
echo "$num x $i = " . ($num * $i) . "<br>";
}
?>
Output:
6. Calculate sum of natural numbers from one to n
<?php
$n = 10;
$sum = ($n * ($n + 1)) / 2;
echo "Sum of natural numbers up to $n is: $sum<br>"; ?>
Output:
Output:
<?php
$num = 5;
$factorial = 1;
Output:
9. Determine prime numbers within a specific range
<?php
$start = 1;
$end = 50;
function isPrime($num) { if
($num < 2) return false;for ($i =
2; $i <= sqrt($num); $i++) {
if ($num % $i == 0) return false;
}
return true;
}
Output:
<?php
$marks = [85, 90, 78, 92, 88];
$total = array_sum($marks); $average
= $total / count($marks);
echo "Average Marks: $average<br>";
Output:
11. Compute addition, subtraction, and multiplication of matrices
<?php
$matrix1 = [ [1, 2], [3, 4]];
$matrix2 = [ [5, 6], [7, 8]];
// Matrix Subtraction
$subtraction = []; for
($i = 0; $i < 2; $i++) {
for ($j
= 0; $j < 2; $j++) {
$subtraction[$i][$j] = $matrix1[$i][$j] - $matrix2[$i][$j];
}
}
// Matrix Multiplication
$multiplication = []; for ($i = 0;
$i < 2; $i++) { for ($j =
0; $j < 2; $j++) {
$multiplication[$i][$j]
= 0; for ($k = 0; $k <
2; $k++) {
$multiplication[$i][$j] += $matrix1[$i][$k] * $matrix2[$k][$j];
}
}
}
Output:
12. Count total number of vowels in a word “Develop & Empower
Individuals”
<?php
$vCount = 0;
$str = "Develop and Empower Individuals";
$str = strtolower($str);
?>
Output:
Output :
Pallindrome
Output :
$n = 10;
$l = 5;
$u = 50;
check_range($n , $l , $u);
?>
Output:
}
else if ($str[$i] >= 'a' && $str[$i] <= 'z') {
$lower++;
}
else {}
}
echo "Upper case letters: " ,
$upper,"<br>" ; echo "Lower case letters : " ,
$lower,"<br>" ;
}
Output :
Output :
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<h2>Login Form</h2>
<form action="authenticate.php"
method="POST">
<label
for="username">Username:</label><br>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password" required><br><br>
</body>
</html>
$valid_username = 'admin';
$valid_password = 'password123';
$username = $_POST['username'];
$password = $_POST['password'];
header('Location: profile.php');
exit(); } else {
echo "Invalid username or password.";
}
?>
19. Write a program to upload and download files.
A. Uploading files:
<!DOCTYPE html>
<html>
<body>
<form action="fileupload.php"
method="post"
enctype="multipart/form-data">
Directory<input type="text"
name="dirname" id="dirname"><br>
Select image to upload:
<input type="file"
name="fileToUpload"
id="fileToUpload"><br>
<input type="submit"
value="Upload Image"
name="submit">
</form>
</body>
</html>
B. Downloading files:
<?php
// Initialize a file URL to the variable
$url =
'https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png';
// Use basename() function to return the base name of file
$file_name = basename($url);
// Use file_get_contents() function to get the file
// from url and use file_put_contents() function to
// save the file by using base name
if (file_put_contents($file_name, file_get_contents($url)))
{
echo "File downloaded successfully";
}
else
{
echo "File downloading failed.";
}
?>
Output :
20. Design front page of college or department using graphics method
<?php
<!doctype html>
<html>
<head>
<title>GJIMT</title>
</head>
<body>
<?php include_once('includes/header.php');?>
<div class="banner">
<div class="container">
<div class="slider">
<div class="callbacks_container">
<ul class="rslides" id="slider">
<li>
<h3 style="color: #c54521; text-shadow: 2px
4px rgba(0, 0, 0, 0.5);" ><strong >GJIMT Student
Mangment System</strong></h3>
<div class="readmore">
<a href="user/login.php" style="border-radius:
250px">Student Login<i class="glyphicon glyphicon-
menu- right"> </i></a>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="welcome">
<div class="container">
<?php
$sql="SELECT * from tblpage where PageType='aboutus'";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $row)
{ ?>
<h2><?php echo htmlentities($row->PageTitle);?
></h2>
<p><?php echo ($row->PageDescription);?></p><?php
$cnt=$cnt+1;}} ?>
</div>
</div>
<div class="testimonials">
<div class="container">
<div class="testimonial-nfo">
<h3 style="color:#000000;"><strong
>Notices</strong></h3>
<marquee style="height:350px;
color:#000000;" direction ="up"
onmouseover="this.stop();"
onmouseout="this.start();">
<?php
$sql="SELECT * from tblpublicnotice";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $row)
{ ?>
<a href="view-public-notice.php?viewid=<?
php echo htmlentities ($row->ID);?>"
target="_blank" style="color:#000000; font-
size: 30px">
<?php echo htmlentities($row->NoticeTitle);?
>(<? php echo htmlentities($row->CreationDate);?
>)</a>
<hr /><br />
Output :
21. Insert Data
<?php
$servername = “localhost”;
$username = “my_user”;
$password = “my_password”;
$database = “my_database”;
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}
// Insert data
$sql = “INSERT INTO users (name, email, age) VALUES (‘John Doe’,
‘john.doe@example.com’, 30)”;
if (mysqli_query($conn, $sql)) {
echo “New record created successfully”;
} else {
echo “Error: ” . $sql . “<br>” . mysqli_error($conn);
}
?>
Output:
<?php
$servername = “localhost”;
$username = “my_user”;
$password = “my_password”;
$database = “my_database”;
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}
// Select data
$sql = “SELECT id, name, email, age FROM users”;
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// Output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo “id: ” . $row[“id”]. ” – Name: ” . $row[“name”]. ” – Email: ” . $row[“email”].
” – Age: ” . $row[“age”]. “<br>”;
}
} else {
echo “0 results”;
}
?>
Output:
<?php
$servername = “localhost”;
$username = “my_user”;
$password = “my_password”;
$database = “my_database”;
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}
// Update data
$sql = “UPDATE users SET age = 31 WHERE email = ‘john.doe@example.com'”;
if (mysqli_query($conn, $sql)) {
echo “Record updated successfully”;
} else {
echo “Error updating record: ” . mysqli_error($conn);
}
?>
Output:
<?php
$servername = “localhost”;
$username = “my_user”;
$password = “my_password”;
$database = “my_database”;
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}
// Delete data
$sql = “DELETE FROM users WHERE email = ‘john.doe@example.com'”;
if (mysqli_query($conn, $sql)) {
echo “Record deleted successfully”;
} else {
echo “Error deleting record: ” . mysqli_error($conn);
}
?>
Output: