Contents

PHP Advance

PHP Superglobals

Introduction to Superglobal Variables in PHP

Superglobals are built-in array variables in PHP that allow developers to access important data about requests or scripts. These superglobals can be accessed globally from any part of your code, such as functions or classes, without requiring special declarations like global variables. They are especially useful for handling data transfer between pages, dealing with requests, and managing server information.

Here’s a list of the available superglobal variables in PHP:

  • $GLOBALS
  • $_SERVER
  • $_REQUEST
  • $_GET
  • $_POST
  • $_SESSION
  • $_COOKIE
  • $_FILES
  • $_ENV

Let’s take a closer look at some of these superglobals:

1. $GLOBALS Superglobal :$GLOBALS is used to access global variables from any part of the PHP script. PHP stores all global variables in the $GLOBALS array, where the key is the variable name, and the value can be accessed.

Example:

				
					<?php
$a = 10;
$b = 20;

function addition() {
    $GLOBALS['result'] = $GLOBALS['a'] + $GLOBALS['b'];
}

addition();
echo $result;
?>

				
			

Output:

				
					30

				
			

2.$_SERVER Superglobal:$_SERVER holds information about headers, paths, and script locations. It provides valuable details about the server and the current script.

Example:

				
					<?php
echo $_SERVER['PHP_SELF'];  // Current script
echo "<br>";
echo $_SERVER['SERVER_ADDR'];  // Server IP
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];  // Browser details
echo "<br>";
echo $_SERVER['REQUEST_METHOD'];  // HTTP method used
?>

				
			

Output:

				
					/path/to/script.php
127.0.0.1
Mozilla/5.0 (your browser details)
GET

				
			

3.$_REQUEST Superglobal: $_REQUEST is a superglobal that collects data from forms, whether submitted using GET or POST. Although it’s versatile, developers often prefer using $_POST or $_GET for specific requests.

Example:

				
					<!DOCTYPE html>
<html>
<body>
 
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  Name: <input type="text" name="username">
  <input type="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_REQUEST['username'];
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo "Hello, " . $name;
    }
}
?>
</body>
</html>

				
			

Output:

				
					Hello, John

				
			

4.$_POST Superglobal:$_POST is used to collect data from forms when they are submitted using the POST method. The data is not visible in the URL, ensuring privacy and security.

Example:

				
					<!DOCTYPE html>
<html>
<body>
  
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  Enter your name: <input name="username" type="text"><br>
  Enter your age: <input name="age" type="text"><br>
  <input type="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['username'];
    $age = $_POST['age'];
    echo "$name is $age years old.";
}
?>
</body>
</html>

				
			

Output:

				
					Jane is 25 years old.

				
			

5. $_GET Superglobal: $_GET is used to collect data from forms submitted using the GET method. Data sent this way is visible in the URL, making it less secure but useful in certain scenarios.

Example:

				
					<!DOCTYPE html>
<html>
<head>
<title>$_GET Example</title>
</head>
<body>

<?php
// Collecting values sent in the URL
$name = $_GET['username'];
$city = $_GET['city'];

echo "<h2>Welcome, $name from $city!</h2>";
?>

</body>
</html>

				
			

Assuming URL

				
					http://localhost/page.php?username=Alice&city=NewYork

				
			

Output:

				
					Welcome, Alice from NewYork!

				
			

HTTP GET and POST Methods in PHP

Understanding HTTP GET and POST Methods in PHP

The Hypertext Transfer Protocol (HTTP) enables communication between clients (browsers) and servers. It follows a request-response model where the client submits an HTTP request, and the server responds with the necessary content and status information. In PHP, we frequently work with two primary HTTP request methods: GET and POST.

1. GET Method: Used to request data from a specified resource.
2. POST Method: Used to send data to the server for processing.

1. GET Method in PHP: The GET method sends data through the URL as query parameters. These parameters are key-value pairs separated by &. The GET method is suitable for retrieving data and can be used to pass simple text information.

Example URL:

				
					http://www.example.com/process.php?name=Alex&age=30

				
			

Here, name=Alex and age=30 are the query parameters sent via GET.

Example: GET Method in PHP

				
					<?php
  if( $_GET["name"] || $_GET["age"] ) {
      echo "Hello, " . htmlspecialchars($_GET['name']) . "<br />";
      echo "Your age is " . htmlspecialchars($_GET['age']);
      exit();
  }
?>
<html>
<body>
  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">
    Name: <input type="text" name="name" /> 
    Age: <input type="text" name="age" />
    <input type="submit" />
  </form>
</body>
</html>

				
			

Output:

				
					Hello, Alex
Your age is 30

				
			

In this example, the user enters their name and age, which is sent via the GET method. The data is displayed on the same page after submission.

