0% found this document useful (0 votes)
19 views30 pages

PHP File - PHP - Merged

Uploaded by

digitalcash36
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
19 views30 pages

PHP File - PHP - Merged

Uploaded by

digitalcash36
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 30

PHP Basics and Data Types :

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.

Displaying Type Information

 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.

PHP Data Types

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

$intVar = 42; // Decimal

$intVar2 = 0x1A; // Hexadecimal (26 in decimal)

$intVar3 = 0755; // Octal (493 in decimal)

```

### 2. **Float (Floating Point Numbers or Doubles)**

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

$floatVar = 3.14; // Decimal number

$floatVar2 = 2.5e3; // Exponential notation (2.5 * 10^3 = 2500)

$floatVar3 = 7E-10; // 7 * 10^-10

### 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

$stringVar = "Hello, World!"; // Using double quotes


$stringVar2 = 'PHP is fun!'; // Using single quotes

```

- **Functions**:

- `strlen()`: Returns the length of a string.

- `strpos()`: Finds the position of the first occurrence of a substring in a string.

- `str_replace()`: Replaces all occurrences of a search string with a replacement string.

---

### 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

$arrayVar = array(1, 2, 3, 4);

```

- **Associative Array**:
```php

$assocArray = array("name" => "John", "age" => 25);

```

- **Multidimensional Arrays**: These are arrays that contain other arrays, which can be used to
represent more complex data structures.

- **Functions**:

- `count()`: Returns the number of elements in an array.

- `array_merge()`: Merges two or more arrays.

- `array_push()`: Adds elements to the end of an array.

---

### 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

$file = fopen("example.txt", "r"); // This is a file resource.

```

- **Common Resources**:

- Database connections (`mysqli_connect()`)

- File operations (`fopen()`, `fclose()`)

---

### Type Juggling vs. Type Casting in PHP

- **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

echo "5" + 10; // Outputs 15 (string "5" is converted to integer)

