0% found this document useful (0 votes)
28 views

PHP Unit 3,4,5

Uploaded by

samarthdubey379
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

PHP Unit 3,4,5

Uploaded by

samarthdubey379
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

UNIT - 3

A Document that containing blank fields, that the user can fill the data or user can select the data. Casually the
data will store in the data base
To create a web form in PHP, you will need to use the following HTML tags:
•form: This tag defines the beginning and end of the form.
•input: This tag defines a form input element.
•label: This tag defines a label for a form input element.
•select: This tag defines a form select element.
•option: This tag defines an option for a form select element.
•submit: This tag defines a form submit button.

Processing Web Form


To process a web form in PHP, you will need to use the following steps:
1.Create a web form.
2.Write a PHP script to process the form data.
3.Save the PHP script in the same directory as the HTML form.
4.Set the form action to the PHP script.
Here is an example of a simple web form in PHP:
<form name="contact_form" method="post" action="contact.php">
<input type="text" name="name" placeholder="Your name">
<input type="email" name="email" placeholder="Your email">
<input type="submit" value="Submit">
</form>
Here is an example of a PHP script to process the form data:
<?php
$name = $_POST["name"];
$email = $_POST["email"];

echo "Your name is $name and your email address is $email.";


?>
When the user submits the form, the data will be sent to the contact.php file. In this file, you can use the $_POST super
global to access the data that was submitted by the form.

Capturing form Data


To capture form data in PHP, you can use the following steps:
1.Create a web form.
2.Set the form method to "post".
3.In the form action attribute, specify the path to the PHP script that will handle the form data.
4.In the PHP script, use the $_POST superglobal to access the form data.
Here is an example of a simple web form in PHP:
<form name="contact_form" method="post" action="contact.php">
<input type="text" name="name" placeholder="Your name">
<input type="email" name="email" placeholder="Your email">
<input type="submit" value="Submit">
</form>

Here is an example of a PHP script to process the form data:


<?php
$name = $_POST["name"];
$email = $_POST["email"];

echo "Your name is $name and your email address is $email.";


?>
When the user submits the form, the data will be sent to the contact.php file. In this file, you can use the $_POST superglobal to access
the data that was submitted by the form.
Passing information between Pages
In PHP, Here are some commonly used methods:

1.URL Parameters:
- You can pass information through the URL by appending parameters using the
GET method.
- In the sending page, construct the URL with the parameters you want to pass:
php
$id = 123;
$name = "John Doe";
$url = "destination.php?id=" . urlencode($id) . "&name=" . urlencode($name);
// Redirect to the destination page
header("Location: " . $url);
exit();
```
- In the receiving page (destination.php), retrieve the parameters using the
`$_GET` superglobal:
php
$id = $_GET['id'];
$name = $_GET['name'];
2. Hidden Form Fields:
- Include hidden input fields within an HTML form to pass
data between pages.
- In the sending page, set the values of hidden fields within
the form:
```html
<form method="post" action="destination.php">
<input type="hidden" name="id" value="123">
<input type="hidden" name="name" value="John Doe">
<input type="submit" value="Submit">
</form>
```
- In the receiving page (destination.php), retrieve the values
using the `$_POST` superglobal:
```php
$id = $_POST['id'];
$name = $_POST['name'];
3. Sessions:
- Sessions allow you to store data that can be accessed across multiple pages for
a specific user session.
- In the sending page, store the values in session variables:
```php
session_start();
$_SESSION['id'] = 123;
$_SESSION['name'] = "John Doe";
```
- In the receiving page, retrieve the session values after starting the session:
```php
session_start();
$id = $_SESSION['id'];
$name = $_SESSION['name'];
```

