File - potatoscript/php GitHub Wiki
PHP provides a wide range of functions for handling files, from reading and writing to file manipulation and error handling. This section covers:
- Reading Files
- Writing Files
- File Handling Functions
- File Uploads
- File Permissions
- File System Functions
PHP makes it easy to read files in various ways. The most common methods are fopen()
, file_get_contents()
, and readfile()
.
<?php
// Read the content of a file into a string
$content = file_get_contents('example.txt');
echo $content; // Outputs the content of 'example.txt'
?>
-
file_get_contents()
reads the entire file into a string. This is the simplest and most common method for reading text files.
<?php
// Open the file for reading
$file = fopen('example.txt', 'r');
if ($file) {
// Read one line at a time
while (($line = fgets($file)) !== false) {
echo $line . "<br>"; // Outputs each line of the file
}
fclose($file); // Close the file after reading
} else {
echo "Unable to open the file.";
}
?>
-
fopen()
opens a file for reading or writing. -
fgets()
reads a file line by line, which is useful for processing large files.
You can write data to files using the fopen()
, fwrite()
, and file_put_contents()
functions.
<?php
// Write data to a file (overwrites the file)
file_put_contents('example.txt', 'Hello, world!');
?>
-
file_put_contents()
writes data directly to a file. It overwrites the file if it already exists, and creates the file if it does not exist.
<?php
// Open the file for writing
$file = fopen('example.txt', 'w');
if ($file) {
// Write data to the file
fwrite($file, 'Hello, world!');
fclose($file); // Close the file after writing
} else {
echo "Unable to open the file.";
}
?>
-
fopen()
with the'w'
mode opens the file for writing and truncates it to zero length if it exists. -
fwrite()
writes data to the file.
PHP offers several useful functions for file manipulation, such as checking file existence, getting file sizes, and modifying file permissions.
<?php
// Check if a file exists
if (file_exists('example.txt')) {
echo "The file exists.";
} else {
echo "The file does not exist.";
}
?>
-
file_exists()
checks whether the specified file exists.
<?php
// Get the size of the file
$fileSize = filesize('example.txt');
echo "The size of the file is: $fileSize bytes.";
?>
-
filesize()
returns the size of the file in bytes.
<?php
// Change the file permissions
chmod('example.txt', 0755);
echo "File permissions changed.";
?>
-
chmod()
changes the permissions of a file. The second parameter specifies the permissions in octal format.
PHP makes it easy to handle file uploads from forms using the $_FILES
superglobal array. Here's how to handle file uploads securely:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
// Check if the file is an actual image (optional)
if (isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if ($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if the file already exists
if (file_exists($targetFile)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size (max 5MB)
if ($_FILES["fileToUpload"]["size"] > 5000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow only certain file formats
if ($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg" && $fileType != "gif") {
echo "Sorry, only JPG, JPEG, PNG, and GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
-
$_FILES
is used to access uploaded files. -
move_uploaded_file()
moves the uploaded file to a specified directory. - The file upload is secured by checking for file type, file size, and whether the file already exists.
Managing file permissions is an important part of file handling. PHP provides functions like chmod()
, chown()
, and chgrp()
to control file permissions.
<?php
// Change the file permissions to be readable and writable by the owner
chmod('example.txt', 0644);
?>
-
chmod()
changes the permissions of a file, and the octal value0644
grants read/write permissions for the owner and read-only permissions for others.
PHP provides a variety of file system functions for creating, deleting, and checking directories.
<?php
// Create a new directory
mkdir('new_directory');
echo "Directory created successfully.";
?>
<?php
// Remove an empty directory
rmdir('new_directory');
echo "Directory removed successfully.";
?>
-
mkdir()
creates a directory. -
rmdir()
removes an empty directory.
In this section, we covered the following topics:
-
Reading Files: Using
file_get_contents()
,fopen()
, andfgets()
to read files. -
Writing Files: Writing data to files using
file_put_contents()
andfwrite()
. - File Handling Functions: Checking file existence, retrieving file size, and modifying file permissions.
-
File Uploads: Handling file uploads from forms securely with
$_FILES
. -
File Permissions: Managing file permissions with
chmod()
,chown()
, andchgrp()
. -
File System Functions: Creating and removing directories using
mkdir()
andrmdir()
.
By mastering these functions, you’ll be able to handle various file operations in PHP. In the next section, we will dive into MySQL Database Integration, where we will learn how to interact with databases using PHP.
- Basic definition
- JSON File Write and Read
- Output to Excel :
header("content-type:application/vnd.ms-excel");
- Read File
- Upload File
- Directory of current included file
- if a script called 'database.php' which is included from anywhere on the filesystem would like to include the script 'database_class.php', which lays in the same directory
include_one(dirname(__FILE__).`/database_class.php`);
- FILE : The full path and filename of the file with symlinks resolved. If used inside an include. The name of the included file is returned.
- LINE : The current line number of the file.
- DIR : The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(FILE)
- FUNCTION : The function name
- CLASS : The class name, included the namespace it was declared in (Foo\Bar)
header('Content-Type:application/json');
$content = "../../apps/".$_POST["file"];
$datalist = json_decode(file_get_contents($content),true);
echo json_encode($datalist);
$fp = fopen('../../data.json','w');
fwrite($fp,json_encode($datalist));
fwrite($fp);
_.$Params('file','data.json'); //my own function
$directory = 'files';
if($handle = opendir($directory.'/')){
echo 'search\''.$directory.'\':<br>';
while($file= readdir($handle)){
if($file!='.'&& file != '..'){
echo '<a href="'.$directory.'/'.$file.'">'.$file.'</a>';
}
}
}
echo 'addExpandCollapseAll();startParentNode('2010');';
$directory = "tcd/2010/";
if($handle = opendir($directory)){
while($file = readdir($handle)){
if($file!='.' && $file != '..'){
echo 'addNode(\'<a href="'.$directory.$file.' ">'.$file.'</a>\');';
}
}
}
echo 'endParentNode();';
$name = $_FILES['file']['name'];
$size = $_FILES['file']['size'];
$type = $_FILES['file']['type'];
$tmp_name = $_FILES['file']['tmp_name'];
if(isset($name)){
if(!empty($name)){
$location = 'uploads/';
if(move_uploaded_file($tmp_name,$location,$name)){
echo 'uploaded!';
}
}else{
echo 'please choose a file.';
}
}
<form action="upload.php" method="POST" enctype="multipart/form_data">
<input type="file" name="file">
<input type="submit" value="submit">
</form>