Upload multiple images create thumbnails and save path to database with php and mysql

97

One of my blog follower Vikash Singh from West Bengal, requested me to provide some codes so that he can upload multiple images create thumbnails and save path to database with php and mysql. I could have directly sent him the codes but I am posting in my blog so that someone with similar problem could benefit from his request.

Scope of this script

I have posted similar topics before, check Upload multiple files with php, Upload and save image with PHP and MySql, Generating thumbnails on the fly. But in this case there’s a slight catch. When you upload multiple images, a thumbnail will be generated accordingly and its path will be stored in mysql database. So if you upload 4 images then total 8 images are stored.

Setup a form to upload multiple images

First of all you need to setup your form with file fields so you can attach multiple images. Here’s the first approach where you can attach multiple images using one file field. Make sure the name ends with [] and multiple=”multiple” attribute must be present.

The other approach is by using jquery where you can create multiple file fields. I have already posted an article Add remove multiple textfield with jquery. Just replace the textfield with file field. Also make sure you give [] with every name. [] denotes array.

Steps to upload multiple images with php

After you setup the form, it’s time to upload images. Uploading multiple images involves these steps:

Check if images are attached for uploading. There’s no point of going further if you haven’t attached any image to upload.

If you have attached images for uploading, the first priority is to check if its a valid image or not.

If the image file has passed the mime test, you can upload the image. Always generate a unique name to avoid overwriting any existing images on the server.

Steps to create thumbnails with PHP Image Magician

Why re-invent the tool if you already have them. PHP Image Magician is a very nice library to manipulate images. It’s features not only limit to creating thumnails, you can perform many amazing task like add text, resize,crop,sharpen, give color, save to transparent images and many more. Check the official site for more details.

Moving futher, you have to create a folder name “uploads” to save the main/larger images and inside uploads folder create “thumb” folder which will save the thumbnail of that image. The trick is that the thumnail version of the image will have the same name as the main/larger image just seperated by the directory name.

Coming back to our code, If the image is successfully uploaded you will then create a thumbnail of that image and store it in thumb folder.

Now the last part of this section is to insert the filename in mysql database. I have used PDO class. If you are still using old mysql_query it’s time to upgrade it. I have made a mini project Simple address book with php and mysql using pdo that will help you get started.

Display uploaded image with thumbnails

The most easiest part of all these section is fetching the records from the database and display both large and thumbnail image.

Download the source code below and run on your server. Hope this code helps you.
Download

Share.
 

About Author

Entrepreneur & Dreamer

I am a passionate Software Professional, love to learn and share my knowledge with others.

Software is the hardware of my life.

