File Handling
PHPPHP can read, write, and manipulate files on the server. This is useful for logs, file uploads, configuration files, and more.
Reading a File
PHP
<?php
// Read entire file as string
$content = file_get_contents("data.txt");
echo $content;
// Read file into array (one line per element)
$lines = file("data.txt", FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
echo $line . "<br>";
}
?>Writing to a File
PHP
<?php
// Write (overwrites existing content)
file_put_contents("log.txt", "Hello, World!");
// Append to file
file_put_contents("log.txt", "New line\n", FILE_APPEND);
// Write with fopen (more control)
$file = fopen("log.txt", "a"); // 'a' = append
fwrite($file, date("Y-m-d H:i:s") . " — User logged in\n");
fclose($file);
?>File Upload
HTML + PHP
<!-- HTML form -->
<form method="POST" enctype="multipart/form-data">
<input type="file" name="photo" />
<button type="submit">Upload</button>
</form>
<?php
if (isset($_FILES["photo"])) {
$file = $_FILES["photo"];
// Validate
$allowed = ["image/jpeg", "image/png", "image/gif"];
if (!in_array($file["type"], $allowed)) {
die("Only images allowed.");
}
if ($file["size"] > 2 * 1024 * 1024) { // 2MB
die("File too large.");
}
// Move to uploads folder
$destination = "uploads/" . basename($file["name"]);
move_uploaded_file($file["tmp_name"], $destination);
echo "Upload successful!";
}
?>Checking Files & Directories
PHP
<?php
// Check existence
file_exists("data.txt"); // true/false
is_file("data.txt"); // is it a file?
is_dir("uploads/"); // is it a directory?
// File info
filesize("data.txt"); // size in bytes
filemtime("data.txt"); // last modified timestamp
pathinfo("photo.jpg"); // ['extension' => 'jpg', ...]
// Create directory
mkdir("uploads", 0755, true);
// Delete
unlink("old_file.txt"); // delete file
rmdir("empty_folder"); // delete empty directory
?>💡
In Laravel, use Storage facade!
Storage::put('file.txt', $content), Storage::get('file.txt'). It supports local storage, S3, and other drivers with the same API.Test your knowledge!
Take the PHP Basics quiz.