
PHP Advanced: Date, Files, Cookies, Sessions, JSON and Exceptions
After learning PHP basics, control flow, functions, arrays, regular expressions, and forms, the next step is understanding advanced PHP features that are used in real applications.
This article explains important advanced PHP topics including date and time, include, file handling, file open and read, file create and write, file upload, cookies, sessions, filters, advanced filters, callback functions, JSON, and exceptions.
These concepts help developers build more practical applications that can manage files, remember users, validate data, exchange information with APIs, and handle errors properly.
PHP Date and Time
PHP provides built-in functions for working with dates and time. Dates are important in many web applications, such as blogs, dashboards, invoices, reports, appointments, logs, subscriptions, and user activity tracking.
The most common function for formatting dates is date().
<?php
echo date("Y-m-d");
echo date("Y-m-d H:i:s");
?>The format string controls how the date appears. For example, Y represents the full year, m represents the month, d represents the day, H represents the hour, i represents minutes, and s represents seconds.
You can also set the timezone using date_default_timezone_set().
<?php
date_default_timezone_set("Europe/Istanbul");
echo date("Y-m-d H:i:s");
?>PHP also provides the DateTime class, which is more flexible for modern applications.
<?php
$date = new DateTime();
echo $date->format("Y-m-d H:i:s");
?>The DateTime class is useful when adding days, comparing dates, handling timezones, and building applications that depend on accurate time calculations.
PHP Include
The include statement allows you to insert one PHP file inside another PHP file. This helps developers organize code and avoid repeating the same HTML or PHP logic in many files.
For example, a website may have a shared header and footer. Instead of copying the header into every page, you can include it.
<?php include "header.php"; ?>
<h1>Home Page</h1>
<?php include "footer.php"; ?>PHP also provides require, include_once, and require_once.
include: includes a file and shows a warning if the file is missing.
require: includes a file and stops the script if the file is missing.
include_once: includes a file only one time.
require_once: requires a file only one time.
In real projects, include and require are often used for configuration files, shared layouts, helper functions, database connections, and reusable components.
PHP File Handling
File handling means working with files through PHP. PHP can read files, write files, create files, upload files, delete files, and check whether files exist.
File handling is useful for logs, reports, simple storage, configuration files, uploaded documents, generated exports, and temporary files.
Before working with a file, it is important to check whether the file exists.
<?php
$file = "example.txt";
if (file_exists($file)) {
echo "File exists.";
} else {
echo "File does not exist.";
}
?>PHP provides many file functions such as file_exists(), filesize(), file_get_contents(), file_put_contents(), fopen(), fread(), fwrite(), and fclose().
When working with files, developers should always pay attention to permissions, file paths, security, and user input. Never allow users to freely control file paths without validation.
PHP File Open/Read
PHP can open and read files using functions such as fopen(), fread(), and fclose(). The fopen() function opens a file, while fread() reads its content.
<?php
$file = fopen("example.txt", "r");
$content = fread($file, filesize("example.txt"));
fclose($file);
echo $content;
?>The second argument in fopen() is the mode. The mode r means read only.
A simpler way to read a complete file is using file_get_contents().
<?php
$content = file_get_contents("example.txt");
echo $content;
?>This method is shorter and useful when you want to read the whole file at once.
For large files, reading line by line may be better because it uses less memory.
<?php
$file = fopen("example.txt", "r");
while (!feof($file)) {
echo fgets($file);
}
fclose($file);
?>Reading files is commonly used for logs, text files, CSV files, templates, cached content, and imported data.
PHP File Create/Write
PHP can create and write files using functions such as fopen(), fwrite(), and file_put_contents().
The following example creates or opens a file and writes text into it.
<?php
$file = fopen("notes.txt", "w");
fwrite($file, "Learning PHP file writing.");
fclose($file);
?>The mode w opens the file for writing. If the file does not exist, PHP tries to create it. If the file already exists, its old content will be removed.
To append new content to the end of a file, use the a mode.
<?php
$file = fopen("notes.txt", "a");
fwrite($file, "\nNew line added.");
fclose($file);
?>You can also use file_put_contents() for a shorter syntax.
<?php
file_put_contents("notes.txt", "Hello from PHP.");
?>To append content using file_put_contents(), use the FILE_APPEND flag.
<?php
file_put_contents("notes.txt", "\nAnother line.", FILE_APPEND);
?>Writing files is useful for logs, generated reports, cache files, exported data, and simple file-based storage.
PHP File Upload
File upload allows users to send files from their computer to the server. This is used in profile images, resumes, documents, galleries, attachments, and admin panels.
To upload files, the HTML form must use method="post" and enctype="multipart/form-data".
<form method="post" enctype="multipart/form-data">
<input type="file" name="document">
<button type="submit">Upload</button>
</form>In PHP, uploaded file information is available through the $_FILES superglobal.
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$fileName = $_FILES["document"]["name"];
$tmpName = $_FILES["document"]["tmp_name"];
move_uploaded_file($tmpName, "uploads/" . $fileName);
echo "File uploaded.";
}
?>This basic example works, but real file upload systems need stronger validation. Developers should check file size, file extension, MIME type, upload errors, and generate safe file names.
<?php
$allowedExtensions = ["jpg", "png", "pdf"];
$fileName = $_FILES["document"]["name"];
$tmpName = $_FILES["document"]["tmp_name"];
$fileSize = $_FILES["document"]["size"];
$extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
if (!in_array($extension, $allowedExtensions)) {
echo "File type is not allowed.";
} elseif ($fileSize > 2 * 1024 * 1024) {
echo "File is too large.";
} else {
$newName = uniqid("upload_", true) . "." . $extension;
move_uploaded_file($tmpName, "uploads/" . $newName);
echo "File uploaded successfully.";
}
?>File uploads must be handled carefully because unsafe upload systems can create serious security problems.
PHP Cookies
Cookies are small pieces of data stored in the user's browser. PHP can create cookies and read them in later requests.
Cookies are commonly used to remember preferences, language selection, simple tracking values, and non-sensitive user settings.
A cookie can be created using setcookie().
<?php
setcookie("theme", "dark", time() + 3600, "/");
?>This creates a cookie named theme with the value dark. The cookie will expire after one hour.
Cookies can be read using the $_COOKIE superglobal.
<?php
$theme = $_COOKIE["theme"] ?? "light";
echo $theme;
?>To delete a cookie, set its expiration time to a past time.
<?php
setcookie("theme", "", time() - 3600, "/");
?>Cookies should not be used to store sensitive information such as passwords. Sensitive authentication data should be handled securely using sessions, tokens, and proper security practices.
PHP Sessions
Sessions allow PHP to store data for a specific user across multiple pages. Unlike cookies, session data is stored on the server, while the browser usually stores only a session identifier.
Sessions are commonly used for login systems, shopping carts, user dashboards, flash messages, and temporary user data.
To use sessions, start the session with session_start().
<?php
session_start();
$_SESSION["user_id"] = 15;
$_SESSION["user_name"] = "Adnan";
echo $_SESSION["user_name"];
?>On another page, you can start the session again and access the stored values.
<?php
session_start();
if (isset($_SESSION["user_id"])) {
echo "User is logged in.";
} else {
echo "User is not logged in.";
}
?>To remove a session value, use unset().
<?php
session_start();
unset($_SESSION["user_id"]);
?>To destroy the full session, use session_destroy().
<?php
session_start();
session_destroy();
?>Sessions are essential for applications that need to remember users securely between requests.
PHP Filters
PHP filters are used to validate and sanitize data. Validation checks whether data is valid, while sanitization cleans or modifies data.
The main function for filters is filter_var().
<?php
$email = "user@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email.";
} else {
echo "Invalid email.";
}
?>PHP filters can validate emails, URLs, integers, floats, IP addresses, and booleans.
<?php
$url = "https://example.com";
if (filter_var($url, FILTER_VALIDATE_URL)) {
echo "Valid URL.";
}
?>Filters are commonly used with form input, API input, query parameters, and configuration values.
PHP Filters Advanced
Advanced filtering allows developers to use options and flags for more specific validation rules.
For example, you can validate an integer inside a specific range.
<?php
$age = 25;
$options = [
"options" => [
"min_range" => 18,
"max_range" => 60
]
];
if (filter_var($age, FILTER_VALIDATE_INT, $options)) {
echo "Age is valid.";
} else {
echo "Age is not valid.";
}
?>You can also validate an IP address.
<?php
$ip = "192.168.1.1";
if (filter_var($ip, FILTER_VALIDATE_IP)) {
echo "Valid IP address.";
}
?>For arrays of input values, PHP provides filter_input() and filter_input_array(), which are useful when working directly with request data.
<?php
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
if ($email) {
echo "Valid email from POST.";
}
?>Advanced filters help developers create stricter validation rules and reduce incorrect or unsafe input in applications.
PHP Callback Functions
A callback function is a function that is passed as an argument to another function. PHP can call that function later when needed.
Callbacks are useful for sorting, filtering arrays, transforming data, event-style logic, and flexible reusable code.
A simple callback example can use array_map().
<?php
$numbers = [1, 2, 3, 4];
$result = array_map(function ($number) {
return $number * 2;
}, $numbers);
print_r($result);
?>This example sends an anonymous function as a callback to array_map(). The function is applied to every item in the array.
Another common callback example uses array_filter().
<?php
$numbers = [1, 2, 3, 4, 5, 6];
$evenNumbers = array_filter($numbers, function ($number) {
return $number % 2 === 0;
});
print_r($evenNumbers);
?>Named functions can also be used as callbacks.
<?php
function makeUppercase($value) {
return strtoupper($value);
}
$names = ["php", "laravel", "symfony"];
$result = array_map("makeUppercase", $names);
print_r($result);
?>Callback functions are important in modern PHP because they help make code more flexible and expressive.
PHP JSON
JSON stands for JavaScript Object Notation. It is a common data format used to exchange information between applications, APIs, frontends, backends, mobile apps, and external services.
PHP provides json_encode() to convert PHP arrays or objects into JSON.
<?php
$user = [
"name" => "Adnan",
"role" => "Developer",
"active" => true
];
$json = json_encode($user);
echo $json;
?>The output will be a JSON string that can be sent to a frontend or API client.
PHP also provides json_decode() to convert JSON back into PHP data.
<?php
$json = '{"name":"Adnan","role":"Developer"}';
$data = json_decode($json, true);
echo $data["name"];
?>The second argument true tells PHP to convert the JSON object into an associative array.
JSON is used heavily in REST APIs, AJAX requests, configuration files, external integrations, and modern web applications.
When working with JSON, it is useful to check for errors using json_last_error() or json_last_error_msg().
<?php
$json = '{"name": "Adnan"';
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo json_last_error_msg();
}
?>PHP Exceptions
Exceptions are used to handle errors in a controlled way. Instead of allowing an error to break the application unexpectedly, PHP can throw an exception and catch it.
The basic structure uses try, catch, and sometimes finally.
<?php
try {
throw new Exception("Something went wrong.");
} catch (Exception $exception) {
echo $exception->getMessage();
}
?>The code inside the try block is executed first. If an exception is thrown, PHP moves to the catch block.
The finally block runs whether an exception happens or not.
<?php
try {
echo "Trying to process data.";
} catch (Exception $exception) {
echo $exception->getMessage();
} finally {
echo "Process finished.";
}
?>Exceptions are useful when working with databases, APIs, files, payments, authentication, and any operation that may fail.
You can also create custom exception messages for better debugging and cleaner error handling.
<?php
function divide($a, $b) {
if ($b === 0) {
throw new Exception("Division by zero is not allowed.");
}
return $a / $b;
}
try {
echo divide(10, 0);
} catch (Exception $exception) {
echo "Error: " . $exception->getMessage();
}
?>Good exception handling makes applications more stable and easier to debug.
How These Advanced PHP Topics Work Together
In real PHP projects, these advanced topics are often used together. For example, a user profile system may use sessions to check login status, file uploads to upload a profile image, filters to validate input, JSON to return API responses, and exceptions to handle errors.
A simple API response may combine validation, JSON, and exceptions.
<?php
header("Content-Type: application/json");
try {
$email = $_POST["email"] ?? "";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new Exception("Invalid email address.");
}
echo json_encode([
"success" => true,
"message" => "Email is valid."
]);
} catch (Exception $exception) {
echo json_encode([
"success" => false,
"message" => $exception->getMessage()
]);
}
?>This example uses form input, filters, exceptions, and JSON to create a simple response structure that could be used in an API or AJAX request.
Security Notes for Advanced PHP
Advanced PHP features are powerful, but they must be used carefully. File handling, uploads, cookies, sessions, and user input can create security risks if they are not handled properly.
Important security practices include:
Validate and sanitize all user input.
Use safe file names for uploaded files.
Restrict allowed upload extensions and file sizes.
Do not store sensitive data directly in cookies.
Use sessions securely for authentication-related data.
Escape output before displaying user data.
Handle exceptions without exposing sensitive server details.
Use proper permissions for files and upload directories.
In professional applications, frameworks such as Laravel provide built-in tools for validation, file storage, sessions, cookies, JSON responses, and exception handling. However, understanding these PHP concepts directly is important because it explains how the framework works behind the scenes.
Conclusion
Advanced PHP topics such as date and time, include, file handling, file open and read, file create and write, file upload, cookies, sessions, filters, advanced filters, callback functions, JSON, and exceptions are essential for building real web applications.
These features help developers manage files, validate data, remember users, exchange information with APIs, and handle errors in a structured way.
After learning these concepts, the next step is to practice by building small projects such as a contact form, file upload system, login system, JSON API, and simple dashboard. These projects will connect the PHP fundamentals with real development experience.

