Working with directories
Working with directories
Working with directories, file uploading, and downloading are common tasks in web development. Here's how you can perform these operations in PHP:
### Working with Directories:
#### Creating a Directory:
```php
<?php
$dirName = "new_directory";
if (!is_dir($dirName)) {
mkdir($dirName); // Creates a new directory
echo "Directory created successfully.";
} else {
echo "Directory already exists.";
}
?>
```
#### Reading a Directory:
```php
<?php
$dirName = "."; // Current directory
$files = scandir($dirName); // Get list of files and directories
print_r($files);
?>
```
#### Deleting a Directory:
```php
<?php
$dirName = "directory_to_delete";
if (is_dir($dirName)) {
rmdir($dirName); // Removes the directory
echo "Directory deleted successfully.";
} else {
echo "Directory not found.";
}
?>
```
### File Uploading:
#### Creating an HTML Form for File Upload:
```html
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="file" id="file">
<input type="submit" value="Upload File" name="submit">
</form>
```
#### Handling File Upload in PHP (upload.php):
```php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$targetDir = "uploads/"; // Directory to save uploaded files
$targetFile = $targetDir . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
echo "File uploaded successfully.";
} else {
echo "Error uploading the file.";
}
}
?>
```
### File Downloading:
#### Creating a Download Link:
```php
<?php
$filename = "example.txt";
if (file_exists($filename)) {
echo "<a href='download.php?file=$filename'>Download $filename</a>";
} else {
echo "File not found.";
}
?>
```
#### Handling File Download in PHP (download.php):
```php
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET["file"])) {
$filename = $_GET["file"];
$filepath = "path/to/your/files/" . $filename;
if (file_exists($filepath)) {
header("Content-Disposition: attachment; filename=$filename");
readfile($filepath); // Output the file to the browser
exit;
} else {
echo "File not found.";
}
}
?>
```
In the above examples, replace `"path/to/your/files/"` with the actual path to the directory containing your files. Always validate user input and set appropriate permissions to ensure security when working with file operations.
Comments
Post a Comment