97 Comments

  1. hello, thanks for your code, but im getting error Call to undefined function exif_imagetype() in F:wampwwwsaveindex.php on line 48

    is there any solution?

  2. Florian Schubert on

    hey…
    I want to save each img file … in a different column…
    img_v1, img_v2, img_v3 and so on…

    how do I get the filename ?

    if I do that…

    $imgv1 = $_FILES[“user_files”][“tmp_name”][0];
    $imgv2 = $_FILES[“user_files”][“tmp_name”][1];

    the unique name wouldn’t be saved in the column, just the original name…

    please help me

  3. hi, is that possible to change the size of original uploaded image? I
    mean suppose i upload 2 mb and 4000×3000 pixels size , so this script
    will create 100×100 px thumb and move to thumb folder and original big
    image to main image upload folder. my question is can we resize the
    original image also, say 800×600 and thumb of 100×100?

    • Yes you can using phpimagemagician library that I have used in this script

      // include library class
      require_once(‘./php-image-magician/php_image_magician.php’);

      $magicianObj = new imageLib($filepath);
      // will create a 100 X 100 image, put your dimension here
      $magicianObj->resizeImage(100, 100);

      // saving file to thumb directory
      $magicianObj->saveImage($folderName . ‘thumb/’ . $filename, 100);

  4. Akhil P Ashok on

    i want to upload images through different fields.. like 1-logo 2-image1 3-image2 4-image3.
    how can i do that???

  5. Hi, Very nice tutorial but I tried to upload the images, and then it returned this message:
    Warning: move_uploaded_file(uploads/110310_1408656074.png): failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/photob/index.php on line 57

    Do you know why?
    Greetings!!
    Alex

      • Hi! Thank you for your replay! it has been very useful!
        Now appears this message:
        “The path is not writable. Please check your permissions”.
        BUT, Anyway, It already moved the file to the folder I assigned,
        thats good!,
        but nothing appears inserted on my database yet.

        Any suggestions?

          • Ok, since I am a beginner, can you tell me how to check my SQL
            on phpmyadmin and how to put the filename on the sql query?

          • Hi, I did what you said, I feed the file name in database, and yes,
            it appears the space for the thumbnail and the image, but they don´t show up, they show up like a question mark. How can I do to fix this?
            Chao!!

          • Ok, Also I fix this!!,
            But Do I have to write the filename in the database always?
            or is supposed to do it automatically?

  6. Also returned me this..
    Warning: move_uploaded_file(): Unable to move ‘/Applications/XAMPP/xamppfiles/temp/phpgx7TMA’ to ‘uploads/110310_1408656074.png’ in /Applications/XAMPP/xamppfiles/htdocs/photob/index.php on line 57

  7. giau nguyen thanh on

    hi guys! i have to trouble hope guys help me. Thank you very much.

    Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0

    Fatal error: Unknown: Failed opening required ‘C:/wamp/www/PHP/thủ thuật demo sÆ°u tầm/save_create_image_thumnail_php_mysql/index.php’ (include_path=’.;C:phppear’) in Unknown on line 0

    • Bro first create data base with give .. sql query with demo……. and then put all file in htdocs / root folder and
      then in index.php change database credential in file .. thats it

      then run .. it will run …. 100% sure… if its not working then reply…..

  8. hi,i have a problem .the problem is that only one image is uploaded in database while coding is for multiple images.I cross checked the coding but invain

  9. if i write $folderName = “uploads/***”; * some other folder then i am getting this the path is not writable. please check your permissions
    please help me in this
    thanks in advancd

  10. Hey shahrukh, thanks for a great tutorial……i need your guide, suppose i want to resize the original image by getting its width and height ratio. if i have an image of 1020 * 768 then how we resize it to half or something.

    • In that case you can use
      [code]
      // just give calculate the width and reduce it to half or
      // whatever your want for
      and set the value
      $magicianObj->resizeImage($smallwidth);
      [/code]

  11. i have been assigned a project of student information, where in, students is applying for certificate. he/she need to apply online by providing personal information plus marks scored in 10th ,12th and has to upload jpg file of 10th,12th, caste certificate, thumb impression. I need to store all information of student in one record including 4 images.. how do i do that. pls help me

    • Hi shekhar. in your case all you have to do is create a form with all the required fields and do both client side ( javascript) and Server side ( PHP ) validation, on the submit event store all the values to the database. For images make sure you use 4 file field with different name. check if the image file field has been image attached (server side), if so do process the image and store in the server and use that filename and store it in database. I hope this will do.

    • I will suggest you not to do this, but if you want to make add another text field ( for folder name) in the form and when user submits the form then create a folder with that name and upload the images in that folder. Also make sure you give write permission to that folder.

      • Can you please send me the code, actually am looking for upload each event photos in separate folder so that i can able to fetch particular event photos when user click on cover photo of that particular event, and can please suggest me how to make that DEMO 2 part to upload videos because i have 9 colleges and i want to upload photos and videos college wise with each event photos belongs particular college will be in different folder. Any help may appreciated.

        • Uploading images and Video are very much the same, all you have to make sure is the file upload limit and validate the file type. Coming back to your problem the possible solution cab be like this, You give a textfield where user will create a folder ( same like facebook albums concepts ) after the folder is created, upload the files under that.

  12. facing problem in this code

    Fatal error: Undefined class constant ‘MYSQL_ATTR_INIT_COMMAND’ in C:\wamp\www\New folder\save_create_image_thumnail_php_mysql (1)\index.php on line 23

    • If You are using PHP >= 5.3.6, so add charset to dsn and don’t use PDO::MYSQL_ATTR_INIT_COMMAND. Further I think you can only execute 1 query with PDO::MYSQL_ATTR_INIT_COMMAND. That might be the problem. Also try mysql:host=localhost;dbname=php_orm_test;charset=utf8

  13. Can you please post mysqli Procedural or mysql Procedural code of your post (Upload multiple images create thumbnails and save path to database with php and mysql) instead of PDO. Any help may appreciated.

  14. As you said i trayed Upload files by creating folder, but its not uploading photos to created folder instad it is uploading only a first image out of several images under uploads and displaying error “The path is not writable. Please check your permissions.” also its not creating tumbs under the created folder
    please try to correct this problem and please check your mail i sent a code attachment, Thank you

  15. While creating the folder am specifying (mkdir($dir, 0777)); its correct na ? Please once check the code that i sent you in mail. Thank you

  16. hi please am trying to choose one of my uploaded images as profile picture using php …please how do i go about this….your help will really be appreciated

  17. Thank you for your script…
    But, I am getting error like “Image not found.” when i uploading an image how to solve that.
    When i using re-size script this error came. But without using this re-size script image successfully updated. How can i solve this problem. Thank you.

  18. Sir, i want upload image and viewing image to their profile, again they upload means it will delete and store a latest image. now i done the code for uploading and viewing on their profile. but i upload another time means it will store one more time and viewing another time, please send example code. my email id is prakash.deva20@gmail.com

  19. Sir I cant see the download link to this your tutorial ” Upload multiple images create thumbnails and save path to database with php and MySQL “

  20. Valmiki Nayak on

    Rather than reinvent the wheel, I thought I’d Google for a code that came near enough to what I wanted. First half hour I found a whole load of crap created by people with no idea how to code. And then, I found this one – it is perfect. Saved me a lot of time. Thanks buddy, you’re great!

    Mmuuuaaahhhhhhhh

  21. Dear Mr. Khan,
    Very nice and detailed working script! Already learned a great deal about php and PDO sql in this single exercise! I am currently working on a similar project, and I want to know if you can give me some advice on it.

    Firstly, in my server there will be an “original” folder, and inside that folder, there will be a couple sub-folders called “apple”, “banana”, “orange”, and a folder which is called “combined”. After users upload an image, their image will first be saved and moved to the “original” folder, if that is successful, I will then apply image magician to it, and save the new modified image into one of the 3 sub-folders, also saving an copy of that into the “combined” folder. So in total there will be 3 copies of image created. The original image in “original” folder, one copy of the image in one of the 3 sub-folders, and one copy in the “combine” folder.

    Secondly, the reason for saving 3 copies of the same image is that on my website, there will be 4 tabs, “apple” , “banana”, “orange” and “mainpage”. Inside “apple” link, there will be all pictures exclusively about apple, and same goes to “banana” and “orange”, and in “mainpage”, there will be all the pictures from “apple” , “banana”, “orange” .

    Finally, there will be 4 tables in my SQL, being “mainpage” ,”apple” , “banana”, “orange” and the name of the files will be saved into the tables as well as the created time from the timestamp option, and will then be retrieve from the assigned webpage tabs.
    My questions are as following: Is my logic correct? How do I display the images according to the created time in time stamp, I am hoping to list it from new to old.

    Thank you so much again for the code, and any feedback would be very much appreciated!
    Best regards,
    Ray.W

    • Hi. Since you are saving the same copy of image in 3+1 folder it doesnt make sense to save the name of the in multiple tables. Here’s what you can do. Save the first image in “Original” folder say “abc.jpg” and then use the same name for when you save a copy for other images in other 4 folders. save the name of the file in the table. Now when you display those images in the tabs just change the folder path for each tabs like for orange “orange/abc.jpg” for apple “apple/abc.jpg”.

      Hope this helps you.

  22. actually im making an ordering online .. but i dont really understand the code.. and also i cant download the source code ... i already share it on my twitter ... please help me.. if you dont mind will you send me the source code in my email..
    sorry to say this.. but i`m badly needed that sample .. please thank you.

    • ohw.. gosh .. it was just my connection who has failed. thats why i cant download.. it`s done sir.. thank you 🙂 <3

  23. Sir.. if you dont mind sir.. will you be my mentor .. Im with my thesis right now and its an Ordering Online System with Inventory .. im looking forward with your responce sir.. <3

    • I am glad that you thought that I can be your mentor, but since I am busy with some projects these days I will not be able you devote time to you. Please mail me I will reply to your problem whenever I will find time.

  24. This looks like great solution for a project I am trying to complete. However, I just can’t get it to run. Would really like to download the source code but I can’t get the link to unlock. Tried sending some love via Facebook and google+ but nothing happens.

    Can I buy this from you?

  25. i need a concept of uploading a pofile image in my site and it will be display while the user is login to my site and also it is stored to the database.pls provided the source code for my problem.And send this to
    my email id “3dbalamurali@gmail.com”,

  26. Any way to include a title for each image? I have already created the table in my database and created the html input field, however I cannot seem to get it to insert with the way this is inserting the data into my database.

    • It should work the same way as you are inserting the image, make another column in database table “photo_title” and in the same way you are inserting the picture image name in database, same way insert the html input field title in that part.
      Note: the image text field will be an array as well and the array index must match with the file input index.

  27. Hi,

    I’m working on windows machine and I’m able to upload on first selected image.
    I’m getting “The path is not writable. Please check your permissions.” message.
    I’ve also tried setting my folder’s permission to Everyone through Properties–>Security.
    But unable to achieve the task..

    Please help me out.
    Thanks

    • You have to make changes in the php code because there is only check for image mime trype
      $valid_image_check = array(“image/gif”, “image/jpeg”, “image/jpg”, “image/png”, “image/bmp”);
      add mime type for pdf i guess it will be application/pdf

      • All my files have been uploaded if they are png , jpeg, bmp but when i upload pdf it says not a valid image. I changed the following code but it doesnot work. Any help will be apppreciated.
        $valid_image_check = array(“image/gif”, “image/jpeg”, “image/jpg”, “image/png”, “image/bmp”, “application/pdf”);

  28. Hi,
    I am uploading multiple images but it is generating thumbnail for 1 image only. I wanted to generate for all images. please help!

    Thank you.

Leave A Reply

CommentLuv badge

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.