Page Stats
Visitor: 468
With PHP, you can upload files to the server, File format can be of any kind like images, videos, ZIP files, Microsoft Office documents, PDFs, as well as executables files. To upload a file first configure the "php.ini" file, In "php.ini" file, search for the file_uploads directive, and set it to On.
Some rules to follow for the HTML form:
Make sure that the form uses method="post"
The form also needs the following attribute: enctype="multipart/form-data". This attribute ensures that the form data is encoded as mulitpart MIME data — which is required for uploading the large quantities of binary data such as files.
Once the form is submitted information about the uploaded file can be accessed via PHP superglobal array called $_FILES. For example, our upload form contains a file select field called photo (i.e. name="photo"), if any user uploaded a file using this field, we can obtains its details like the name, type, size, temporary name or any error occurred while attempting the upload via the $_FILES["photo"] associative array, like this:
$_FILES["photo"]["name"] — This array value specifies the original name of the file, including the file extension. It doesn't include the file path.
$_FILES["photo"]["type"] — This array value specifies the MIME type of the file.
$_FILES["photo"]["size"] — This array value specifies the file size, in bytes.
$_FILES["photo"]["tmp_name"] — This array value specifies the temporary name including full path that is assigned to the file once it has been uploaded to the server.
$_FILES["photo"]["error"] — This array value specifies error or status code associated with the file upload.
<?php if($_FILES["photo"]["error"] > 0){ echo "Error: " . $_FILES["photo"]["error"] . "<br>"; } else{ echo "File Name: " . $_FILES["photo"]["name"] . "<br>"; echo "File Type: " . $_FILES["photo"]["type"] . "<br>"; echo "File Size: " . ($_FILES["photo"]["size"] / 1024) . " KB<br>"; echo "Stored in: " . $_FILES["photo"]["tmp_name"]; } ?>Example 1: Create The HTML Form. upload.php file
Check if the file already exists in the "uploads" folder. If it does, an error message is displayed, and if it does not exists than save the file in upload folder.
// Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; }
Check the size of the file. If the file is larger than 500kb, an error message is displayed.
if ($_FILES["file1"]["size"] > 500000) { echo "Sorry, your file is more than 500kb."; }
Allow only JPG, JPEG, PNG & GIF files.
echo $_FILES['file1']['type']; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); if($imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType != "png" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; }