4. Cookies:
- Cookies are another way to pass information between pages, as they are
stored on the user's browser.
- In the sending page, set cookie values:
```php
$id = 123;
$name = "John Doe";
setcookie("id", $id, time() + 3600, "/");
setcookie("name", $name, time() + 3600, "/");
```
- In the receiving page, retrieve the cookie values:
```php
$id = $_COOKIE['id'];
$name = $_COOKIE['name'];
GET Method

The $_GET array is a very useful tool for collecting data from the URL. You can use it to collect information from users, such
as their name, age, or email address. You can also use it to collect information about the page that the user is visiting, such
as the page's ID or the page's title.
Here are some examples of how you can use the $_GET array:
•You can use it to collect information from users, such as their name, age, or email address.
•You can use it to collect information about the page that the user is visiting, such as the page's ID or the page's title.
•You can use it to redirect the user to a different page.
•You can use it to search for data in a database.
•You can use it to control the behavior of your website.
The $_GET array is a powerful tool that can be used to do a variety of things. It is a valuable asset for any PHP developer.

The $_GET array will contain the following values:

$name = "John"
$age = 30
You can access the values in the $_GET array using the following syntax:
$name = $_GET["name"];
$age = $_GET["age"];
You can also use the foreach loop to iterate over the $_GET array:
foreach ($_GET as $key => $value) {
echo "$key = $value<br>"; }
POST Method
The $_POST array is a very useful tool for collecting data from forms. You can use it to collect information from users, such as their name, age, or email
address. You can also use it to collect information about the form that the user is submitting, such as the form's ID or the form's title.

Here are some examples of how you can use the $_POST array:

You can use it to collect information from users, such as their name, age, or email address.
You can use it to collect information about the form that the user is submitting, such as the form's ID or the form's title.
You can use it to redirect the user to a different page.
You can use it to search for data in a database.
You can use it to control the behavior of your website.
The $_POST array is a powerful tool that can be used to do a variety of things. It is a valuable asset for any PHP developer.

$name = $_POST["name"];
$email = $_POST["email"];

foreach ($_POST as $key => $value) {


echo "$key = $value<br>";
}
Multi Value Fields
Multi-value fields are fields in a form that can accept multiple values. For example, a checkbox field can be used
to allow the user to select multiple options, and a multi-select list box can be used to allow the user to select
multiple items from a list.

In PHP, you can handle multi-value fields using arrays. An array allows you to store
multiple values under a single variable. Here's an example of how you can work with
multi-value fields in PHP:

HTML form:

<form method="POST" action="process.php">


<label for="colors">Select your favorite colors:</label><br>
<select name="colors[]" multiple>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select><br><br>
<input type="submit" value="Submit">
</form>
process.php:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$selectedColors = $_POST['colors']; // $_POST['colors'] will be an array

// Displaying selected colors


if (!empty($selectedColors)) {
echo "You have selected the following colors:<br>";
foreach ($selectedColors as $color) {
echo $color . "<br>";
}
} else {
echo "Please select at least one color.";
}
}
?>

In the above example, the HTML form includes a `select` element with
the `multiple` attribute. The `name` attribute is set as `colors[]` to
create an array in PHP. When the form is submitted, the selected colors
are sent as an array in the `$_POST['colors']` variable.
Validating a Web Form
Validating a web form in PHP is a process of checking the input data submitted by the user to ensure that it is valid and meets the
required criteria.

<html >
<head>
<title>Document</title>
</head>
<body>
<form method="POST" action="process.php">
<label for="name">Name:</label>
<input type="text" name="name" required><br><br>

<label for="email">Email:</label>
<input type="email" name="email" required><br><br>

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


</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Validate name field
if (empty($_POST['name'])) {
echo "Name is required.<br>";
} else {
$name = $_POST['name'];
// Additional validation rules for name, if necessary
}

// Validate email field


if (empty($_POST['email'])) {
echo "Email is required.<br>";
} else {
$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format.<br>";
}
}

// If there are no validation errors


if (!isset($nameError) && !isset($emailError)) {
// Process the form data or perform further actions
echo "Form submitted successfully.";
}
}
?>

</body>
</html>
Exception and Error Handling

Exception and error handling in PHP allows you to catch and handle unexpected situations or errors that may occur
during the execution of your code. PHP provides mechanisms to handle both exceptions and errors. Here's an
overview of exception handling and error handling in PHP:

1. Exception Handling:
Exceptions are used to handle exceptional or error conditions that occur during the execution of code. You can
throw an exception when an error occurs and catch it in an appropriate catch block.

```php
try {
// Code that may throw an exception
throw new Exception("Something went wrong.");
} catch (Exception $e) {
// Handle the exception
echo "Exception: " . $e->getMessage();
}
```
2. Error Handling:
Errors are different from exceptions and usually represent fatal or non-recoverable errors that may occur during the execution of your code. PHP provides
error handling mechanisms using error reporting and custom error handlers.

- Error Reporting:
To control how errors are displayed, you can use the `error_reporting` directive in your PHP configuration file or use the `error_reporting` function in your
code. For example:

```php
error_reporting(E_ALL); // Report all errors
```

Setting `error_reporting` to `E_ALL` will display all types of errors.

- Custom Error Handlers:


You can define custom error handlers in PHP to handle errors based on your requirements. The `set_error_handler` function is used to set a custom error
handler function.

```php
function customErrorHandler($errno, $errstr, $errfile, $errline) {
echo "Error: [$errno] $errstr";
}