Advantages of GET:
  • The data is visible in the URL, making it easy to bookmark the page with query string values.
  • GET requests can be cached and stored in browser history.
  • They can also be bookmarked for future reference.
Disadvantages of GET:
  • It’s unsuitable for sending sensitive data like passwords, as the information is exposed in the URL.
  • The amount of data you can send via GET is limited by the URL length.
POST Method in PHP

The POST method sends data to the server within the HTTP request body, making it invisible in the URL. This method is commonly used when you need to send large amounts of data or sensitive information.

Example: POST Method in PHP

				
					<?php
   if( $_POST["name"] || $_POST["height"] ) {
       if (preg_match("/[^A-Za-z'-]/", $_POST['name'])) {
           die ("Invalid name, name should only contain letters.");
       }
       echo "Hello, " . htmlspecialchars($_POST['name']) . "<br />";
       echo "Your height is " . htmlspecialchars($_POST['height']) . " cm.";
       exit();
   }
?>
<html>
<body>   
  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
     Name: <input type="text" name="name" />
     Height: <input type="text" name="height" />
     <input type="submit" />
  </form>
</body>
</html>

				
			

Output:

				
					Hello, John
Your height is 175 cm.

				
			

In this example, the user’s name and height are submitted via the POST method. The form data is securely processed, and the result is displayed on the same page.

Advantages of POST:
  • Since the data isn’t visible in the URL, it’s more secure for handling sensitive information.
  • The POST method allows sending large amounts of data, including files or binary data.
Disadvantages of POST:
  • POST requests cannot be bookmarked since the data isn’t in the URL.
  • POST requests are not cached or stored in browser history, making it harder to retrieve past form submissions.

PHP Regular Expressions

Regular expressions, often abbreviated as regex or regexes, are sequences of characters that define search patterns used for matching text. They are commonly employed in algorithms to match loosely defined patterns, helping with tasks like data validation, searching, and text manipulation. Regexes can be considered a mini programming language with a specific syntax that allows users to parse and manipulate text strings, making them invaluable tools in many programming contexts.

Regular expressions are powerful tools for working with string patterns, often used to efficiently match or extract certain sequences from text. PHP, being a popular open-source programming language, provides built-in support for regular expressions, just like many other programming languages. Different systems and languages may have their own syntax for regexes, but the basic concepts remain the same. Regexes are capable of working with very large text files or streams, and their applications are widespread across modern development environments.

Key Uses and Benefits of Regular Expressions:

1. Validation: Regexes can be used to validate user inputs such as email addresses, phone numbers, and IP addresses.
2. Searching and Matching: They offer efficient ways to search for and extract specific string patterns in large datasets.
3. Text Parsing: They are useful in parsing text files or streams to find patterns for further analysis or manipulation.
4. Development Efficiency: Using regex saves development time when performing pattern matching and text processing.
5. HTML Template Creation: Regexes help in recognizing tags and templates within HTML, allowing data to be substituted dynamically.
6. Form Validations: Ensuring fields like passwords meet strength requirements by using regex to check for required characters.
7. Other Uses: Regexes are used for browser detection, spam filtration, and keyword searching, among other applications.

Regular Expression Syntax and Examples:
Regular Expression Matches
developers The string “developers”
^developers Strings that begin with “developers”
developers$ Strings that end with “developers”
^developers$ The exact string “developers”
[xyz] Any one of the characters: x, y, or z
[a-z] Any lowercase letter
[^A-Z] Any character that is not an uppercase letter
`(png jpeg)`
[a-z]+ One or more lowercase letters
^[a-zA-Z0-9]{3, }$ A word with at least three alphanumeric characters
([mn])([op]) Matches: mo, mp, no, np
[^a-zA-Z0-9] Any symbol other than letters or numbers
`([A-Z]{2} [0-9]{4})`
Key Regex Operators:
OperatorDescription
^Indicates the start of the string
$Indicates the end of the string
.Matches any single character
()Groups expressions together
[]Matches any character within the brackets
[^]Matches any character not in the brackets
-Specifies a range (e.g., [a-z] for lowercase letters)
``
?Matches 0 or 1 of the preceding character
*Matches 0 or more of the preceding character
+Matches 1 or more of the preceding character
{n}Matches exactly n occurrences
{n,}Matches at least n occurrences
{n, m}Matches between n and m occurrences
\Escape character
Special Character Classes:
Special CharacterMeaning
\nNew line
\rCarriage return
\tTab
\vVertical tab
\fForm feed
\xhhHexadecimal character
Example Functions in PHP:
FunctionDescription
preg_match()Searches for a pattern in a string and returns true if found
preg_match_all()Searches for all occurrences of a pattern and returns all matches
preg_replace()Searches and replaces occurrences of a pattern in a string
preg_split()Splits a string by a regex pattern
preg_grep()Searches for array elements that match a pattern

