Upload image using PHP
Mostly, we need to upload images during the development of a php website. So, today we will explain to you an easy way to upload image using php.
PHP File Upload, PHP upload image, Upload image and save to my folder in php, upload image file to server using php, How to Upload Files on Server in PHP, Handling file uploads, POST method uploads, Image Uploading in PHP, file upload in php example code demo.
Checkout more articles on PHP
PHP allows you to upload images in the directory of a website on a server. We divide this task in two steps:
1. Create HTML Form
Here, we create a file named index.php
that shows the image upload form.
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 | <!DOCTYPE html> <html> <head> <title>Image Upload using PHP</title> </head> <body> <form action="fileUpload.php" method="post" enctype="multipart/form-data"> Select Image: <input type="file" name="image" /> <input type="submit" name="submit" value="Upload" /> </form> </body> </html> |
To upload an image, we must add the enctype="multipart/form-data"
attributes in form tag. This form will be submitted to fileUpload.php
.
2. PHP code for file upload
Now, we write PHP code to upload images in fileUpload.php
.
fileUpload.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <?php if(isset($_POST["submit"])){ $uploadDir = "../uploads/"; $uploadPath = $uploadDir . basename($_FILES["image"]["name"]); $extensionsArr = ['jpeg','jpg','png']; $fileName = $_FILES['image']['name']; $fileSize = $_FILES['image']['size']; $fileTmpName = $_FILES['image']['tmp_name']; $fileType = $_FILES['image']['type']; $fileExtension = pathinfo($uploadPath,PATHINFO_EXTENSION); if (in_array($fileExtension,$extensionsArr)) { $uploadImage = move_uploaded_file($fileTmpName, $uploadPath); if($uploadImage){ $error = "Image uploaded successfully."; } else { $error = "There was some error in image uploading."; } } else{ $error = "This file extension not allowed."; } echo $error; } ?> |
That’s it for today.
Thank you for reading. Happy Coding!