index.php →
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container box">
<br>
<br>
<br>
<h2 align="center">PHP upload an image file through URL.</h2>
<br>
<div class="form-group">
<label>Enter Image URL</label>
<input type="text" name="image_url" id="image_url" class="form-control">
</div>
<div class="form-group">
<input type="button" name="upload" id="upload" value="upload" class="btn btn-info">
</div>
<br>
</div>
<br>
<br>
<br>
<div id="result"></div>
<br>
<br>
<br>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#upload').click(function(){
var image_url = $('#image_url').val();
if (image_url === '') {
alert("Please enter image URL");
return false;
} else {
$('#upload').attr("disabled","disabled");
$.ajax({
url:"upload.php",
method:"POST",
data:{image_url:image_url},
dataType:"JSON",
beforeSend:function(){
$('#upload').val("Processing...")
},
success:function(data){
$('#image_url').val('');
$('#upload').val('Upload');
$('#image_url').attr('disabled',false);
$('#result').html(data.image);
alert(data.message);
}
})
}
})
})
</script>
</body>
</html>
and
upload.php:
<?php
//upload.php
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);
if (in_array($extension, $allowed_extension)) {
$image_data = file_get_contents($_POST["image_url"]);
$new_image_path = "upload/".rand().".".$extension;
file_put_contents($new_image_path, $image_data);
$message = 'Image Uploaded';
$image = '<img src="'.$new_image_path.'" class="img-responsive img-thumbnail">';
}else{
$message = 'Image not Found';
}
}else{
$message = 'Invalid URL';
}
$output = array(
'message' => $message,
'image' => $image
);
echo json_encode($output);
}
Issue: the actual file is not yet saving.