PHP Example 1:

				
					<?php
// Example of validating a name string with letters and spaces
$regex = '/^[a-zA-Z ]+$/';
$name = 'John Doe';

if (preg_match($regex, $name)) {
    echo "Valid name string";
} else {
    echo "Invalid name string";
}
?>

				
			

Output:

				
					Valid name string

				
			

Example:

				
					<?php
// Extract bold text within HTML tags
$regex = "/<b>(.*)<\/b>/U";
$string = "Title: <b>PHP</b> Version: <b>7.4</b>";

preg_match_all($regex, $string, $matches);

echo $matches[0][0] . " <br> " . $matches[0][1];
?>

				
			

Output:

				
					PHP 
7.4

				
			

Example:

				
					<?php
// Replace year in a string
$regex = "([0-9]+)";
$original = "Graduated in 2010";
$replaceWith = "2015";

$updatedString = preg_replace($regex, $replaceWith, $original);
echo $updatedString;
?>

				
			

Output:

				
					Graduated in 2015

				
			
Metacharacters:
MetacharacterDescriptionExample
.Matches any single character except newline/./ matches any character
^Matches the start of a string/^web/ matches “web” at the start
$Matches the end of a string/end$/ matches “end” at the end
*Matches zero or more occurrences/do*/ matches “do”, “dog”, etc.
+Matches one or more occurrences/go+/ matches “go”, “good”, etc.
\Escapes a metacharacter/\./ matches the literal dot
POSIX Regular Expressions:
RegexMeaning
[0-9]Matches any digit
[a-z]Matches any lowercase letter
[A-Z]Matches any uppercase letter
[:lower:]Matches any lowercase letter
[:upper:]Matches any uppercase letter
[:alnum:]Matches any alphanumeric character
Quantifiers:
QuantifierMeaning
a+Matches one or more occurrences of “a”
a*Matches zero or more occurrences of “a”
a{2}Matches exactly two occurrences of “a”
a{2,}Matches two or more occurrences of “a”
a{2,5}Matches between two and five occurrences of “a”
^aMatches “a” at the start of a string
a$Matches “a” at the end of a string
[^a-zA-Z]Matches any character that is not a letter

PHP Form Processing

Processing Forms in PHP

In this article, we will explore how to handle forms in PHP. HTML forms are designed to send user information to a server and return results to the browser. For instance, if you wish to collect visitor details on your website and send them positive messages, you can achieve this through form processing. The gathered information can be validated either on the client-side or server-side, and the final results are communicated back to the client via their web browser. To create an HTML form, you should utilize the <form> tag.

Attributes of the Form Tag:
AttributeDescription
name or idSpecifies the name of the form, allowing for individual identification.
actionIndicates the destination to which the form data will be sent upon submission.
methodDefines the HTTP method to be used during form submission. Possible values include GET and POST. Using the GET method exposes the form data in the URL. The default method is GET.
encTypeSpecifies the encoding type for the form data upon submission.
novalidateInstructs the server not to validate form data upon submission.
Controls Used in Forms:

Form processing involves a variety of controls through which communication occurs between the client and the server. The controls typically found in forms are:

  • Textbox: A textbox allows users to input single-line data, suitable for entries like names or search queries.
  • Textarea: A textarea enables users to provide multi-line input, ideal for gathering information like addresses or messages.
  • Dropdown: A dropdown (or combobox) lets users select a value from a predefined list.
  • Radio Buttons: Radio buttons permit users to choose only one option from a specified set of options.
  • Checkbox: Checkboxes allow users to select multiple options from a provided list.
  • Buttons: Buttons are clickable elements used to submit the form.
Creating a Simple HTML Form:

All the aforementioned form controls can be created using the <input> tag based on its type attribute. In the following script, the form does not implement any event handling mechanism upon submission. Event handling refers to the processes executed during form submission, which can be managed using JavaScript or PHP. While JavaScript provides client-side validation, PHP is recommended for robust form processing.

HTML Code:

				
					<!DOCTYPE html>
<html>
<head>
    <title>Simple Form Processing</title>
</head>
<body>
    <form id="form1" method="post">
        First Name:
        <input type="text" name="firstname" required/>
        <br><br>
        Last Name:
        <input type="text" name="lastname" required/>
        <br><br>
        Address:
        <input type="text" name="address" required/>
        <br><br>
        Email Address:
        <input type="email" name="emailaddress" required/>
        <br><br>
        Password:
        <input type="password" name="password" required/>
        <br><br>
        <input type="submit" value="Submit"/>
    </form>
</body>
</html>

				
			

Output:

				
					Current file: /path/to/current/script.php

				
			
Form Validation:

