1

I am trying to upload and save an image using PHP scripting, but the image is not getting saved in the specified folder. Please help

here's my code:

  <?php
  if(isset($_POST['button'])){
  $name= "product_name.jpg";
  move_uploaded_file($_FILES["fileField"]["tmp_name"],"student_images/$name");
  header("location: tryupload.php");
  }
  ?>
  <html>
  <body>
  <form action="tryupload.php" enctype="multiple/form-data" name="myForm" id="myform" method="post">
  <table>
  <tr>
    <td align="right">Product Image</td>
    <td><label>
      <input type="file" name="fileField" id="fileField" />
    </label></td>
  </tr>      
  <tr>
    <td>&nbsp;</td>
    <td><label>
      <input type="submit" name="button" id="button"/>
    </label></td>
  </tr></table>
  </form>
  </body>
  </html>

3 Answers3

6

This part of your code enctype="multiple/form-data" is incorrect.

It needs to read as enctype="multipart/form-data".

Also make sure that the folder you intend on uploading to, has proper permissions to write to.

Uploading security-related links:


Add error reporting to the top of your file(s) which will help find errors.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Sidenote: Error reporting should only be done in staging, and never production.

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
1

To upload multuple files you can have.

Multiupload.php

<? session_start()?>
<!DOCTYPE html>

<html>

    <head>

    <title>Blank</title>

    <!-------Including jQuery from google------>

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

        <script src="js/script.js"></script>



        <!-------Including CSS File------>

        <link rel="stylesheet" type="text/css" href="css/style.css">

    <link rel="stylesheet" type="text/css" href="css/main.css">

    <body>
            <div id="formdiv">
                    <h1 class="uploadH2">Upload Your Artwork</h1>
                <form enctype="multipart/form-data" action="" method="post">

                  Take a photo, upload your artwork, or choose an image from Facebook or Instagram



            <label for="file">

                    <div id="image" style="margin-top:5%;">

                    <img src="img/camera.png">    

                    </div>

                    </label>



                    <div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>


                    <input type="button" class="add_more" id="add_more" value="Add More Files"/>

                    <input type="submit" value="Upload File" name="submit" id="img_upload" class="show-page-loading-msg" data-theme="b" data-textonly="false" data-textvisible="false" data-msgtext="" data-icon="arrow-r" data-iconpos="right"/>

                </form>

                <br/>

                <br/>

                <!-------Including PHP Script here------>

                <?php include "uploadScript.php"; ?>

        </div>

    </body>

</html>

uploadScript.php

<?php
$dir_id = session_id(md5(uniqid()));
session_start($dir_id);
$path = "uploads/";
$dir = $path.$dir_id;
$path = $path.$dir_id."/";
if (file_exists($dir)) {
    system('/bin/rm -rf ' . escapeshellarg($dir));
} else {
mkdir($path);
chmod($path, 0722);  
}
$_SESSION["id"] = $dir_id;
$_SESSION["directory"] = "/" . $dir;
$_SESSION["path_name"] = $path;
?>

<?
if (isset($_POST['submit'])) {
    $j = 0; //Variable for indexing uploaded image
    $target_path = $path;

    for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array

        $validextensions = array("jpeg", "jpg", "png", "gif");  //Extensions which are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) 
        $file_extension = end($ext); //store extensions in the variable

        $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
        $j = $j + 1;//increment the number of uploaded images according to the files in array       

      if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
                && in_array($file_extension, $validextensions)) {
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
                echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
            } else {//if file was not moved.
                echo $j. ').<span id="error">Only JPG, JPEG, PNG and GIF files types allowed.</span><br/><br/>';
            }     
        } else {//if file size and file type was incorrect.
            echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
        }
    }
}
?>

This script will only accept, jpg, png, gif and jpeg. You can't upload or execute anything inside the directory unless you are owner and you can't have a file size bigger than 10KB.

script.js

var abc = 0; //Declaring and defining global increement variable

$(document).ready(function() {

//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
    $('#add_more').click(function() {
        $(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
                $("<input/>", {name: 'file[]', type: 'file', id: 'file'}),        
                $("<br/><br/>")
                ));
    });

//following function will executes on change event of file input to select different file   
$('body').on('change', '#file', function(){
            if (this.files && this.files[0]) {
                 abc += 1; //increementing global variable by 1

                var z = abc - 1;
                var x = $(this).parent().find('#previewimg' + z).remove();
                $(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src='' style='width:40%; height:40%;'/></div>");

                var reader = new FileReader();
                reader.onload = imageIsLoaded;
                reader.readAsDataURL(this.files[0]);

                $(this).hide();
                $("#abcd"+ abc).append($("<img/>", {id: 'delete', src: 'x.png', alt: 'delete'}).click(function() {
                $(this).parent().parent().remove();
                }));
            }
        });

//To preview image     
    function imageIsLoaded(e) {
        $('#previewimg' + abc).attr('src', e.target.result);
    };

    $('#upload').click(function(e) {
        var name = $(":file").val();
        if (!name)
        {
            alert("First Image Must Be Selected");
            e.preventDefault();
        }

        else {}

    });
});

This will upload multiple files, preview the image on the same page as the upload form, this will create a directory inside /uploads on the server with a directory matching the users session_id(). If the directory exists, the directory will be deleted, if it doesn't the directory will be created. The files will then be uploaded to that directory on the server.

BradleyIW
  • 1,338
  • 2
  • 20
  • 37
0

You have incorrect enctype for the form. Instead of "multiple/form-data" use "multipart/form-data".

user4035
  • 22,508
  • 11
  • 59
  • 94