How to File Upload in PHP

 To handle file uploads in PHP, you can use the $_FILES superglobal array. This array stores all the information about the uploaded file, including the file name, temporary storage location, and any errors that may have occurred during the file upload.

Here is an example of how you can handle file uploads in PHP:

<?php // Check if the form has been submitted if (isset($_POST['submit'])) { // Check if a file was uploaded if (isset($_FILES['uploaded_file'])) { // Get the file details $file = $_FILES['uploaded_file']; $file_name = $file['name']; $file_tmp_name = $file['tmp_name']; $file_size = $file['size']; $file_error = $file['error']; // Check if there were any errors if ($file_error === 0) { // Check if the file is too large if ($file_size <= 1000000) { // Generate a new file name to avoid overwriting existing files $new_file_name = uniqid('', true) . '.' . pathinfo($file_name, PATHINFO_EXTENSION); // Set the upload directory $upload_dir = 'uploads/'; // Try to move the uploaded file to the upload directory if (move_uploaded_file($file_tmp_name, $upload_dir . $new_file_name)) { // File upload was successful echo 'File uploaded successfully'; } else { // File upload failed echo 'Failed to upload file'; } } else { // File is too large echo 'File is too large'; } } else { // An error occurred during the file upload echo 'Error uploading file'; } } }

This code first checks if the form has been submitted and then checks if a file was uploaded. It then retrieves the file details from the $_FILES array and checks for any errors that may have occurred during the file upload. If there were no errors, it checks if the file is too large and, if it is not, generates a new file name and tries to move the uploaded file to the specified upload directory. If the file was successfully moved, it outputs a success message; otherwise, it outputs an error message.

It's important to note that this code is just an example and you may need to customize it to fit your specific needs. For example, you may want to add additional checks to validate the file type, size, or other details before allowing the file to be uploaded.

Popular posts from this blog

Ajax Toggle(on/off) on-click Update

Yii Framework In Update Time View Image In Form