Form validation ensures that users provide the required information. Basic validation can be implemented using HTML attributes. For example, in the script above, the email input has a type of “email,” preventing incorrect entries. Each field in the form is marked with a required attribute, prompting users to complete all fields before submission.

PHP Functions and Arrays Used in Form Processing:
  • isset(): This function checks whether a variable or form control has a value.
  • $_GET[]: Retrieves information from form controls via parameters sent in the URL.
  • $_POST[]: Fetches data from form controls using the HTTP POST method.
  • $_REQUEST[]: Used to retrieve data when working with databases.
Form Processing Using PHP:

The above HTML code is revised to include the necessary functions and arrays for validation. The rewritten script checks all fields, and if no errors occur, it displays the submitted information in a table format.

Example:

				
					<?php 
if (isset($_POST['submit'])) { 
    if ((!isset($_POST['firstname'])) || (!isset($_POST['lastname'])) ||  
        (!isset($_POST['address'])) || (!isset($_POST['emailaddress'])) ||  
        (!isset($_POST['password'])) || (!isset($_POST['gender']))) { 
        $error = "*" . "Please fill all the required fields."; 
    } else { 
        $firstname = $_POST['firstname']; 
        $lastname = $_POST['lastname']; 
        $address = $_POST['address']; 
        $emailaddress = $_POST['emailaddress']; 
        $password = $_POST['password']; 
        $gender = $_POST['gender']; 
    } 
} 
?> 
<html> 
<head> 
    <title>Simple Form Processing</title> 
</head> 
<body> 
    <h1>Form Processing with PHP</h1> 
    <fieldset> 
        <form id="form1" method="post" action="form.php"> 
            <?php 
                if (isset($_POST['submit'])) { 
                    if (isset($error)) { 
                        echo "<p style='color:red;'>" . $error . "</p>"; 
                    } 
                } 
            ?> 
            First Name: 
            <input type="text" name="firstname"/>  
            <span style="color:red;">*</span> 
            <br><br> 
            Last Name: 
            <input type="text" name="lastname"/> 
            <span style="color:red;">*</span> 
            <br><br>  
            Address: 
            <input type="text" name="address"/> 
            <span style="color:red;">*</span> 
            <br><br>  
            Email: 
            <input type="email" name="emailaddress"/> 
            <span style="color:red;">*</span> 
            <br><br>  
            Password: 
            <input type="password" name="password"/> 
            <span style="color:red;">*</span> 
            <br><br>  
            Gender: 
            <input type="radio" value="Male" name="gender"> Male 
            <input type="radio" value="Female" name="gender"> Female 
            <br><br> 
            <input type="submit" value="Submit" name="submit" /> 
        </form> 
    </fieldset> 

    <?php 
    if (isset($_POST['submit'])) { 
        if (!isset($error)) { 
            echo "<h1>INPUT RECEIVED</h1><br>"; 
            echo "<table border='1'>"; 
            echo "<thead>"; 
            echo "<th>Parameter</th>"; 
            echo "<th>Value</th>"; 
            echo "</thead>"; 
            echo "<tr>"; 
            echo "<td>First Name</td>"; 
            echo "<td>".$firstname."</td>"; 
            echo "</tr>"; 
            echo "<tr>"; 
            echo "<td>Last Name</td>"; 
            echo "<td>".$lastname."</td>"; 
            echo "</tr>"; 
            echo "<tr>"; 
            echo "<td>Address</td>"; 
            echo "<td>".$address."</td>"; 
            echo "</tr>"; 
            echo "<tr>"; 
            echo "<td>Email Address</td>"; 
            echo "<td>" .$emailaddress."</td>"; 
            echo "</tr>"; 
            echo "<tr>"; 
            echo "<td>Password</td>"; 
            echo "<td>".$password."</td>"; 
            echo "</tr>"; 
            echo "<tr>"; 
            echo "<td>Gender</td>"; 
            echo "<td>".$gender."</td>"; 
            echo "</tr>"; 
            echo "</table>"; 
        } 
    } 
    ?> 
</body> 
</html>

				
			

Output:

				
					INPUT RECEIVED

+------------------+------------------+
|     Parameter    |       Value      |
+------------------+------------------+
|    First Name    |     John         |
|     Last Name    |     Doe          |
|      Address     |     123 Main St  |
|   Email Address   | john@example.com  |
|     Password     |  password123     |
|      Gender      |      Male        |
+------------------+------------------+

				
			

PHP Date and Time

Handling date and time is a common task in PHP, especially when managing database queries or web development tasks. PHP provides built-in functions for these operations, and we’ll discuss some of the most useful ones below.

PHP date() Function:

The date() function in PHP is used to convert a timestamp into a more human-readable format, allowing us to work with dates and times in a flexible way.

