π PHP Files and Uploads
PHP has built-in functions to read, write and upload files to the file system. These tools can be very useful for enhancing the user experience as they provide a means for customizing the user interface with personalized user information and content.
Form for File Upload
- Use
method="post"
to form tag. - Add
enctype="multipart/form-data"
to form tag. - Use
<input type="file" name="xxx" />
as the form field. input type="file"
generates a browse button for the user to locate the file.- Upon submission of the form the file is uploaded along with other form input.
Example
<section class="container">
<p>New members must register before entering.</p>
<form action="membership.php" enctype="multipart/form-data" method="post">
<div class="form-group">
<label for="firstname">First Name:</label>
<input type="text" name="firstname" id="firstname" value="$firstname" class="form-control"> $invalid_firstname
</div>
<div class="form-group">
<label for="lastname">Last Name:</label>
<input type="text" name="lastname" id="lastname" value="$lastname" class="form-control"> $invalid_lastname
</div>
<div class="form-group">
<label for="email">E-Mail:</label>
<input type="text" name="email" id="email" value="$email" class="form-control"> $invalid_email $invalid_email_format
</div>
<p>Please select an image for your profile.</p>
<div class="form-group">
<input type="hidden" name="MAX_FILE_SIZE" value="100000">
<label for="profilePic">File to Upload:</label> $invalid_image
<input type="file" name="profilePic" id="profilePic" class="form-control">
</div>
<div class="form-group">
<input type="submit" name="submit" value="Submit Profile" class="btn btn-primary">
</div>
</form>
</section>\n
PHP File Upload Directives
There are several directives in the php.ini file that are important for file upload:
- file_uploads = on - required for a php script to accept a file upload
- max_execution_time = 30 - maximum number of seconds that a PHP script will execute before registering a fatal error. This may restrict file sizes that are uploaded. Default is 30
- memory_limit = 8M - maximum allowable megabytes of memory - prevents runaway scripts. Default is 8M
- upload_max_filesize = 2M - maximum file size in megabytes for an uploaded file. Default is 2M
- upload_temp_dir = filepath - location for temporary placement of file while it is located. Default is null. Files cannot be uploaded unless a location is specified and Apache has write permissions to the directory. The file will be deleted from this directory when execution of the script terminates
- post_max_size = 8M - maximum size of data uploaded via POST method. Must be larger than uploadd_max_filesize. Default is 8M
$_FILES Array
By using the global PHP $_FILES array you can upload files from a client computer to the remote server.
The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this:
$_FILES["file"]["name"]
- the name of the uploaded file
$_FILES["file"]["type"]
- the type of the uploaded file - deprecated
A better way to get the file type is to usepathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$_FILES["file"]["size"]
- the size in bytes of the uploaded file
$_FILES["file"]["tmp_name"]
- the name of the temporary copy of the file stored on the server
$_FILES["file"]["error"]
- the error code resulting from the file upload
File Upload functions
move_uploaded_file($_FILES[ 'userfile']['tmp_name'], " filepath".$_FILES['userfile']['tmp_name']
- moves the specified file to the location specified by the filepath
is_uploaded_file($_FILES['userfile']['tmp_name'])
- tests to see if the specified file is uploaded. Used to prevent unauthorized manipulation of files.
File Upload Example
<?php
// only allow files that are gif, png or jpeg files to be uploaded and restrict size to 20KB
$filetype = pathinfo($_FILES['profilePic']['name'],PATHINFO_EXTENSION);
if ((($filetype == "gif") or ($filetype == "jpg") or ($filetype == "png")) and $_FILES['profilePic']['size'] < 100000) {
// check to make sure there is no error on the upload. If so, display the errror
if ($_FILES["profilePic"]["error"] > 0) {
echo "Return Code: " . $_FILES["profilePic"]["error"] . "<br>";
} else {
// display information about the file
echo "Upload: " . $_FILES["profilePic"]["name"] . "<br>";
echo "Type: " . $_FILES["profilePic"]["type"] . "<br>";
echo "Size: " . ($_FILES["profilePic"]["size"] / 1024) . " Kb<br>";
echo "Temp file: " . $_FILES["profilePic"]["tmp_name"] . "<br>";
// if the file already exists in the upload directory, give an error
if (file_exists("upload/" . $_FILES["profilePic"]["name"])) {
echo $_FILES["profilePic"]["name"] . " already exists. ";
} else {
// move the file to a permanent location
move_uploaded_file($_FILES["profilePic"]["tmp_name"],"upload/" . $_FILES["profilePic"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["profilePic"]["name"];
}
}
} else {
echo "Invalid file";
}
?>
The examples above should work to create an HTML form and process with PHP to upload a file and display basic information about the file. To improve the application, each of the echo statements should be assigned to a variable and used within the context of a formatted page display. It may also be helpful to assign each of the $_FILES["profilePic"] elements to a local variable for better application development.
File Handling Functions
Mode | Function |
---|---|
r | Read only. Starts at the beginning of the file |
r+ | Read/Write. Starts at the beginning of the file |
w | Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist |
w+ | Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist |
a | Append. Opens and writes to the end of the file or creates a new file if it doesn't exist |
a+ | Read/Append. Preserves file content by writing to the end of the file |
x | Write only. Creates a new file. Returns FALSE and an error if file already exists |
x+ | Read/Write. Creates a new file. Returns FALSE and an error if file already exists |
- Open a file
- "filename" is the name (and path if not the default) of the file. If a file is opened with mode a, w, or w+, it will be created if it does not already exist.
- "mode" is the type of access
-
/* Format */ fopen("filename", "mode"); /* Example */ $newfile = fopen("newfile.txt", "w+");
- Close a file
- fileIdentifier is the variable assigned to the file in the fopen statement
-
/* Format */ fclose(fileIdentifier); /* Example */ fclose($newfile);
- Write to a file
- file is the variable assigned to the file in the fopen() statement
- string is the text to write out to the file
- length is optional and specifies the maximum number of characters to be written
-
/* Format */ fwrite(file, string, length); /* Example */ fwrite($newfile, "File content");
- Read from a file
- file is the variable assigned to the file in the fopen() statement
- length is optional and specifies the number of bytes to read. Default is 1024 bytes.
- fgets will stop returning on a new line, at the specified length, or at EOF, whichever comes first.
-
/* Format */ fgets(file, length); /* Example */ fgets($newfile); // reads one line from a file fgets($newfile, 10); // reads 10 bytes of data from a file
- Check for end of file
- file is the variable assigned to the file in the fopen() statement
- feof() returns True if the end of file has been reached or if an error occured; otherwise returns False
-
/* Format */ feof(file); /* Example */ if (!feof($newfile)) { fgets($newfile); }
- Lock a file
- file is the variable assigned to the file in the fopen() statement
- type specifies the type of lock:
- LOCK_SH - shared for reading
- LOCK_EX - exclusive for writing
- LOCK_UN - release lock
- LOCK_NB - non-blocking lock
-
/* Format */ f(filelock, type); /* Example */ flock($newfile, LOCK_EX); // locks the file fwrite($newfile, "file content"); // writes to the file flock($newfile, LOCK_UN); // unlocks the file
- Read a file into an array
- file is the variable assigned to the file in the fopen() statement
-
/* Format */ file(file); /* Example */ $myArray = file($newFile);
- Open a directory (folder)
- opens a directory so it can be read
- returns FALSE if it doesn't exist
- must be used before readdir(), closedir(), or rewinddir() can be used
-
/* Format */ opendir(directoryName); /* Example */ $myDir = opendir("c:\images");
- Get the names of all files in a directory or folder
- directoryStream is the directory stream from an opendir() command
- the name of the next file in the directory will be placed in $file
- when no more files are found in the directory, $file will contain FALSE
-
/* Format */ $file=readdir(directoryStream); /* Example */ $file=readdir($myDir);
- Change to a directory
- returns TRUE if successful, FALSE if not
- directory is the directory or folder to change to. It can be a fully qualified or relative path
-
/* Format */ chdir(directory); /* Example */ chdir("c:\images"); chdir("images");
- Close a directory
- closes a directory previously opened with opendir()
- directoryStream is the variable created from the opendir() function
-
/* Format */ closedir(directoryStream); /* Example */ closedir($myDir);
Β File Handling Examples
Writing to a text file.
One common task for using the file handling functions of PHP is to write to a text file. There are a variety of ways to write to a file including replacing and appending file contents. If you want to create a file that would record logins, you would want to capture the login information and append the file contents. That way you would be creating a growing record of logins. This works well with other log files, too.
/* Append a txt File Example */
// specify the name of the txt file
$filename = "membership.txt";
// format the form data to be saved to the txt file
$data_entry = $firstname . "," . $lastname . "," . $email . "," . $username . "\n";
// open the txt file ($filename) to append (a) and assign it to a file handle ($fp)
$fp = fopen($filename, "a") or die ("Couldn't open file, sorry.");
// write (fwrite) the data ($data_entry) to the file using the file handle ($fp)
if (fwrite($fp, $data_entry) > 0) { // successful write operation returns 1, failure returns 0
// do this on success
$logged_in = TRUE; // sets a login trigger for the program to switch from form display to content display
} else {
// do this on failure
echo "Your information was not saved. Please try again at another time.";
}
$fp = fclose($fp); // close the file
Reading from a text file.
Another common task for using the file handling functions of PHP is to read from a text file. If you want to use content from a saved file, you would use fopen to open teh file and fgets to read the file contents.
/* Read a txt File Example */
// specify the name of the txt file
$poem = "poem.txt";
// open the txt file ($poem) to read (r) and assign it to a file handle ($fp)
$fp = fopen($poem, "r") or die ("Couldn't open file, sorry.");
if (!feof($fp)) { // keep reading the open file ($fp) until the end of file (foef)
// do this on success
$poemText = fgets($fp); // assign the file content to a variable for later use in the program
} else {
// do this on failure
echo "Your information was not found. Please try again at another time.
";
}
$fp = fclose($fp); // close the file
It will help if you create the supporting text files before running the application. You will also need some additional coding to create the context for these programs. For the write file application, you will need a form to collect the information. For the read application, you'll need a file that has content already saved.