set_error_handler("customErrorHandler");
```
Cookies and Session Handling
Cookies and session handling are important features in PHP for maintaining state and storing user data across multiple requests. Here's an introduction to
cookies and session handling in PHP:

1. Cookies:
Cookies are small pieces of data stored on the client-side (user's browser) that are sent back to the server with each subsequent request. Cookies are
commonly used to store user preferences, session identifiers, and other information.

- Setting a cookie:
```php
setcookie("name", "value", time() + 3600, "/");
```

In the above example, a cookie named "name" is set with a value of "value". The third parameter sets the expiration time (in seconds since the Unix
epoch), and the fourth parameter ("/") specifies the path on the server where the cookie is valid.

- Accessing a cookie:
```php
echo $_COOKIE["name"];
```

You can access the value of a cookie using the `$_COOKIE` superglobal array.

- Deleting a cookie:
```php
setcookie("name", "", time() - 3600, "/");
```

To delete a cookie, you can set its expiration time to a time in the past.

Note: Cookies are stored on the client-side and can be manipulated by users, so avoid storing sensitive or critical information in cookies. Consider using
secure and encrypted methods for sensitive data.
2. Sessions:
Sessions provide a way to store and retrieve user data on the server-side. Unlike cookies, session data is stored on the server and identified by a unique
session ID stored in a cookie on the client-side.

- Starting a session:
```php
session_start();
```

The `session_start()` function is used to start a session and enable session functionality in PHP.

- Storing session data:


```php
$_SESSION["username"] = "John";
```

You can store session data in the `$_SESSION` superglobal array.

- Accessing session data:


```php
echo $_SESSION["username"];
```

- Destroying a session:
```php
session_destroy();
```

The `session_destroy()` function is used to destroy the current session and delete all session data.

Note: Session data is stored on the server, which makes it more secure compared to cookies. However, session data can still be vulnerable to session
hijacking or session fixation attacks. To mitigate such risks, consider implementing security measures like session regeneration and session expiration.
UNIT - 4
PHP supported databases
PHP supports a wide range of databases, including:
•MySQL
•MariaDB
•PostgreSQL
•SQLite
•Oracle
•IBM DB2
•Microsoft SQL Server
•MongoDB
•CUBRID
•dBase
•Firebird/InterBase
Installation and configuration of MySQL
To install and configure MySQL on Windows for use with PHP, you can follow these steps:

Download MySQL: Visit the official MySQL website (https://dev.mysql.com/downloads/) and download the MySQL Installer for Windows. Choose the
appropriate version (Community or Commercial) and select the 64-bit or 32-bit installer based on your system.

Run the MySQL Installer: Double-click the downloaded MySQL Installer executable to launch the installer. It will guide you through the installation process.

Select Installation Type: Choose the "Developer Default" installation type, which includes MySQL Server, MySQL Shell, and other useful components for
development.

Choose Setup Type: Select "Server Only" to install only the MySQL Server component. If you need additional features or tools, you can choose a different setup
type.

Check Requirements: The installer will check if your system meets the requirements for installation. Make sure all the requirements are met, and if any issues
are reported, resolve them before proceeding.

Configure MySQL Server: Set a root password for the MySQL Server. Make sure to remember this password as you will need it to connect to the MySQL
database.

Select MySQL Products: You can choose to install additional MySQL products or simply proceed with the default selection.

Install: Click the "Execute" button to start the installation process. It may take some time to complete.

Configure MySQL Server: After the installation is finished, the installer will provide options to configure the MySQL Server. You can choose the default
configuration or customize it based on your requirements.

Start MySQL Server: Once the configuration is completed, click the "Next" button to start the MySQL Server.
Checking Configuration
To check the configuration of PHP, you can follow these steps:

1. Create a PHP file: Create a new file with a .php extension, for example, `phpinfo.php`.

2. Open the file in a text editor and add the following line of code:

```php
<?php
phpinfo();
?>
```

3. Save the file and place it in the root directory of your web server. If you are using a local development environment like XAMPP or WampServer, the root
directory is typically `htdocs`.

4. Start your web server and make sure PHP is running. Access the PHP file through a web browser by visiting `http://localhost/phpinfo.php` (replace
`localhost` with the appropriate hostname if necessary).

