Spex3
    

PHP File Uploads & Directory Operations


    

    

PHP File Uploads & Directory Operations
PHP allows users to upload files and perform directory operations such as creating, deleting, and managing directories.

1. Handling File Uploads in PHP
Uploading files in PHP involves:

Creating an HTML form ().

Configuring PHP to handle file uploads.

Moving the uploaded file to a designated folder.

1.1 Configuring php.ini for File Uploads
Ensure file uploads are enabled in php.ini:


file_uploads = On
upload_max_filesize = 10M ; Maximum file size
post_max_size = 12M ; Maximum POST request size

📌 Restart the server after changes.

1.2 Creating an HTML Form for File Upload
✅ Example: File Upload Form (upload.html)


<form action="upload.php" method="post" enctype="multipart/form-data">
<label>Select a file:</label>
<input type="file" name="fileToUpload">
<input type="submit" value="Upload File">
</form>


📌 Important:

Use enctype="multipart/form-data" to send files.

The name="fileToUpload" is used to access the file in PHP.

1.3 Processing the File Upload (upload.php)

✅ Example: Handling the File Upload


<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$targetDir = "uploads/"; // Directory to store files
$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

// Check if file already exists
if (file_exists($targetFile)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}

// Allow only certain file types
$allowedTypes = ["jpg", "png", "gif", "pdf"];
if (!in_array($fileType, $allowedTypes)) {
echo "Only JPG, PNG, GIF, and PDF files are allowed.";
$uploadOk = 0;
}

// Check file size (limit: 5MB)
if ($_FILES["fileToUpload"]["size"] > 5 * 1024 * 1024) {
echo "File is too large (Max: 5MB).";
$uploadOk = 0;
}

// Move file if valid
if ($uploadOk) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
} else {
echo "Error uploading file.";
}
}
}
?>


✅ Explanation:

Store files in an uploads/ directory.

Check if the file exists to prevent overwriting.

Restrict file types (jpg, png, gif, pdf).

Limit file size (5MB).

Move uploaded file from temporary storage to the uploads/ folder.

1.4 Displaying Uploaded Files
✅ Example: Listing Uploaded Files


<?php
$files = scandir("uploads/");
foreach ($files as $file) {
if ($file !== "." && $file !== "..") {
echo "<a href='uploads/$file'>$file</a><br>";
}
}
?>


1.5 Deleting Uploaded Files
✅ Example: Deleting an Uploaded File


<?php
$file = "uploads/sample.jpg";
if (file_exists($file)) {
unlink($file);
echo "File deleted successfully.";
} else {
echo "File not found.";
}
?>


2. Directory Operations in PHP
PHP provides functions to create, delete, and list directories.

2.1 Creating a Directory (mkdir())
✅ Example: Create a Directory


<?php
$dir = "my_directory";
if (!file_exists($dir)) {
mkdir($dir, 0777, true); // Create directory with full permissions
echo "Directory created: $dir";
} else {
echo "Directory already exists.";
}
?>


📌 Permissions (0777) allow read, write, and execute access.

2.2 Listing Files in a Directory (scandir())
✅ Example: List Files in a Directory


<?php
$dir = "uploads/";
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file !== "." && $file !== "..") {
echo $file . "<br>";
}
}
}
?>

📌 Note: "." (current directory) and ".." (parent directory) are ignored.

2.3 Checking if a Directory Exists (is_dir())
✅ Example: Check Directory Existence


<?php
$dir = "uploads/";
if (is_dir($dir)) {
echo "Directory exists.";
} else {
echo "Directory does not exist.";
}
?>


2.4 Deleting a Directory (rmdir())
✅ Example: Delete an Empty Directory


<?php
$dir = "old_directory";
if (is_dir($dir)) {
rmdir($dir);
echo "Directory deleted.";
} else {
echo "Directory not found.";
}
?>

📌 Note: rmdir() only deletes empty directories.

2.5 Deleting a Directory with Files
✅ Example: Delete a Directory with Files


<?php
function deleteDirectory($dir) {
if (!is_dir($dir)) return false;

foreach (scandir($dir) as $file) {
if ($file !== "." && $file !== "..") {
unlink("$dir/$file"); // Delete file
}
}
return rmdir($dir); // Remove directory
}

$dir = "uploads/";
if (deleteDirectory($dir)) {
echo "Directory and files deleted.";
} else {
echo "Error deleting directory.";
}
?>


Summary of File & Directory Functions
File Upload Functions
Function Description

move_uploaded_file($tmp, $destination) Moves uploaded file.
$_FILES["file"]["name"] Gets file name.
$_FILES["file"]["size"] Gets file size.
$_FILES["file"]["type"] Gets file type.
$_FILES["file"]["tmp_name"] Temporary file location.
Directory Functions
Function Description
mkdir($dirname, $permissions, $recursive) Creates a directory.
rmdir($dirname) Deletes an empty directory.
scandir($dirname) Lists files and directories.
is_dir($dirname) Checks if a directory exists.
unlink($filename) Deletes a file.


Conclusion
File Uploads
✅ Create an HTML form with .
✅ Use $_FILES[] to handle file uploads.
✅ Store files using move_uploaded_file().
✅ Validate file size and type before upload.

Directory Operations
✅ Use mkdir() to create directories.
✅ Use scandir() to list files.
✅ Use rmdir() to delete empty directories.
✅ Use unlink() to delete files inside a directory.


    Date: 2025-03-28 00:00:00.000000