Why do we need the date() function?

Dates and times in computers are stored as UNIX Timestamps, which are the number of seconds since the Unix epoch (January 1, 1970, 00:00:00 GMT). This raw format is not suitable for human interpretation, so PHP allows us to convert it into a readable format using the date() function.

Syntax:

				
					date(format, timestamp)

				
			

Explanation:

  • format: Specifies the format of the output.
  • timestamp (optional): If not provided, the current date and time will be used.

Example: Here’s how you can use the date() function to get today’s date:

				
					<?php
  echo "Current date is: ";
  $currentDate = date("d-m-Y");
  echo $currentDate;
?>

				
			

Output:

				
					Current date is: 23-10-2024

				
			
Formatting Options in the date() Function:

The format parameter allows us to specify how the date will be displayed. Below are some common formatting characters:

  • d: Day of the month (01 to 31).
  • D: Abbreviated day name (Mon to Sun).
  • m: Month number (01 to 12).
  • M: Abbreviated month name (Jan to Dec).
  • y: Two-digit year (e.g., 24 for 2024).
  • Y: Four-digit year (e.g., 2024).

You can also include separators like hyphens (-), dots (.), slashes (/), etc., to format the date as desired.

Example:

				
					<?php
  echo "Date formats:" . "\n";
  echo date("d/m/Y") . "\n";
  echo date("d-m-Y") . "\n";
  echo date("Y.m.d") . "\n";
  echo date("M-d-Y/D");
?>

				
			

Output:

				
					Date formats:
23/10/2024
23-10-2024
2024.10.23
Oct-23-2024/Wed

				
			
Time Formatting with date() Function:

You can also use the date() function to format the time string using the following characters:

  • h: 12-hour format with leading zeros (01 to 12).
  • H: 24-hour format with leading zeros (00 to 23).
  • i: Minutes with leading zeros (00 to 59).
  • s: Seconds with leading zeros (00 to 59).
  • a: Lowercase am or pm.
  • A: Uppercase AM or PM.

Example:

				
					<?php
  echo date("h:i:s A") . "\n";
  echo date("d-M-Y h:i:s a");
?>

				
			

Output:

				
					03:14:29 PM
23-Oct-2024 03:14:29 pm

				
			
PHP time() Function:

The time() function returns the current time as a Unix timestamp (the number of seconds since January 1, 1970, 00:00:00 GMT).

Example:

				
					<?php
  $currentTimestamp = time();
  echo "Current timestamp: " . $currentTimestamp;
  echo "\n";
  echo "Formatted time: " . date("F d, Y h:i:s A", $currentTimestamp);
?>

				
			

Output:

				
					Current timestamp: 1729674869
Formatted time: October 23, 2024 03:14:29 PM

				
			
PHP mktime() Function:

The mktime() function is used to create a timestamp for a specified date and time. If no arguments are provided, it will return the current date and time.

Syntax:

				
					mktime(hour, minute, second, month, day, year)

				
			

Example:

				
					<?php
  echo mktime(12, 45, 30, 10, 23, 2024);
?>

				
			

Output:

				
					1729674330

				
			

PHP Date and Time

In this article, we will explore the include() and require() functions in PHP, understand how they impact code execution, and examine their differences and usage through examples. As you may know, PHP enables us to create reusable functions and elements that might be needed on multiple pages. Writing the same function across different pages is time-consuming and error-prone. This repetition can be avoided using the concept of file inclusion, which allows you to insert external files—containing text or code—into a program, saving time and effort. If you need to update the code later, modifying the source file will automatically update all the files that include it. PHP offers two key functions for this purpose:

1. include() function
2. require() function

We will explore both of these functions, their uses, and their differences through examples.

PHP include() Function:

The include() function allows us to include the contents of a file within another PHP file. It copies the contents of the specified file into the location where the include() function is called, before the server executes the rest of the script.

Example: Using the include() function in PHP

				
					<?php 
  // Contents of file_to_include.php
  echo "Hello from the file!";
?>

				
			

Now, we can include this file in another PHP file, such as index.php:

				
					<?php  
    include("file_to_include.php"); 
    echo "<br>File has been included successfully.";
?>

				
			
PHP require() Function:

The require() function works similarly to the include() function. It also copies the contents of the specified file into the location where it is called.

Example: Using the require() function in PHP

				
					<?php 
  // Contents of file_to_include.php
  echo "Hello from the file!";
?>

				
			

We can include this file using the require() function in another PHP file:

				
					<?php  
    require("file_to_include.php"); 
    echo "<br>File has been required successfully.";
?>

				
			
Difference between include() and require() functions:

While both include() and require() perform the same task of file inclusion, there is one key difference in how they handle errors. This difference becomes evident when an error arises, such as a missing file.