5. The PHP `phpinfo()` function will generate a detailed page with information about your PHP configuration.

The PHP configuration page will display a wealth of information, including:

- PHP version
- Server information (e.g., Apache or Nginx)
- Configuration settings and their respective values
- Loaded PHP extensions and modules
- PHP environment variables
- PHP directives and their current values
- PHP options and their settings
Connecting to Database
To connect to a database in PHP
Using MySQLi extension
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

// Create a connection
$conn = new mysqli($servername, $username, $password,
$database);

// Check the connection


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Connection successful, perform database operations...

// Close the connection


$conn->close();
?>
selecting a database
To select a specific database in PHP
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

// Create a connection
$conn = new mysqli($servername, $username, $password);

// Check the connection


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Select the desired database


$conn->select_db($database);

// Connection successful, perform database operations...

// Close the connection


$conn->close();
?>
<?php
adding table $servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

// Create a connection
$conn = new mysqli($servername, $username, $password, $database);

// Check the connection


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// SQL statement to create a table


$sql = "CREATE TABLE your_table (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(50)
)";

// Execute the query


if ($conn->query($sql) === TRUE) {
echo "Table created successfully";
} else {
echo "Error creating table: " . $conn->error;
}

// Close the connection


$conn->close();
?>
altering table <?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

// Create a connection
$conn = new mysqli($servername, $username, $password, $database);

// Check the connection


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// SQL statement to alter a table


$sql = "ALTER TABLE your_table ADD COLUMN age INT(3)";

// Execute the query


if ($conn->query($sql) === TRUE) {
echo "Table altered successfully";
} else {
echo "Error altering table: " . $conn->error;
}

// Close the connection


$conn->close();
?>
<?php
inserting $servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

// Create a connection
$conn = new mysqli($servername, $username, $password, $database);

// Check the connection


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Data to be inserted
$name = "John Doe";
$email = "[email protected]";

// SQL statement to insert data


$sql = "INSERT INTO your_table (name, email) VALUES ('$name', '$email')";

// Execute the query


if ($conn->query($sql) === TRUE) {
echo "Data inserted successfully";
} else {
echo "Error inserting data: " . $conn->error;
}

// Close the connection


$conn->close();
?>
deleting and modifying data in a table

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password"; // Modifying data
$database = "your_database"; $idToUpdate = 2;
$newName = "Jane Doe";
// Create a connection
$conn = new mysqli($servername, $username, $password, $database);
// SQL statement to update data
// Check the connection $sqlUpdate = "UPDATE your_table SET name = '$newName'
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
WHERE id = $idToUpdate";
}
// Execute the update query
// Deleting data if ($conn->query($sqlUpdate) === TRUE) {
$idToDelete = 1;
echo "Data updated successfully";
// SQL statement to delete data } else {
$sqlDelete = "DELETE FROM your_table WHERE id = $idToDelete"; echo "Error updating data: " . $conn->error;
// Execute the delete query
}
if ($conn->query($sqlDelete) === TRUE) {
echo "Data deleted successfully"; // Close the connection
} else { $conn->close();
echo "Error deleting data: " . $conn->error;
} ?>
<?php
retrieving data $servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

// Create a connection
$conn = new mysqli($servername, $username, $password, $database);

// Check the connection


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// SQL statement to retrieve data


$sql = "SELECT * FROM your_table";

// Execute the query and get the result set


$result = $conn->query($sql);

// Check if any rows were returned


if ($result->num_rows > 0) {
// Loop through each row
while ($row = $result->fetch_assoc()) {
// Access the column values of each row
$id = $row["id"];
$name = $row["name"];
$email = $row["email"];

// Perform operations with the retrieved data


echo "ID: " . $id . ", Name: " . $name . ", Email: " . $email . "<br>";
}
} else {
echo "No data found";
}

// Close the connection


$conn->close();
?>
performing queries <?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

// Create a connection
$conn = new mysqli($servername, $username, $password, $database);

// Check the connection


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// SQL query
$query = "SELECT * FROM your_table";

// Perform the query


$result = $conn->query($query);

// Check if the query was successful


