Image - Upload Not Responding, No Access to $_Files

Image - Upload not responding, no access to $_FILES

You should use form method to POST instead of get.

<form action="edit_profile_parse.php" method="post" enctype="multipart/form-data" >

Image Uploading -- PHP File not accessed correctly

You need to make few changes in your uploadImg() function, such as:

  • Since you're encoding $_FILES using json_encode() function on the server side, change the dataType setting to json. dataType is the type of data you're expecting back from the server. This way you don't have to parse the response in the success() callback function, AJAX will take care of that.
  • Since you're sending images using FormData object, set the contentType to false.
  • You're getting the file name in the success() callback function in the wrong way, it should be like this:

    success: function(data){
    fileName=data.image.name;
    alert(fileName);
    }

So your uploadImg() function should be like this:

function uploadImg() {
var fileName = false;
var formData = new FormData();

fileName = $("#addImg")[0].files[0].name;
formData.append("image", $("#addImg")[0].files[0]);

$.ajax({
url: "upload.php", // Url to which the request is send
dataType: "json", // Type of data you're expecting back from server
type: "POST", // Type of request to be send, called as method
data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data){
fileName=data.image.name;
alert(fileName);
},
error: function(data){
console.log(data);
}
});
return fileName;
}

PHP upload not working, no error

In your code, I can see some issue.

//process image
if($_FILES['upload']['tmp_name']!=null){
$image="../assets/img/horses/horse".$id.".jpg";
if((bool)getimagesize($_FILES["upload"]["tmp_name"])){
$writeimage = fopen($imgPath, "w");
if(move_uploaded_file($_FILES["upload"]["tmp_name"], $imgPath)){
echo("<script>console.log('couldn't move img');</script>");
} else{
echo("<script>console.log('image uploaded');</script>");
}
fclose($writeimage);
} else{
echo(" <div class='alert alert-warning' id='notSaved' style='margin-top:20px;'>
Fehler: Die Datei die hochgeladen werden soll, scheint kein Bild zu sein.
</div>");
}
}

Please check where is $imgPath variable is defined? it should be $image.
No need to use fopen and fclose

So Your cose shouled be...

if($_FILES['upload']['tmp_name']!=null){
$image="../assets/img/horses/horse".$id.".jpg";
if((bool)getimagesize($_FILES["upload"]["tmp_name"])){
if(move_uploaded_file($_FILES["upload"]["tmp_name"], $image)){
echo("<script>console.log('couldn't move img');</script>");
} else{
echo("<script>console.log('image uploaded');</script>");
}
} else{
echo(" <div class='alert alert-warning' id='notSaved' style='margin-top:20px;'>
Fehler: Die Datei die hochgeladen werden soll, scheint kein Bild zu sein.
</div>");
}
}

$_files is empty in image upload in Phonegap/Cordova

Finally I fixed the issue, the fix was simple.

The url I had given was http://sample.com/upload_img.php. I just needed to add www in the url. So, working URL is http://www/sample.com/upload_img.php.
It fixed the issue.

XMLHttpRequest cannot load http://www.images.mysite.com/upload.php. No 'Access-Control-Allow-Origin' header is present on the requested resource

With your code as is, the Access-Control-Allow-Origin header should have been sent.

You may have a server error, or something else that prevents the headers from being sent (headers already sent? content flushed? wrong URL?).

Look at your console and browser's developer tools network tab for errors and look at the headers.

After you fix whatever it is that prevented the headers form being sent, consider the following:

  1. Dropzone sends a

    Access-Control-Request-Headers:accept, cache-control, content-type, x-requested-with

    header. You don't reply with cache-control accepted, so you will need to add it:

    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Cache-Control");
  2. You allow uploadMultiple, but only expect a single file.

  3. The paramName that you specify in your dropzone config is different from the one that you use on the server ("file" vs 'userfile').
  4. Your server does not return valid JSON, which the dropzone handler expects.

A contrived example that might get you started (don't use in production!):

<?php
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Cache-Control");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT');
header('content-type: application/json; charset=utf-8');

$uploaddir = '/post/';
$idx = "file";

$res = array("success" => true, "status" =>array());

if (isset($_FILES[$idx]) && is_array($_FILES[$idx])) {
foreach ($_FILES[$idx]["error"] as $key => $error) {
$status = array("success" => true);
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES[$idx]["tmp_name"][$key];
$name = $_FILES[$idx]["name"][$key];
if (move_uploaded_file($tmp_name, $uploaddir.$name)) {
$status["message"] = "ok";
} else {
$res["success"] = false;
$status["success"] = false;
$status["error"] = error_get_last();
$status["message"] = "internal server error";
}
} else {
$res["success"] = false;
$status["success"] = false;
$status["error"] = $error;
$status["message"] = "upload error";
}
$res["status"][] = $status;
}
}

echo(json_encode($res));

Edit:

Turns out there was a server issue. Apache's _mod_security_ had blocked the file uploads, but not normal POST or GET requests, and returned 406 Not Acceptable.

Issuing

$ curl http://example.com/upload.php -X POST \
-F "file[]=@/path/to/file" \
-v

resulted in

> POST /upload.php HTTP/1.1
> User-Agent: curl/7.35.0
> Host: images.sitename.com
> Accept: */*
> Content-Length: 719
> Expect: 100-continue
> Content-Type: multipart/form-data; boundary=------------------------755cbe89e26cbeb1
>
< HTTP/1.1 100 Continue
< HTTP/1.1 406 Not Acceptable
* Server nginx admin is not blacklisted
< Server: nginx admin
< Date: Mon, 19 Oct 2015 08:06:59 GMT
< Content-Type: text/html; charset=iso-8859-1
< Connection: keep-alive
< Content-Length: 380
* HTTP error before end of send, stop sending
<

(nginx serves as a reverse-proxy and Apache is behind it).
In such case, if you manage the server yourself, you can disable the problematic rule using .htaccess, or in other ways:

Method 1 - completely disable mode_security for the file (less recommended)

<IfModule mod_security2.c>
SecRuleEngine Off
</IfModule>

Method 2 - disable specific rule

$ cat /var/log/apache2/error.log | grep ModSecurity

(modify the path to point to your Apache error log), which should returns lines like this one:

[<date>] [error] [client <...>] ModSecurity: Access denied with code 406 (phase 2). <...> at REQUEST_FILENAME. [file <...>] [id "950004"] [msg <...>] <...>

Note the [id "950004"].

It can be disabled via:

<IfModule mod_security2.c>
SecRuleRemoveById 950004
</IfModule>

There are other, potentially better, ways of doing this.

Here is a good reference for mod_security configuration.

php upload script won't work

  1. Check to see if you can upload the file at all by executing this at the command line:

    chmod -R 777 /var/www/uploads/

  2. Then try to upload something. If that works, you know it was a permissions issue. But you don't want to leave the uploads folder at 777 permission (which give access to everyone)

  3. If it was a permissions issue, here is the way I like to do permissions:

    chown [your username]:www-data -R /var/www/uploads/

    chmod -R 775 /var/www/uploads/

This changes the group assignment of the folder to www-data, which is typically what apache runs as on a Ubuntu linux server.



Related Topics



Leave a reply



Submit