0

I am trying to upload an image using php and ajax. I have tried coding but i am not sure that how can i pass ectype data of the file which i am going to upload to AJAX and then pass it in PHP where i am uploading the file and saving the path of the file into the database. Here is my html and AJAX code.

<form class="form-horizontal" role="form" onsubmit="uploadimage(this.value)" method="post" id= "sample" enctype="multipart/form-data">
            <input type="hidden" name="sid" value="<?php echo $sid; ?>">
            <input type="hidden" name="site" value="<?php echo $site; ?>">
            <input type="hidden" name="img_pos" value="img_gal1">
            <div class="form-group">
                <!--<label class="control-label col-lg-2">Upload Gallery</label><br/>-->
                <div class="col-lg-10">
                    <input type="file" name="fileToUpload" placeholder="Upload Gallery">
                    <!--<input type="Submit" value="Upload Image" name="submit">-->
                </div>
            </div>
            <div class="form-group"> 
                <div class="col-sm-5">
                    <input type="submit" class="btn btn-primary form-control">
                </div>
            </div>
        </form>

and ajax code is:

<script>
function uploadimage(str) {
  if (str=="") {
    document.getElementById("txtHint").innerHTML="";
    return;
  } 
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { //   code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","gallery_upload.php?q="+str,true);
  xmlhttp.send();
}

I just copied the code from w3schools. I am not sure what the ajax code should be regarding the passing of a 2 dimensional file array so I didn't edited it. The php code looks like this for reference.

<?php

$img_pos= $_REQUEST["img_pos"];
$folder= "img/$sid/";
if (!file_exists($folder)) 
{
     mkdir($folder, 0777, true);
     $target_dir = $folder;
}
else
{
$target_dir = $folder;
}

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$n_filename= $target_dir.$img_pos.".".$imageFileType;
rename($target_file, $n_filename);
$uploadOk = 1;
//$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        //echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        //echo "File is not an image.";
        $uploadOk = 0;
    }
}
 /*Check if file already exists
if (file_exists($target_file)) {
    header("Location: admin/pages/profile.php?response= Sorry, file already exists. PLease change the name and try again!&sid=".$sid);
    //echo "Sorry, file already exists.";
    $uploadOk = 0;
}*/
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    header("Location: admin/pages/profile.php?response= Sorry, your file is too large.&sid=".$sid);
    //echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    header("Location: admin/pages/profile.php?response= Sorry, only JPG, JPEG, PNG & GIF files are allowed.&sid=".$sid);
    //echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    header("Location: admin/pages/profile.php?response= Sorry, your file was not uploaded.&sid=".$sid);
    //echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";

        $query="Update content SET ".$img_pos."='".$_FILES["fileToUpload"]["name"]."' where Sid='".$sid."' and site='".$site."'";

        $result= mysqli_query($con,$query) or die(mysqli_error($con));
        if($result)
        {
            header("Location: admin/pages/profile.php?response= Great! Your Profile has been updated&sid=".$sid);
            //echo "done";
            //echo $query;
        }

        } else {
            header("Location: admin/pages/profile.php?response= Sorry, there was an error uploading your file.&sid=".$sid);
            //echo "Sorry, there was an error uploading your file.";
        }
    }
?>

I want to upload 5 images from page. So I have 5 different forms. and I was thinking to make only one php code for uploading the images by using AJAX. so basically what I want is that I transfer the file type data to AJAX and then AJAX works with php and uploads the image to the folder and updates the path in database. So I basically want to know that what would be the AJAX code to send the data in php.

halfer
  • 19,824
  • 17
  • 99
  • 186
Nagesh Katna
  • 679
  • 2
  • 7
  • 27
  • Hi, can you see this post http://stackoverflow.com/questions/19447435/ajax-upload-image and comment if help. I have a code to read a image as data/image64 and send with ajax. In the server, decode and put in a file. – Maxi Schvindt Feb 16 '16 at 02:41
  • HI, Cuchu i read your question. it feels like it can solve my problem a bit but the problem is the update i have written in my question that i want to upload 5 images. if you have any example for that then that would be great. otherwise i have to follow your question's answers. like putting 5 different ajax codes for all the 5 image uploading forms. – Nagesh Katna Feb 16 '16 at 07:50

2 Answers2

0

You're checking for if(isset($_POST["submit"])) { but there is no element with name="submit"

Edit: I didn't notice you're actually having a GET request instead of a POST request: xmlhttp.open("POST","gallery_upload.php?q="+str,true);

dex
  • 137
  • 5
  • That isset() function is just taking the response . you can ignore that. Its just a usless code. for current i cant figure out how can i send multipart data of $_FILES to ajax and read it in php – Nagesh Katna Feb 16 '16 at 03:15
0

The form's enctype is not the same as the file's media-type (also referred to as its mime type), which I think is what you are actually wanting. You can't (and don't want to) rely on the media-type being passed in from the browser/client, but should instead be checking for the file's media type server-side to confirm that it is a valid (expected) type. You could do this a few different ways, but here's how using mime_content_type. Example:

$upload_file_mime_type = mime_content_type($_FILES["fileToUpload"]["tmp_name"]);

If the uploaded file is a legit image file of type PNG, the mime-type will be image/png. If you are only wanting to verify that the uploaded file is an image file, you could use explode to split the string value for $upload_file_mime_type into an array. Example:

$upload_file_mime_type_parts = explode("/", $upload_file_mime_type);

if ( $upload_file_mime_type_parts[0] != "image" ) {

     echo "File must be valid image!";

}
Anthony
  • 36,459
  • 25
  • 97
  • 163
  • I actually want to upload 5 images from page. so i have 5 different forms. and i was thinking to make only one php code for uploading the images by using ajax. so basically what i want is that i transfer the file type data to ajax and then ajax works with php and uploads the image to the folder and updates the path in database. So i basically want to know that what would be the ajax code to send the data in php. – Nagesh Katna Feb 16 '16 at 07:27