Home / PHP/MySQL Tutorials / Archive by category 'PHP File Handling'

PHP File Handling

php-file-handling

Read JSON from file in PHP

$file = new File('/path/to/file');
$myjson = $file->read(true, 'r');
$myjsonarray = json_decode($json);

Write JSON to file in PHP

$json = '{"key":"value"}';
$file = new File('/path/to/file', true);
$file->write($json);

Secure image upload script in PHP

<?php // upload.php
echo <<<_END
<html><head><title>PHP Form Upload</title></head><body>
<form method='post' action='upload2.php' enctype='multipart/form-data'>
Select a JPG, GIF, PNG or TIF File:
<input type='file' name='filename' size='10' />
<input type='submit' value='Upload' /></form>
_END;
if ($_FILES)
{
$name = $_FILES['filename']['name'];
switch($_FILES['filename']['type'])
{
case 'image/jpeg': $ext = 'jpg'; break;
case 'image/gif': $ext = 'gif'; break;
case 'image/png': $ext = 'png'; break;
case 'image/tiff': $ext = 'tif'; break;
default: $ext = ''; break;
}
if ($ext)
{
$n = "image.$ext";
move_uploaded_file($_FILES['filename']['tmp_name'], $n);
echo "Uploaded image '$name' as '$n':<br />";
echo "<img src='$n' />";
}
else echo "'$name' is not an accepted image file";
}
else echo "No image has been uploaded";
echo "</body></html>";
?>

Common Internet media content types

application/pdf
image/gif
multipart/form-data
text/xml
application/zip
image/jpeg
text/css
video/mpeg
audio/mpeg
image/png
text/html
video/mp4
audio/x-wav
image/tiff
text/plain
video/quicktime


Contents of the $_FILES array in PHP

$_FILES['file']['name']
The name of the uploaded file (e.g., somefile.jpg)
$_FILES['file']['type']
The content type of the file (e.g., image/jpeg)
$_FILES['file']['size']
The file’s size in bytes
$_FILES['file']['tmp_name']
The name of the temporary file stored on the server
$_FILES['file']['error']
The error code resulting from the file upload


Image uploader in PHP

<?php // upload.php
echo <<<_END
<html><head><title>PHP Form Upload</title></head><body>
<form method='post' action='upload.php' enctype='multipart/form-data'>
Select File: <input type='file' name='filename' size='10' />
<input type='submit' value='Upload' />
</form>
_END;
if ($_FILES)
{
$name = $_FILES['filename']['name'];
move_uploaded_file($_FILES['filename']['tmp_name'], $name);
echo "Uploaded image '$name'<br /><img src='$name' />";
}
echo "</body></html>";
?>

Updating a file with file locking in PHP

<?php
$fh = fopen("testfile.txt", 'r+') or die("Failed to open file");
$text = fgets($fh);
fseek($fh, 0, SEEK_END);
if (flock($fh, LOCK_EX))
{
fwrite($fh, "$text") or die("Could not write to file");
flock($fh, LOCK_UN);
}
fclose($fh);
echo "File 'testfile.txt' successfully updated";
?>

Updating a file in PHP

open testfile.txt for both reading and writing by setting the mode with ‘+r’, which puts the file pointer right at the start. It then uses the fgets function to read in a single line from the file (up to the first line feed). After that, the fseek function is called to move the file pointer right to the file end, at which point the line of text that was extracted from the start of the file (stored in $text) is then appended to file’s end and the file is closed.

<?php // update.php
$fh = fopen("testfile.txt", 'r+') or die("Failed to open file");
$text = fgets($fh);
fseek($fh, 0, SEEK_END);
fwrite($fh, "$text") or die("Could not write to file");
fclose($fh);
echo "File 'testfile.txt' successfully updated";
?>

Deleting a File in PHP

Deleting a file is just a matter of using the unlink function to remove it from the file system.

<?php // deletefile.php
if (!unlink('testfile.txt')) echo "Could not delete file";
else echo "File 'testfile' successfully deleted";
?>

Syntax for copying a file in PHP

