so here's the problem. I am getting some strange behavior from my php script that I use to upload images without refreshing a site. Bellow there are 2 scripts, the jquery / ajax and the php. And actually it works great but i found an error that occurs. This is what happens.
I choose an image that is less than 5 MB - image uploads - correct I choose an image of 7 MB - i get an error "image is to big" - correct I choose an image that is less than 5 MB - image uploads - correct I choose an image (the same one) of 7 MB - i get "invalid argument supplied for foreach" and "not an image"
This happens when i choose images exactly in that order. I tried choosing images less than 5mb an every time it's ok. I don't know what's going on. Have in mind that I am a begginer in PHP so the code probably isn't "as should be" and I'm opened for suggestions on what to improve or do differently
html
<form class="uploadImageForm" method="post" enctype="multipart/form-data">
<input type="file" name="userImage" id="images">
<input type="submit" name="submitImage">
</form>
Jquery / ajax code
if (window.FormData) {
formdata = new FormData();
$('#images').on("change", function(evt) {
var reader, file;
file = this.files[0];
if (window.FileReader) {
reader = new FileReader();
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("userImage[]", file);
}
if (formdata) {
$.ajax({
url: "includes/upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
var result = res;
if(result == "not an image"){
console.log("error - this is not an image");
}else if(result == "image too big"){
console.log("error - image to big")
}else{
console.log("result", result);
$('img.userImage').attr("src", result);
}
}
});
}
});
}else{
$('input[name="userImage"]').on("change", function(){
$('input[name="submitImage"]').trigger("click");
});
}
PHP CODE
<?php
session_start();
$sessionId = session_id();
foreach ($_FILES["userImage"]["name"] as $key => $value) {
$name = $_FILES["userImage"]["name"][$key];
$size = $_FILES["userImage"]["size"][$key];
$tmpName = $_FILES["userImage"]["tmp_name"][$key];
$type = explode("/", $_FILES["userImage"]["type"][$key]);
$type = $type[1];
}
$possibleTypes = array("jpeg", "jpg", "gif", "png", "JPEG", "JPG");
$maxSize = 5000000;
if($size > $maxSize){
echo "image too big";
die();
}
else if(!in_array($type, $possibleTypes)){
echo "not an image, this type is: " .$type;
die();
}
else{
$directory = ("../user_img/".$sessionId);
if(!file_exists($directory)){
mkdir($directory, 0777);
}
else{
foreach(glob($directory ."/*.*") as $file) {
unlink($file);
}
}
move_uploaded_file( $tmpName, $directory."/" . $sessionId."_img.".$type);
$img_src = "user_img/".$sessionId."/".$sessionId."_img.".$type;
echo $img_src;
}
?>