Example 1: Using include() when a file is missing:

				
					<?php  
    include("missing_file.php"); 
    echo "<br>This message is displayed even if the file is missing.";
?>

				
			

Output:

				
					Warning: include(missing_file.php): Failed to open stream: No such file or directory in [file path] on line X
Warning: include(): Failed opening 'missing_file.php' for inclusion in [file path] on line X
This message is displayed even if the file is missing.

				
			

PHP File Handling

File handling in PHP allows you to create, open, read, write, delete, and manage files on a server. It’s especially useful when you need to store data persistently or handle file uploads by users. PHP provides a variety of built-in functions that simplify and secure file handling tasks.

Common File Handling Functions in PHP
  • fopen() – Opens a file.
  • fclose() – Closes a file.
  • fread() – Reads data from a file.
  • fwrite() – Writes data to a file.
  • file_exists() – Checks if a file exists.
  • unlink() – Deletes a file.
What is File Handling in PHP?

File handling refers to the process of working with files on the server, including reading, writing, creating, or deleting files. It is crucial for applications requiring data storage and retrieval, such as logging systems, user-generated content, or file uploads.

Opening and Closing Files

Before performing operations like reading or writing to a file, it needs to be opened using the fopen() function, which returns a file pointer resource. After the file operations are done, the file should be closed using fclose() to free system resources.

				
					<?php

// Open a file in read mode
$file = fopen("example.txt", "r"); 

if ($file) {
    echo "File opened successfully!";
    fclose($file); // Close the file after use
} else {
    echo "Failed to open the file.";
}

?>

				
			
File Modes in PHP

Files can be opened in several modes, such as:

  • "w" – Opens the file for writing. If the file doesn’t exist, a new one is created. If it exists, the contents will be erased.
  • "r" – Opens the file for reading only.
  • "a" – Opens the file for writing, appending data to the end. Existing data is preserved.
  • "w+" – Opens the file for both reading and writing. If it doesn’t exist, a new one is created. If it exists, its contents are erased.
  • "r+" – Opens the file for both reading and writing.
  • "a+" – Opens the file for both writing and reading, appending data to the end. If the file doesn’t exist, a new one is created.
  • "x" – Creates a new file for writing only.

Reading from Files

There are two primary ways to read the contents of a file in PHP:

1. Reading the Entire File: You can use the fread() function or file_get_contents() to read the whole content of a file.

				
					<?php

$file = fopen("example.txt", "r");
$content = fread($file, filesize("example.txt"));

echo $content;
fclose($file);

?>

				
			

2. Reading a File Line by Line: The fgets() function allows reading a file line by line.

				
					<?php
  
$file = fopen("example.txt", "r");

if ($file) {
    while (($line = fgets($file)) !== false) {
        echo $line . "<br>";
    }
    fclose($file);
}

?>

				
			

3. Writing to Files: To write data to a file, you can use the fwrite() function, which writes to an open file in the specified mode.

				
					<?php
  
// Open a file in write mode
$file = fopen("example.txt", 'w');

if ($file) {
    $text = "Hello, PHP file handling!\n";
    fwrite($file, $text);
    fclose($file);
}

?>

				
			

4. Deleting Files: To delete a file in PHP, use the unlink() function.

				
					<?php

if (file_exists("example.txt")) {
    unlink("example.txt");
    echo "File deleted successfully!";
} else {
    echo "File does not exist.";
}

?>

				
			
1. Output for Each Example: Opening a file:
				
					File opened successfully!

				
			

2. Reading the entire file:

				
					(Contents of example.txt displayed here)

				
			

3. Reading the file line by line:

				
					(Each line of example.txt is displayed with <br> between lines)

				
			

4. Writing to a file: No output. The contents of example.txt will be updated with the text “Hello, PHP file handling!”.

5. Deleting a file:

				
					File deleted successfully!

				
			

PHP Uploading File

Approach: To execute the PHP script, you’ll need a server environment. Ensure you have either XAMPP or WAMP installed on your machine for testing purposes.

HTML Code Snippet: Here’s an HTML code example for creating a file upload form. The enctype='multipart/form-data' is an encoding type that allows files to be sent through a POST method. Without this, files cannot be uploaded through the form.

upload.html:

				
					<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Upload</title>
</head>
<body>
    <form action="upload-handler.php" method="post" enctype="multipart/form-data">
        <h2>Select a File to Upload</h2>
        <label for="fileSelect">Choose File:</label>
        <input type="file" name="fileToUpload" id="fileSelect">
        <input type="submit" name="submit" value="Upload File">
        <p><strong>Note:</strong> Only .pdf, .docx, .txt files are allowed, with a maximum size of 3MB.</p>
    </form>
</body>
</html>

				
			

