Check if image exists on remote URL with or without http/https
Instead of checking the accessibility and the image size in 2 steps, you could combine it in one:
Validator::extend('valid_img_url', function ($attribute, $value, $parameters, $validator) {
$ch = curl_init($value);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, TRUE);
$data = curl_exec($ch);
$size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
$mime = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
curl_close($ch);
return $httpCode >= 200 && $httpCode <= 400 && $size > 0 && substr($mime, 0, 5) == 'image');
}
To use the power of getimageSize
you could add this piece of code:
Validator::extend('valid_img_url', function ($attribute, $value, $parameters, $validator) {
$handle = curl_init($value);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode >= 200 && $httpCode <= 400) {
if (!preg_match("~^(?:f|ht)tps?://~i", $value)) {
$value = "http://" . $value;
}
return getimagesize($value) !== false;
}
});
It will add the missing http
if there is no one. But remember if the url is only accessible via https without any redirect it can throw an error.
How to check if Image exists on server using URL
Use fopen function
if (@fopen($resultUF['destination'], "r")) {
echo "File Exist";
} else {
echo "File Not exist";
}
Check if Image Exists on Remote Site ASP.NET VB
Assuming that your database column Name
contains only the short filename (i.e. no directory path information or folder names) then you can do this:
String nameFromDatabase = (String)dsDriver.Tables("Driver").Rows[0]["Name"] + ".png";
String appRootRelativeHttpResourcePath = "~/Images/DriversNew/" + nameFromDatabase;
String localFileSystemPath = Server.MapPath( appRootRelativeHttpResourcePath );
if( File.Exists( localFileSystemPath ) ) {
imgDriver.ImageUrl = appRootRelativeHttpResourcePath; // you can specify app-root-relative URLs ("~/...") here
}
else {
imgDriver.ImageUrl = "~/Images/DriversNew/Blank.png";
}
Check if image exists on server using JavaScript?
You could use something like:
function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
}
Obviously you could use jQuery/similar to perform your HTTP request.
$.get(image_url)
.done(function() {
// Do something now you know the image exists.
}).fail(function() {
// Image doesn't exist - do something else.
})
Fast way to check if image on remote URL exists in python
Your requests are blocking and synchronous which is why it is taking a bit of time. In simple terms, it means that the second request doesn't start, until the first one finishes.
Think of it like one conveyer belt with a bunch of boxes and you have one worker to process each box.
The worker can only process one box at a time; and he has to wait for the processing to be done before he can start processing another box (in other words, he cannot take a box from the belt, drop it somewhere to be processed, come back and pick another one).
To reduce the time it takes to processes boxes, you can:
- Reduce the time it takes to process each box.
- Make it so that multiple boxes can be processed at the same time (in other words, the worker doesn't have to wait).
- Increase the number of belts and workers and then divide the boxes between belts.
We really can't do #1 because this delay is from the network (you could reduce the timeout period, but this is not recommended).
Instead what we want to do is #2 - since the processing of one box is independent, we don't need to wait for one box to finish to start processing the next.
So we want to do the following:
- Quickly send multiple requests to a server for URLs at the same time.
- Wait for each of them to finish (independent of each other).
- Collect the results.
There are multiples ways to do this which are listed in the documentation for requests; here is an example using grequests
:
import grequests
# Create a map between url and the item
url_to_item = {item.item_low_url: item for item in items}
# Create a request queue, but don't send them
rq = (grequests.head(url) for url in url_to_item.keys())
# Send requests simultaneously, and collect the results,
# and filter those that are valid
# Each item returned in the Response object, which has a request
# property that is the original request to which this is a response;
# we use that to filter out the item objects
results = [url_to_item[i.request.url]
for i in filter(lambda x: x.status_code == 200,
grequests.map(rq)))]
Check if URL exist, and if it's an image
You can never be 100% sure but i would at least check for:
- Content Headers rather than extension (works even if the image is being served dynamically with the extension of ".php" or anything else)
- Check the content length header to make sure it's greater than zero and the server is not sending me a soft 404
Finally check if the final image is a redirect. (incase of 404 page or a default image file)
$content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$content_length = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
$content_redirect = curl_getinfo($ch, CURLINFO_REDIRECT_COUNT );
$imageTypes = array('image/png','image/jpeg','image/gif');
if(in_array($content_type,$imageTypes) && $content_redirect == 0 && $content_length >0){
// is a vald image
}
to stop curl from downloading the whole image file set CURLOPT_NOBODY
to true.
curl_setopt($ch, CURLOPT_NOBODY, true);
Is there a way to check whether a remote image is exist? PHP
I use this method to ping distant files:
/**
* Use HTTP GET to ping an url
*
* /!\ Warning, the return value is always true, you must use === to test the response type too.
*
* @param string $url
* @return boolean true or the error message
*/
public static function pingDistantFile($url)
{
$options = array(
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_URL => $url,
CURLOPT_FAILONERROR => true, // HTTP code > 400 will throw curl error
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$return = curl_exec($ch);
if ($return === false)
{
return curl_error($ch);
}
else
{
return true;
}
}
You can also use the HEAD
method but maybe your CDN as disabled it.
Related Topics
Append Data to a .Json File With PHP
Show Image Using File_Get_Contents
How to Access MySQL Result Set Data With a Foreach Loop
In PHP, What Does "≪≪≪" Represent
How to Generate a Screenshot of a Webpage Using a Server-Side Script
Serializing and Submitting a Form With Jquery and PHP
Why I'M Getting 500 Error When Using File_Get_Contents(), But Works in a Browser
How to Execute PHP That Is Stored in a MySQL Database
A Problem Occurred Somewhere in the Ssl/Tls Handshake
PHP Header Redirect Not Working
Yii2 Htaccess - How to Hide Frontend/Web and Backend/Web Completely
PHP: Sort an Array by the Length of Its Values
How to Import a .SQL File in MySQL Database Using PHP
How to Detect a Create, Update, Delete Query Is Successful in Codeigniter