if ($result) {
// Process the result set
while ($row = $result->fetch_assoc()) {
// Access the column values of each row
$id = $row["id"];
$name = $row["name"];
$email = $row["email"];

// Perform operations with the retrieved data


echo "ID: " . $id . ", Name: " . $name . ", Email: " . $email . "<br>";
}
} else {
echo "Error executing query: " . $conn->error;
}

// Close the connection


$conn->close();
?>
processing result sets <?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

// Create a connection
$conn = new mysqli($servername, $username, $password, $database);

// Check the connection


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// SQL query
$query = "SELECT * FROM your_table";

// Perform the query


$result = $conn->query($query);

// Check if the query was successful


if ($result) {
// Process the result set
while ($row = $result->fetch_assoc()) {
// Access the column values of each row
$id = $row["id"];
$name = $row["name"];
$email = $row["email"];

// Perform operations with the retrieved data


echo "ID: " . $id . ", Name: " . $name . ", Email: " . $email . "<br>";
}
} else {
echo "Error executing query: " . $conn->error;
}

// Close the connection


$conn->close();
?>
UNIT- 5
Code re-use

Code re-use in PHP can be achieved through various techniques such as ```php
functions, classes, and libraries. Here are a few approaches to code re-use in PHP: <?php
class Calculator {
1. Functions: Functions allow you to encapsulate a set of instructions that can be public function add($a, $b) {
called multiple times throughout your code. By defining functions, you can easily return $a + $b;
reuse code without duplicating it. Here's an example: }

```php public function subtract($a, $b) {


<?php return $a - $b;
function greet($name) { }
echo "Hello, $name!"; }
}
// Create an instance of the Calculator class
// Call the function $calculator = new Calculator();
greet("John");
greet("Jane"); // Use the methods of the Calculator class
?> $result = $calculator->add(5, 3);
``` echo "Addition: $result\n";

2. Classes: Classes provide a way to define reusable code structures. You can $result = $calculator->subtract(10, 4);
create a class with properties and methods, and then instantiate objects from echo "Subtraction: $result\n";
that class to reuse the code. Here's an example: ?>
```
3. Libraries: PHP provides various libraries and frameworks that offer
reusable code for common tasks. You can include these libraries in your
project and utilize their functionality to save time and effort. Popular
PHP libraries include Symfony, Laravel, and CodeIgniter.

4. Include and Require Statements: PHP allows you to include and


require external PHP files into your code. This enables you to reuse
code snippets or entire files in multiple parts of your application. For
example:

```php
<?php
// File: utilities.php
function formatDate($date) {
return date("Y-m-d", strtotime($date));
}

// File: index.php
require_once "utilities.php";

$date = "2023-05-21";
$formattedDate = formatDate($date);
echo "Formatted Date: $formattedDate";
?>
```
require() In PHP, the `require()` function is used to include and execute an external PHP file within
another PHP file. It ensures that the specified file is required and must be present for the script
to continue executing. If the file cannot be found or there is an error during its inclusion, a fatal
error is generated, and the script execution stops.

The `require()` function can be used in two forms: `require($filename)` and `require $filename`.
Here's an example of how to use `require()` in PHP:

```php
<?php
// File: utils.php
function greet($name) {
echo "Hello, $name!";
}
?>

<?php
// File: index.php
require('utils.php');

greet("John");
?>
```
The `require_once()` function can also be used, which has the same behavior as `require()`, but
it ensures that the specified file is included only once, even if it is called multiple times in the
script. This prevents duplicate inclusions and potential redeclaration errors.

```php
<?php
// File: index.php
require_once('utils.php');
require_once('utils.php');

greet("John");
?>
```
include()
In PHP, the `include()` function is used to include and execute an external PHP file within another PHP file. It allows you to include a file and continue executing the
script even if the file cannot be found or there is an error during inclusion. If the file is not found, a warning is generated, but the script execution continues.

The `include()` function can be used in two forms: `include($filename)` and `include $filename`. Here's an example of how to use `include()` in PHP:

```php
<?php
// File: utils.php
function greet($name) {
echo "Hello, $name!";
}
?>

<?php
// File: index.php
include 'utils.php';

greet("John");
?>
```
Similar to `require()`, you can also use `include_once()` to include a file only once, even if it is called multiple times in the script. This prevents duplicate inclusions
and potential redeclaration errors.

```php
<?php
// File: index.php
include_once 'utils.php';
include_once 'utils.php';

greet("John");
?>
```
the include_path
The `include_path` is a configuration setting in PHP that specifies the directories where PHP looks for files when using the `include()` or
`require()` functions. It is an important setting that determines the search path for including files using relative paths.

