• PHP image upload script with categories

    WinMan Member

    I’m trying to create an image hosting site where you can select a file from your device and upload it to your server, but I want to make a dropdown list with categories to choose from where the image will be saved. lets say im uploading my files to /uploads but within my uploads folder I want folders according to the category chosen by the uploader. for instance if someone upload an image and select category I want the file to be saved into /uploads/category 1. can someone please help me code such a basic script please

  • MarkGrillo Member

    Well, this is quite a basic thing. I’ll try to describe the procedure here to give you a head start.

    In the HTML’s select tag put the categories you want. Each select option should have the value of the folder you want to put the image in. Once you have that in your form, the form will be submitted with the value of of the select/dropdown. On the file upload handler (assuming it is in the same page), grab the value from the select option and use it on move_uploaded_file to put the image in that certain selected directory.

    Here’s an example:

    
    
    
    
    
       My website
    
    
       
    Select a file:


    Category:


  • Abhey Member

    Thank you this is what I was looking for but I want to save the images not just in the upload folder I want to make a few categories (folders) inside the upload folder example if I select pets I want to upload it to /uploads/pets and when I select food I want to store it in uploads/food/.

  • SapnaVishwas Member

    Did you try his example? Check the following line:

    $uploads_path = './myuploadpath/' . $category . $_FILES['file']['name'];
    

    In your case, change ‘myuploadpath’ to ‘uploads. Category is then appended, but he did forget the trailing slash. Then the file name is appended. So just change the line to this:

    $uploads_path = './uploads/' . $category . '/' . $_FILES['file']['name'];
    

    A few things to note: you need to make sure that the folder for the category exists before you upload to that folder or you’ll get errors. Also, you may want to ensure that the category is valid before just uploading it. Maybe create an array of valid categories and confirm that the chosen one exists. The reason is that some people may send false data and cause issues.

    Finally, I’d suggest going about this with a database rather than simply uploading to different folders.

Viewing 3 reply threads
  • You must be logged in to reply to this topic.