Now its almost 6 days and i am trying to fix image upload issue in cordova-php but not able to fix it. I tried multiple solutions from google/SO. But none of them is working for me.

I am using the below code as front end.

<div> <h3>Server URL for upload.php:</h3> <input id="serverUrl" type="text" value="http://sample.com/mobile_app/upload_img.php" /> </div> <script type="text/javascript" charset="utf-8">

    var deviceReady = false;
    /**
     * Take picture with camera
     */
    function takePicture() {
        navigator.camera.getPicture(
            function(uri) {
                var img = document.getElementById('camera_image');
                img.style.visibility = "visible";
                img.style.display = "block";
                img.src = uri;
                document.getElementById('camera_status').innerHTML = "Success";
            },
            function(e) {
                console.log("Error getting picture: " + e);
                document.getElementById('camera_status').innerHTML = "Error getting picture.";
            },
            { quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI});
    };
    /**
     * Select picture from library
     */
    function selectPicture() {
        navigator.camera.getPicture(
            function(uri) {
                var img = document.getElementById('camera_image');
                img.style.visibility = "visible";
                img.style.display = "block";
                img.src = uri;
                document.getElementById('camera_status').innerHTML = "Success";
            },
            function(e) {
                console.log("Error getting picture: " + e);
                document.getElementById('camera_status').innerHTML = "Error getting picture.";
            },
            { quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
    };

    /**
     * Upload current picture
     */
    function uploadPicture() {

        // Get URI of picture to upload
        var img = document.getElementById('camera_image');
        var imageURI = img.src;
        if (!imageURI || (img.style.display == "none")) {
            document.getElementById('camera_status').innerHTML = "Take picture or select picture from library first.";
            return;
        }

        // Verify server has been entered
        server = document.getElementById('serverUrl').value;
        if (server) {

            // Specify transfer options
            var options = new FileUploadOptions();
            options.fileKey="fileUpload";
            options.httpMethod="POST";
            options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
            options.mimeType="image/jpeg";
            options.chunkedMode = false;
  //          var op;
//op = new FileUploadOptions();

            options.headers = {
               Connection: "close"
            };
            // Transfer picture to server
            var ft = new FileTransfer();
            ft.upload(imageURI, server, function(r) {
                document.getElementById('camera_status').innerHTML = "Upload successful: "+r.response+" bytes uploaded."; alert(r.response);            
            }, function(error) {
                alert(r.response);
                document.getElementById('camera_status').innerHTML = "Upload failed: Code = "+error.code;               
            }, options);
        }
    }
    /**
     * View pictures uploaded to the server
     */
    function viewUploadedPictures() {

        // Get server URL
        server = document.getElementById('serverUrl').value;
        if (server) {

            // Get HTML that lists all pictures on server using XHR 
            var xmlhttp = new XMLHttpRequest();
            // Callback function when XMLHttpRequest is ready
            xmlhttp.onreadystatechange=function(){
                if(xmlhttp.readyState === 4){
                    // HTML is returned, which has pictures to display
                    if (xmlhttp.status === 200) {
                        document.getElementById('server_images').innerHTML = xmlhttp.responseText;
                    }
                    // If error
                    else {
                        document.getElementById('server_images').innerHTML = "Error retrieving pictures from server.";
                    }
                }
            };
            xmlhttp.open("GET", server , true);
            xmlhttp.send();         
        }   
    }

    /**
     * Function called when page has finished loading.
     */
    function init() {
        document.addEventListener("deviceready", function() {deviceReady = true;}, false);
        window.setTimeout(function() {
            if (!deviceReady) {
                alert("Error: PhoneGap did not initialize.  Demo will not run correctly.");
            }
        },2000);
    }
    </script>

And here comes the backend(php) code.

<?php
header("Access-Control-Allow-Origin: *");
//header("Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS");
//header("content-type: application/json; charset=utf-8");
// Directory where uploaded images are saved
$dirname = "./user_img";//"mobile_app/user_img"; 
// If uploading file
//echo $_FILES;
 print_r($_FILES);
if ($_FILES) {
    print_r($_FILES);
    mkdir ($dirname, 0777, true); 
    move_uploaded_file($_FILES["fileUpload"]["tmp_name"],WWW_ROOT.$dirname."/".$_FILES["file"]["name"]);
}
// If retrieving an image
else if (isset($_GET['image'])) {
    $file = $dirname."/".$_GET['image'];
    // Specify as jpeg
    header('Content-type: image/jpeg');

    // Resize image for mobile
    list($width, $height) = getimagesize($file); 
    $newWidth = 120.0; 
    $size = $newWidth / $width;
    $newHeight = $height * $size; 
    $resizedImage = imagecreatetruecolor($newWidth, $newHeight); 
    $image = imagecreatefromjpeg($file); 
    imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); 
    imagejpeg($resizedImage, null, 80); 
}
// If displaying images
else {
    $baseURI = "http://".$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
    $images = scandir($dirname);
    $ignore = Array(".", "..");
    if ($images) {
        foreach($images as $curimg){ 
            if (!in_array($curimg, $ignore)) {
                echo "Image: ".$curimg."<br>";
                echo "<img src='".$baseURI."?image=".$curimg."&rnd=".uniqid()."'><br>"; 
            }
        }
    }
    else {
        echo "No images on server";
    }
}
?>

I found $_FILES is empty i am getting Array() only. I dont know what is wrong with the code because same code i have seen on multiple question and examples.

I use two webserver but same result.

user_img folder have 777 access.

Hi,

have you tried the web developer console integrated in your browser (Mozilla Firefox, Chrome, Chromium) to see if the javascript code is raising some errors?

Can you provide a live example?

Besides, test your script with a simple HTML form, you will see there are at least few issues:

Issue 1

move_uploaded_file($_FILES["fileUpload"]["tmp_name"],WWW_ROOT.$dirname."/".$_FILES["file"]["name"]);

In the first parameter you refer to fileUpload, in the second to file, so it's like if your are trying to get the values from two different arrays. Fix them to match fileUpload as defined in the javascript.

Issue 2

This involves multiple lines:

/// client side
<input id="serverUrl" type="text" value="http://sample.com/mobile_app/upload_img.php" />

/// server side
$dirname = "./user_img";
mkdir ($dirname, 0777, true); 
move_uploaded_file($_FILES["fileUpload"]["tmp_name"],WWW_ROOT.$dirname."/".$_FILES["file"]["name"]);

If you define $dirname with a relative path, then the upload_img.php script will create the directory inside his own path, so you end with:

/mobile_app/user_img/

The move_uploaded_file() function, instead, points to the document root, and you get something like this:

/./user_img/

The mover function will not find the path, so it will fail to complete the task. However, the $_FILES array gets populated before these things happen, so it may not affect your current issue.

Issue 3

The mkdir() will raise a warning as soon you run the script successfully for the second time, because the path already exists. Use file_exists() to verify if it exists, or just create it manually and remove mkdir().

thanks for your answer. I am fixing all the issues mentioned by you. I am testing it in mobile. $_files is empty. i am not sure why it is empty. Any comment on this.

fixed all the things as advised but i am still getting array(0) .