The `include_path` can be set in several ways:

1. In the PHP configuration file (php.ini): You can set the `include_path` directive in the php.ini file. Open the php.ini file and modify the value
of `include_path` to include the directories you want to search for included files. For example:

```
include_path = ".:/path/to/directory"
```

The `.` represents the current directory, and you can specify multiple directories separated by a colon (`:`) on Unix-like systems or a
semicolon (`;`) on Windows systems.

2. Using the `ini_set()` function: You can also set the `include_path` at runtime using the `ini_set()` function in your PHP script. For example:

```php
<?php
ini_set('include_path', '.:/path/to/directory');
?>

This will change the `include_path` for the current script execution.

3. Using the `set_include_path()` function: PHP provides the `set_include_path()` function, which allows you to set the `include_path`
dynamically within your script. For example:

```php
<?php
set_include_path('.:/path/to/directory');
?>
```

This function sets the `include_path` for the current script execution and overrides any previously set `include_path` value.

When you use the include() or require() functions with a relative path, PHP will search for the file in the directories specified in the include_path in the order they are
defined. If the file is not found in any of the directories, PHP will generate a warning or a fatal error depending on whether you used include() or require()
PHP file permissions

In PHP, you can use the `chmod()` function to change file permissions. The `chmod()` function
allows you to set the permissions of a file or directory on the server's file system.

Here's the syntax for using the `chmod()` function in PHP:

```php
bool chmod(string $filename, int $permissions)
```

The `chmod()` function takes two parameters:

1. `$filename` (string): The path to the file or directory whose permissions you want to change.
2. `$permissions` (int): The new permissions to set, represented as an octal number.

To set file permissions, you need to specify the desired permissions using the octal number
representation. For example, to set read and write permissions for the owner, read-only
permissions for the group, and no permissions for others, you would use the octal value 0640.

Here's an example of using `chmod()` function in PHP:

```php
$file = 'path/to/file.txt';
$permissions = 0640;

// Change file permissions


if (chmod($file, $permissions)) {
echo "File permissions changed successfully.";
} else {
echo "Failed to change file permissions.";
}
```
working with files
Working with files in PHP involves performing various operations such
as creating, reading, writing, and deleting files. Here are some common
file operations and their corresponding PHP functions:

1. Opening a File:
- `fopen()`: Opens a file in different modes (read, write, append, etc.)
and returns a file pointer for further operations.

2. Reading from a File:


- `fgets()`: Reads a line from an open file.
- `fread()`: Reads a specified number of bytes from an open file.
- `file_get_contents()`: Reads the entire contents of a file into a string.

3. Writing to a File:
- `fwrite()`: Writes a string to an open file.
- `file_put_contents()`: Writes a string to a file (overwrites existing
content).

4. Appending to a File:
- `fputs()`: Writes a string to an open file (appends to the existing
content).
- `file_put_contents()`: Appends a string to a file.

5. Closing a File:
- `fclose()`: Closes an open file.
6. Checking File Existence and Information:
- `file_exists()`: Checks if a file or directory exists.
- `is_file()`: Checks if a path is a regular file.
- `is_dir()`: Checks if a path is a directory.
- `filesize()`: Returns the size of a file.

7. Deleting a File:
- `unlink()`: Deletes a file.

Here's an example that demonstrates how to create a file, write content to it, and
read from it:

```php
$file = 'path/to/file.txt';

// Open file for writing


$handle = fopen($file, 'w');

// Write content to the file


fwrite($handle, 'Hello, world!');
fclose($handle);

// Open file for reading


$handle = fopen($file, 'r');

// Read content from the file


$content = fread($handle, filesize($file));
fclose($handle);

echo $content; // Output: Hello, world!


```
Here's a simple example that demonstrates some of these functions:

file system functions ```php


