With PHP, it is easy to upload files to the server. Show However, with ease comes danger, so always be careful when allowing file uploads! Configure The "php.ini" FileFirst, ensure that PHP is configured to allow file uploads. In your "php.ini" file, search for the Create The HTML FormNext, create an HTML form that allow users to choose the image file they want to upload: <!DOCTYPE
html> <form action="upload.php" method="post" enctype="multipart/form-data"> </body> Some rules to follow for the HTML form above:
Without the requirements above, the file upload will not work. Other things to notice:
The form above sends data to a file called "upload.php", which we will create next. Create The Upload File PHP ScriptThe "upload.php" file contains the code for uploading a file: <?php PHP script explained:
Note: You will need to create a new directory called "uploads" in the directory where "upload.php" file resides. The uploaded files will be saved there. Check if File Already ExistsNow we can add some restrictions. First, we will check if the file already exists in the "uploads" folder. If it does, an error message is displayed, and $uploadOk is set to 0: // Check if file already exists Limit File SizeThe file input field in our HTML form above is named "fileToUpload". Now, we want to check the size of the file. If the file is larger than 500KB, an error message is displayed, and $uploadOk is set to 0: // Check file size Limit File TypeThe code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types gives an error message before setting $uploadOk to 0: // Allow certain file formats Complete Upload File PHP ScriptThe complete "upload.php" file now looks like this: <?php // Check if image file is a actual image or fake image // Check if file already exists // Check file size // Allow certain file formats // Check if $uploadOk is set to 0 by an error Complete PHP Filesystem ReferenceFor a complete reference of filesystem functions, go to our complete PHP Filesystem Reference. Move_uploaded_file untuk apa?Fungsi move_uploaded_file() digunakan untuk memindahkan file yang diunggah ke tujuan baru. Catatan: Fungsi ini hanya berfungsi pada file yang diunggah melalui mekanisme unggahan HTTP POST PHP. Catatan: Jika file tujuan sudah ada, maka file itu akan ditimpa.
Apa itu Tmp_name?tmp_name adalah nama file yang berada di dalam direktori temporer server; error menyatakan apakah ada error atau tidak; size adalah ukuran file-nya.
|