In this form, we use the enctype attribute to ensure that the form can handle file uploads. The input field name fileToUpload will be used later in our PHP script to access the uploaded file.

PHP File Upload Script: Now let’s create the PHP script to manage the file upload.

upload-handler.php:

				
					<?php
// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Check if file was uploaded without errors
    if (isset($_FILES["fileToUpload"]) && $_FILES["fileToUpload"]["error"] == 0) {
        
        // Allowed file types and extensions
        $allowed_extensions = array("pdf" => "application/pdf", "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "txt" => "text/plain");
        $file_name = $_FILES["fileToUpload"]["name"];
        $file_type = $_FILES["fileToUpload"]["type"];
        $file_size = $_FILES["fileToUpload"]["size"];

        // Extract file extension
        $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);

        // Check if the file extension is allowed
        if (!array_key_exists($file_extension, $allowed_extensions)) {
            die("Error: Please upload a valid file format.");
        }

        // Check file size (max 3MB)
        $maxsize = 3 * 1024 * 1024;
        if ($file_size > $maxsize) {
            die("Error: File size exceeds the 3MB limit.");
        }

        // Verify file MIME type
        if (in_array($file_type, $allowed_extensions)) {
            
            // Check if the file already exists
            if (file_exists("uploads/" . $file_name)) {
                echo "Error: " . $file_name . " already exists!";
            } else {
                // Move the file to the uploads directory
                move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "uploads/" . $file_name);
                echo "File uploaded successfully!";
            }
        } else {
            echo "Error: Invalid file type.";
        }
    } else {
        echo "Error: " . $_FILES["fileToUpload"]["error"];
    }
}
?>

				
			

In this script, we first check if the form was submitted using the POST method. Then, we access the uploaded file using the $_FILES array to retrieve the file name, size, and type. After that, we validate the file type and size. If the file passes the checks, we move it from its temporary location to the uploads folder on the server.

Output:

When the form is submitted, the following scenarios could occur:

1. File Uploaded Successfully:

				
					File uploaded successfully!

				
			

2. File Size Exceeds Limit:

				
					Error: File size exceeds the 3MB limit.

				
			

3. Invalid File Type:

				
					Error: Please upload a valid file format.

				
			

4. File Already Exists:

				
					Error: filename.docx already exists!

				
			

5. General Upload Error:

				
					Error: (error code)

				
			

PHP Cookies

A cookie in PHP is a small data file, typically 4KB in size, that a web server saves on a user’s computer. Cookies are mainly used to track user information, such as usernames, to personalize web experiences when the user revisits the site. Cookies can only be accessed by the domain that created them, and while they are usually set using HTTP headers, they can also be created using JavaScript.

Setting a Cookie in PHP:

To create a cookie in PHP, you use the setcookie() function. This function needs to be called before any output is generated by the script; otherwise, the cookie won’t be set.

Syntax:

				
					setcookie(name, value, expire, path, domain, security);

				
			

Parameters:

  • Name: The name of the cookie.
  • Value: The value to be stored in the cookie.
  • Expire: The expiration timestamp for the cookie. After this time, the cookie is no longer available.
  • Path: Specifies the path on the server where the cookie will be available.
  • Domain: Defines the domain where the cookie is accessible.
  • Security: Indicates if the cookie should only be sent over secure HTTPS connections.
Operations on Cookies in PHP:

1. Creating Cookies: This example creates a cookie named User_Preference with a value of "Dark Mode", which will expire after 3 days.

				
					<!DOCTYPE html>
<?php 
    setcookie("User_Preference", "Dark Mode", time() + 3 * 24 * 60 * 60); 
?> 
<html>
<body> 
    <?php 
        echo "Cookie has been set."; 
    ?> 
    <p>
        <strong>Note:</strong> You may need to reload the page to see the cookie's value.
    </p>
</body>
</html>

				
			

Output:

				
					Cookie has been set.

				
			

Note: Only the name parameter is mandatory in setcookie(). You can leave other parameters blank by providing an empty string ("").

2. Checking if a Cookie is Set: It’s a good practice to check if a cookie exists before trying to access it. You can use the isset() function to verify whether a cookie is set.

Example:

				
					<!DOCTYPE html>
<?php 
    setcookie("User_Preference", "Dark Mode", time() + 3 * 24 * 60 * 60); 
?> 
<html>
<body>
    <?php 
    if (isset($_COOKIE["User_Preference"])) {
        echo "User preference is set to " . $_COOKIE["User_Preference"];
    } else {
        echo "No user preferences are saved.";
    } 
    ?>
    <p>
        <strong>Note:</strong> Reload the page to check the cookie's value.
    </p>
</body>
</html>

				
			

Output:

				
					User preference is set to Dark Mode

				
			