<?php
// Check if a file exists
$filename = 'example.txt';
Certainly! Here are some commonly used file system functions in PHP: if (file_exists($filename)) {
echo "The file $filename exists.";
} else {
1. **file_exists($filename):** Checks if a file or directory exists. echo "The file $filename does not exist.";
2. **is_file($filename):** Determines if a given path is a regular file. }
3. **is_dir($dirname):** Determines if a given path is a directory.
// Create a directory
4. **mkdir($dirname, $mode = 0777, $recursive = false):** Creates a $dirname = 'mydir';
directory. if (!is_dir($dirname)) {
5. **rmdir($dirname):** Removes a directory. mkdir($dirname);
echo "Directory $dirname created successfully.";
6. **unlink($filename):** Deletes a file. } else {
7. **rename($oldname, $newname):** Renames a file or directory. echo "Directory $dirname already exists.";
8. **copy($source, $destination):** Copies a file. }
9. **file_get_contents($filename):** Reads an entire file into a string. // Read a file into an array
10. **file_put_contents($filename, $data, $flags = 0, $context = null):** $lines = file('example.txt');
Writes data to a file. foreach ($lines as $line) {
echo $line;
11. **fopen($filename, $mode):** Opens a file or URL for reading or }
writing.
12. **fwrite($handle, $string):** Writes a string to an open file. // Write data to a file
$data = "Hello, World!";
13. **fread($handle, $length):** Reads data from an open file. file_put_contents('output.txt', $data);
14. **fclose($handle):** Closes an open file. echo "Data written to file successfully.";
15. **file($filename):** Reads a file into an array, with each element
// Delete a file
representing a line. $file = 'example.txt';
if (file_exists($file)) {
These functions allow you to perform various operations on files and unlink($file);
echo "File $file deleted successfully.";
directories, such as checking their existence, creating or deleting them, } else {
renaming or copying them, reading their contents, and writing data to echo "File $file does not exist.";
them. }
?>
```
file input and output In this example, `fopen()` opens the file in read-only mode ('r'), `fgets()` reads each line from
the file, and `fclose()` closes the file handle.
In PHP, you can perform file input and output operations using various functions and
techniques. Here's an overview of file input and output in PHP: **File Output: Writing to a File**
To write to a file, you can use functions like `file_put_contents()`, `fwrite()`, or `fputs()`. Here's
**File Input: Reading from a File** an example using `file_put_contents()`:
To read from a file, you can use functions like `file_get_contents()`, `fread()`, or `fgets()`.
Here's an example using `file_get_contents()`: ```php
<?php
```php $file = 'output.txt';
<?php $data = "Hello, World!";
$file = 'example.txt'; file_put_contents($file, $data);
$content = file_get_contents($file); echo "Data written to file successfully.";
echo $content; ?>
?> ```
``` Alternatively, you can use the `fopen()`, `fwrite()`, and `fclose()` functions to write to a file:
In this example, the `file_get_contents()` function is used to read the entire contents of ```php
the file "example.txt" into the `$content` variable, which is then displayed using `echo`. <?php
$file = 'output.txt';
Alternatively, you can use the `fopen()`, `fread()`, and `fclose()` functions to read from a $handle = fopen($file, 'w');
file in smaller chunks: if ($handle) {
fwrite($handle, "Hello, World!");
```php fclose($handle);
<?php echo "Data written to file successfully.";
$file = 'example.txt'; }
$handle = fopen($file, 'r'); ?>
if ($handle) { ```
while (($line = fgets($handle)) !== false) {
echo $line; In this example, `fopen()` opens the file in write mode ('w'), `fwrite()` writes the string to the
} file, and `fclose()` closes the file handle.
fclose($handle);
}
?>
```
working with directory

Creating a Directory Deleting a Directory


To create a directory in PHP, you can use the mkdir() function. To delete a directory in PHP, you can use the rmdir() function.
Here's an example: Note that the directory must be empty for the deletion to
succeed. Here's an example:
php
Copy code php
<?php Copy code
$directory = 'mydir'; <?php
if (!is_dir($directory)) { $directory = 'mydir';
mkdir($directory); if (is_dir($directory)) {
echo "Directory $directory created successfully."; rmdir($directory);
} else { echo "Directory $directory deleted successfully.";
echo "Directory $directory already exists."; } else {
} echo "Directory $directory does not exist.";
?> }
In this example, the mkdir() function is used to create a ?>
directory named "mydir". Before creating the directory, we In this example, the rmdir() function is used to delete the
check if it already exists using the is_dir() function. directory named "mydir" if it exists and is empty.
changing a directory
To change the current working directory in PHP, you can use the
`chdir()` function. Here's an example:

```php
<?php
// Get the current working directory
$currentDirectory = getcwd();
echo "Current Directory: $currentDirectory <br>";

// Change to a different directory