```
- **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";

$intVar = (int)$var; // Converts string to integer

### 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

 String Functions: PHP offers a plethora of functions to manipulate strings, including


strlen() for string length, strtoupper() for converting strings to uppercase, and
str_replace() for replacing parts of a string.
Arrays

 Array Types: Arrays in PHP can be of multiple types:

o Indexed Arrays: Arrays with numeric keys.

o Associative Arrays: Arrays with named keys.

o Multidimensional Arrays: Arrays within arrays, allowing more complex data structures.

Forms, File Handling, and Directories


Forms

 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.

Working with Directories

 Directory Operations: PHP allows for creating, reading, and removing directories
through functions like mkdir(), rmdir(), and scandir().

Database Connectivity with MySQL


Introduction to Databases

 Relational Databases (RDBMS): Databases like MySQL follow a relational model, organizing data
in tables with relationships between them.

Connecting PHP with MySQL

 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.

Basic Database Operations

 Inserting Data: The INSERT INTO query is used to add new records.

 Reading Data: SELECT queries retrieve data from tables.

 Updating Data: The UPDATE query modifies existing 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;

echo "Sum: " . ($num1 + $num2) . "<br>";


echo "Subtraction: " . ($num1 - $num2) .
"<br>"; echo "Multiplication: " . ($num1 *
$num2) . "<br>"; echo "Division: " . ($num1 /
$num2) . "<br>"; echo "Exponent: " . ($num1
** $num2) . "<br>";
?>

Output:

2. Find area of shapes (circle, rectangle, triangle,


square, trapezoid, and parallelogram)

<?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:

3. Compute and print roots of quadratic equation

<?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);

echo "Roots are: $root1 and $root2<br>";


} elseif ($discriminant == 0) {
$root = -$b / (2 * $a);

echo "Root is:


$root<br>";
} else {
echo "No real roots.<br>";
}
?>
Output:
4. Check if a triangle is isosceles

<?php
$side1 = 5;
$side2 = 5;
$side3 = 7;

if ($side1 == $side2 || $side2 == $side3 || $side1 ==


$side3) { echo "The triangle is isosceles.<br>";
} else {
echo "The triangle is not isosceles.<br>";
}
?>

Output:

5. Print multiplication table of a number input by the user

<?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:

7. Print Fibonacci series up to n numbers


<?php
$n = 10;
$fib = [0, 1];

for ($i = 2; $i < $n; $i++) {


$fib[] = $fib[$i - 1] + $fib[$i - 2];
}

echo implode(' ', $fib) . "<br>";


?>

Output:

8. Find factorial of any number

<?php
$num = 5;
$factorial = 1;

for ($i = 1; $i <= $num; $i++) {


$factorial *= $i;
}
echo "Factorial of $num is: $factorial<br>";
?>

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;
}

for ($i = $start; $i <= $end;


$i++) { if (isPrime($i)) {
echo "$i ";
}
}
?>

Output:

10. Compute Average and Grade of students' marks

<?php
$marks = [85, 90, 78, 92, 88];
$total = array_sum($marks); $average
= $total / count($marks);
echo "Average Marks: $average<br>";

if ($average >= 90) {


$grade = "A";
} elseif ($average >= 80) {
$grade = "B";
} elseif ($average >= 70) {
$grade = "C";
} else {
$grade = "D";
}
echo "Grade: $grade<br>";
?>

Output:
11. Compute addition, subtraction, and multiplication of matrices
<?php
$matrix1 = [ [1, 2], [3, 4]];
$matrix2 = [ [5, 6], [7, 8]];

// Matrix Addition $addition


= []; for ($i = 0; $i < 2;
$i++) { for ($j = 0; $j < 2;
$j++) {
$addition[$i][$j] = $matrix1[$i][$j] + $matrix2[$i][$j];
}
}

// 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];
}
}
}

echo "Matrix Addition: <br>";


print_r($addition);
echo "<br>Matrix Subtraction: <br>";
print_r($subtraction); echo "<br>Matrix
Multiplication: <br>"; print_r($multiplication);
?>

Output:
12. Count total number of vowels in a word “Develop & Empower
Individuals”
<?php
$vCount = 0;
$str = "Develop and Empower Individuals";
$str = strtolower($str);

for($i = 0; $i < strlen($str); $i++) {


if( $str[$i] == 'a' || $str[$i] == 'e' || $str[$i] == 'i' || $str[$i] == 'o' || $str[$i] == 'u')
{
$vCount++;
}
}
echo "Number of vowels : " , $vCount;
echo "<br>";

?>

Output:

13. Determine whether a string is palindrome or not?


<?php
function Palindrome($string){
if (strrev($string) ==
$string){ return 1;
}
else
{ return
0;
}
}
$original = "SoS";
if(Palindrome($original)){
echo "Palindrome";
}
else {
echo "Not a Palindrome";
}
?>

Output :
Pallindrome

14. Display word after Sorting in alphabetical order


<?php
$text = array("pranshu", "abhay", "raj", "sarbh",
"dimple"); sort($text); print_r($text); echo "<br>";
?>

Output :

15. Check whether a number is in a given range using functions.


<?php
function check_range($n , $l , $u) {

if ($n > $l && $n < $u){


echo "The number $n is between the range";
} else {
echo "The number is out of range";
}
}

$n = 10;
$l = 5;
$u = 50;

check_range($n , $l , $u);
?>

Output:

16. Write a program accepts a string and calculates number of


upper case letters and lower case letters available in that string.
<?php
function count_case($str)
{
$upper = 0;
$lower = 0;
for ($i = 0; $i < strlen($str); $i++)
{
if ($str[$i] >= 'A' && $str[$i] <= 'Z'){
$upper++;

}
else if ($str[$i] >= 'a' && $str[$i] <= 'z') {

$lower++;
}
else {}
}
echo "Upper case letters: " ,
$upper,"<br>" ; echo "Lower case letters : " ,
$lower,"<br>" ;
}

$str = "This Is PHP Class";


count_case($str);
?>

Output :

17. Design a program to reverse a string word by word


<?php
$Str = "october 13 on class php a is this";
$inpStrArray = explode(" ", $Str);
$revArr = array_reverse($inpStrArray);
echo "The reversed string words are : " . $revStr = implode(" ", $revArr); ?>

Output :

18. Write a program to create a login form. On submitting the


form, the user should navigate to profile page.
This file contains the login form

<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>

<input type="submit" value="Login">


</form>

</body>
</html>

This file handles the form submission and authentication


<?php
session_start();

$valid_username = 'admin';
$valid_password = 'password123';

$username = $_POST['username'];
$password = $_POST['password'];

if ($username === $valid_username && $password === $valid_password) {


$_SESSION['username'] = $username;

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 />

<?php $cnt=$cnt+1;}} ?>


</marquee></div>
</div>
</div>
<?php include_once('includes/.footerphp');?>
</body>
</html>

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:

22. Select 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());
}

// 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:

23. Update 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());
}
// 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:

24. Delete 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());
}
// 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:

You might also like