<?php // copyfile2.php
if (!copy('testfile.txt', 'testfile2.txt')) echo "Could not copy file";
else echo "File successfully copied to 'testfile2.txt'";
?>

Copying a file in PHP

<?php // copyfile.php
copy('testfile.txt', 'testfile2.txt') or die("Could not copy file");
echo "File successfully copied to 'testfile2.txt'";
?>

Reading a file with fread in PHP

<?php
$fh = fopen("testfile.txt", 'r') or
die("File does not exist or you lack permission to open it");
$text = fread($fh, 3);
fclose($fh);
echo $text;
?>

Reading a file with fgets in PHP

<?php
$fh = fopen("testfile.txt", 'r') or
die("File does not exist or you lack permission to open it");
$line = fgets($fh);
fclose($fh);
echo $line;
?>

Creating a simple text file in PHP

1. Always start by opening the file. This is done through a call to fopen.
2. Then you can call other functions; here we write to the file (fwrite), but you can
also read from an existing file (fread or fgets) and do other things.
3. Finish by closing the file (fclose).

<?php // testfile.php
$fh = fopen("testfile.txt", 'w') or die("Failed to create file");
$text = <<<_END
Line 1
Line 2
Line 3
_END;
fwrite($fh, $text) or die("Could not write to file");
fclose($fh);
echo "File 'testfile.txt' written successfully";
?>

Checking Whether a File Exists in PHP

To determine whether a file already exists, you can use the file_exists function, which returns either TRUE or FALSE, and is used like this:

if (file_exists("somefile.txt")) echo "File exists";

Displaying Content of a Text File in PHP

 
<?php
$file='info.txt';
$fobj=fopen($file,"r");
$text=fread($fobj, filesize($file));
echo("<h2><font color='blue'>Displaying Content of a Text File</font><h2>");
echo("<br>");
echo("<font size=3>");
echo($text);
echo("</font>");
fclose($fobj);
?>

How to upload multiple files using PHP and HTTP Post

We can implement this in two ways. One as an array of files and the other as individual variables.

Method 1:
In the html form, set multiple file input boxes, use the array name as their names, as follows:

<form action="upload" method=post> 
<input type=file name=upfile[]/> 
<input type=file name=upfile[]/> 
<input type=file name=upfile[]/> 
</ Form>

On the server side we can test for the uploaded files as:

echo "<b>"; 
print_r ($ _FILES); 
echo "</b>";

Method 2:
In the html form set multiple file input boxes, but use different names for each one, as follows:

<form action="upload.php" method=post> 
<input type=file name=upfile_1/> 
<input type=file name=upfile_2/> 
<input type=file name=upfile_2/> 
</ Form>

On the server side we can test uploads same way:

echo "<b>"; 
print_r ($ _FILES); 
echo "</b>";

Display subfolders from directory using php

Example to display subfolders from directory using php:

<?php
echo "<h2>subdirs in dir</h2><ul>";
$basedir = basename( __FILE__ );
$dirtoscan = ($basedir . '/somedir/');
$albumlisting = scandir($dirtoscan);
foreach ($albumlisting as $item) {
            $dirinfo = pathinfo($item);
            print_r($dirinfo);
            if (is_dir("$item")) {
                    echo "<li><a href='index.php?subdirs=$item'>$item</a></li>";
                     }
}
?>

Display dropdown file list in PHP using DirectoryIterator

To iterate over all files in a directory, we can use a DirectoryIterator to get each file in the directory. The example shows how to create a

<select/>

box in a form that lists all the files in a directory.

<?php
echo "<select name='file'>\n";
foreach (new DirectoryIterator('c:\wamp\www') as $file) {
    echo '<option>' . htmlentities($file) . "</option>\n";
}
echo '</select>';
?>

using xcopy with PHP exec

The xcopy command can be used to move/copy files/folders from one place to another.

Example:

<?php 
exec('xcopy c:\\myfolder d:\\myfolder /e/i', $a, $a1); 
?>

by executing this command, it will move folder along with all contents to destination.