$directory = 'mydir';
if (chdir($directory)) {
// Get the updated current working directory
$currentDirectory = getcwd();
echo "Current Directory: $currentDirectory";
} else {
echo "Failed to change directory to $directory.";
}
?>
```

In this example, we first use the `getcwd()` function to retrieve the


current working directory and display it. Then, we specify the directory
name that we want to change to as the `$directory` variable.
Here are the steps to handle file uploads and set the directory in PHP:
file uploads
1. Create a directory to store uploaded files: First, create a directory on your server where you want to store the uploaded files. Ensure that the directory
has appropriate write permissions to allow file uploads.

2. Set the file upload directory in PHP configuration: In your PHP code, you need to set the `upload_tmp_dir` and `upload_max_filesize` directives in the
PHP configuration. This is usually done in the `php.ini` file. Here's an example:

```ini
upload_tmp_dir = /path/to/upload/directory
upload_max_filesize = 10M
```
3. Handle file upload in PHP code: In your PHP script that handles file uploads, you can access the uploaded files and move them to the desired directory.
Here's an example:

```php
<?php
$uploadDirectory = '/path/to/upload/directory/';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {


$file = $_FILES['file'];

// Check for errors


if ($file['error'] === UPLOAD_ERR_OK) {
$tmpName = $file['tmp_name'];
$filename = $file['name'];
$destination = $uploadDirectory . $filename;

// Move the uploaded file to the desired directory


if (move_uploaded_file($tmpName, $destination)) {
echo 'File uploaded successfully.';
} else {
echo 'Failed to move uploaded file.';
}
} else {
echo 'File upload error: ' . $file['error'];
}
}
?>
```
introduction to object oriented programming with PHP

Object-oriented programming (OOP) is a programming paradigm that organizes code around objects, which are instances of classes. It
allows you to structure your code in a more modular, reusable, and maintainable way. PHP supports object-oriented programming, and
here's a brief introduction to the key concepts of OOP in PHP:

**Classes and Objects:**


In OOP, a class is a blueprint or template that defines the properties (attributes) and behaviors (methods) of an object. An object is an
instance of a class. In PHP, you can define a class using the `class` keyword. Here's an example:

```php
class Car {
// Properties
public $brand;
public $color;

// Method
public function startEngine() {
echo "Engine started!";
}
}
```

In this example, we define a `Car` class with two properties (`$brand` and `$color`) and a method (`startEngine()`). The properties
represent the characteristics of a car, and the method represents its behavior.
To create an object from a class, you can use the `new` keyword:

```php
$myCar = new Car();
```

Now, `$myCar` is an object of the `Car` class.

**Accessing Properties and Methods:**


You can access properties and methods of an object using the object operator (`->`).
Here's an example:

```php
$myCar->brand = "Toyota";
$myCar->color = "Blue";
$myCar->startEngine();
```

In this example, we set the values of the `$brand` and `$color` properties of `$myCar`
object, and call the `startEngine()` method.
**Constructor and Destructor:**
In PHP, you can define a constructor and destructor methods in a class. The constructor method is called automatically when an object
is created, and the destructor method is called when an object is destroyed. Here's an example:

```php
class Car {
public $brand;

public function __construct($brand) {


$this->brand = $brand;
echo "A car of brand $this->brand is created.";
}

public function __destruct() {


echo "The car of brand $this->brand is destroyed.";
}
}

$myCar = new Car("Toyota");


unset($myCar);
```

In this example, the `__construct()` method sets the value of the `$brand` property and displays a message when a new car object is
created. The `__destruct()` method displays a message when the car object is destroyed. The `unset()` function is used to destroy the
object explicitly.
**Inheritance:**
Inheritance allows you to create new classes based on existing classes. The new class, called a derived or child class, inherits
the properties and methods of the parent class. PHP supports single inheritance, meaning a class can inherit from only one
parent class. Here's an example:

```php
class SportsCar extends Car {
public function accelerate() {
echo "The sports car is accelerating!";
}
}

$sportsCar = new SportsCar();


$sportsCar->brand = "Ferrari";
$sportsCar->startEngine();
$sportsCar->accelerate();
```

In this example, the `SportsCar` class is derived from the `Car` class using the `extends` keyword. The `SportsCar` class
inherits the `brand` property and `startEngine()` method from the `Car` class, and defines its own `accelerate()` method.

These are some of the fundamental concepts of object-oriented programming in PHP. OOP provides powerful tools for
structuring and organizing code, promoting code reusability, and creating modular applications

You might also like