3. Accessing Cookie Values: You can retrieve a cookie’s value using PHP’s $_COOKIE superglobal array. This array holds all the cookies sent by the user’s browser in the current request.

Example:

				
					<!DOCTYPE html>
<?php 
    setcookie("User_Preference", "Dark Mode", time() + 3 * 24 * 60 * 60); 
?> 
<html>
<body>
    <?php 
        echo "The current user preference is: " . $_COOKIE["User_Preference"]; 
    ?>
    <p>
        <strong>Note:</strong> Reload the page to access the cookie value.
    </p>
</body>
</html>

				
			

Output:

				
					The current user preference is: Dark Mode

				
			

4. Deleting Cookies: You can delete a cookie by calling setcookie() again but setting the expiration time to a point in the past.

Example:

				
					<!DOCTYPE html>
<?php 
    setcookie("User_Preference", "Dark Mode", time() + 3 * 24 * 60 * 60); 
?> 
<html>
<body>
    <?php 
        setcookie("User_Preference", "", time() - 3600); 
        echo "Cookie has been deleted.";
    ?>
    <p>
        <strong>Note:</strong> Reload the page to ensure the cookie is deleted.
    </p>
</body>
</html>

				
			

Output:

				
					Cookie has been deleted.

				
			

PHP Sessions

In general, a session refers to a period of communication between two entities. In PHP, sessions are used to store user data on the server rather than on the client side, offering a more secure way to manage user-related information. Each user in a session-based environment is assigned a unique identifier known as a Session ID (SID). The SID helps link users to their session data stored on the server, such as posts, emails, and other personal information.

Why are Sessions Better than Cookies?

While cookies are also used to store user-related data, they come with security concerns. Cookies are stored on the user’s computer, making them vulnerable to tampering. Attackers can easily modify cookie content, which may lead to malicious data being injected into the application. Moreover, cookies can slow down website performance, as they send user data back to the server every time the user loads a page. Each time the browser makes a request, all cookie data for that site is included in the request.

Steps Involved in PHP Sessions:

1. Starting a Session: To initiate a session, the session_start() function is used. This function starts a new session or resumes an existing one, and also generates a new session ID.

Example:

				
					<?php 
    session_start(); 
?>

				
			

2. Storing Session Data: Session data can be stored as key-value pairs using the $_SESSION[] superglobal array. This data will persist across different pages during the session.

Example:

				
					<?php 
    session_start(); 
    
    $_SESSION["StudentID"] = "101"; 
    $_SESSION["StudentName"] = "Rahul"; 
?>

				
			

3. Accessing Session Data: To retrieve session data, you must first call session_start() and then use the key from the $_SESSION array.

Example:

				
					<?php 
    session_start(); 
    
    echo 'The student\'s name is: ' . $_SESSION["StudentName"] . '<br>';  
    echo 'The student\'s ID is: ' . $_SESSION["StudentID"] . '<br>'; 
?>

				
			

Output:

				
					The student's name is: Rahul
The student's ID is: 101

				
			

4. Deleting Specific Session Data: To remove specific session data, you can use the unset() function with the particular session variable.

Example:

				
					<?php 
    session_start(); 
    
    if (isset($_SESSION["StudentName"])) { 
        unset($_SESSION["StudentID"]); 
    } 
?>

				
			

Output:

				
					Coding is challenging!

				
			

Implementing callback in PHP

In PHP, a callback is essentially a reference to a function that can be called later. A callback variable (or callable) can represent various types of functions such as normal functions, object methods, or static methods in classes. Below are a few ways to implement a callback in PHP:

Standard Callback:

In PHP, normal functions can be invoked through the call_user_func() function, where the argument is simply the function’s name as a string.

Example:

				
					<?php 

// Function that prints a message
function someFunction() { 
    echo "Hello World \n"; 
} 

// Calling the function via callback
call_user_func('someFunction'); 
?>

				
			

Output:

				
					Hello World

				
			
Static Class Method Callback:

Static methods in classes can also be invoked using call_user_func(). The argument in this case is an array where the first element is the class name and the second element is the method name.

Example:

				
					<?php 

// Class definition
class BaseClass { 

    // Static method in the class
    static function someFunction() { 
        echo "Base Class Method \n"; 
    } 
} 

class ChildClass extends BaseClass { 

    // Static method in the child class
    static function someFunction() { 
        echo "Child Class Method \n"; 
    }    
} 

// Callback for static method in the child class
call_user_func(array('ChildClass', 'someFunction')); 

// Another way to call the same static method
call_user_func('ChildClass::someFunction'); 

// Callback to the parent class method using relative path
call_user_func(array('ChildClass', 'parent::someFunction')); 
?>

				
			

Output:

				
					Child Class Method
Child Class Method
Base Class Method