I have downloaded the code. Checking the return from file_put_contents() gives “Warning: file_put_contents(/sitepoint/codeisp/upload/374365915.png): failed to open stream: No such file or directory in C:\wamp64\www\sitepoint\codeisp\upload.php on line 32”.
As soon as I change the line to use getcwd() for the directory it works just fine. In my case the “upload” directory is beneath the directory that my code is running in, so it works. I suspect there may be a better way to get the absolute directory.
But, just checking the return from the function that is falling over showed me what the problem is. And, of course, the OP needs to add that functionality into their code, rather than just call file_put_contents() and then immediately output “Image Uploaded”, which it may not have been.
In actual fact, while I do echo $put; to see the return, by adding the error() function that showed me the standard PHP error screen.
All I’ve done here is add various echo statements, followed by exit(). I then use Chrome to run the code, enable the developer tools and look at the console, which shows me either the raw response (the text I echoed) or the html for an error message if I have one.
<?php
//upload.php
/*
echo "In PHP Code";
var_dump($_POST);
exit();
*/
if (isset($_POST["image_url"])) {
$message = '';
$image = '';
if (filter_var($_POST['image_url'], FILTER_VALIDATE_URL)) {
$allowed_extension = array("jpg","png","jpeg","gif");
$url_array = explode("/", $_POST["image_url"]);
$image_name = end($url_array);
$image_array = explode(".", $image_name);
$extension = end($image_array);
// echo var_dump($extension) . "<br>";
if (in_array($extension, $allowed_extension)) {
$image_data = file_get_contents($_POST["image_url"]);
/*if ($image_data == false) {
echo "couldn't get image";
exit;
} else {
echo "Got image " ;
exit();
}*/
$new_image_path = getcwd()."/upload/".rand().".".$extension;
$put = file_put_contents($new_image_path, $image_data);
//echo $put; Did we get 'false'? Code should check this before saying image uploaded
$message = 'Image Uploaded';
$image = '<img src="'.$new_image_path.'" class="img-responsive img-thumbnail">';
//echo var_dump($image) . "<br>";
}else{
$message = 'Image not Found';
}
}else{
$message = 'Invalid URL';
}
$output = array(
'message' => $message,
'image' => $image
);
echo json_encode($output);
}
I’ve also added an “error” function in the Ajax call, because this seems to be required:
$('#upload').attr("disabled","disabled");
$.ajax({
url:"upload.php",
method:"POST",
data:{image_url:image_url},
dataType:"JSON",
beforeSend:function(){
$('#upload').val("Upload in Process...")
},
success:function(data){
console.log(data);
$('#image_url').val('');
$('#upload').val('Upload');
$('#image_url').attr('disabled',false);
$('#result').html(data.image);
alert(data.message);
},
error: function(data) {
console.log("error");
console.log(data);
}