How to check if an image exists on a remote URL?

27

In order to be able to administer a website from a server other than the one on which the website is hosted, the problem of dealing with remote images has arisen.

Common problems:

  • Verify that the image actually exists before creating links to it;
  • When replacing a particular image, check if the previous image exists to be deleted;
  • Verify that the image uploaded to the server does not have the same name as an existing image.

Typically, this type of operation is done with is_file() , but since it does not support URLs, only absolute or relative paths of the server itself, it is therefore unfeasible for this scenario.

Question

Using PHP, how can I check if a remote image exists?

    
asked by anonymous 10.01.2014 / 00:17

4 answers

15

My approach to dealing with this issue is to use the Client URL Library (cURL) (English) to collect HTTP Status code (English) and with the whether or not the image exists at the given URL:

/**
 * URL Exists
 *
 * Verifica se o caminho URL existe.
 * Isso é útil para verificar se um arquivo de imagem num 
 * servidor remoto antes de definir um link para o mesmo.
 *
 * @param string $url           O URL a verificar.
 *
 * @return boolean
 */
function url_exists($url) {

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return ($code == 200); // verifica se recebe "status OK"
}

Usage example:

$url = 'http://www.example.com/minha_imagem.jpg';
if (url_exists($url))
    // encontrei :)
else
    // não encontrei :(

Note: This solution depends on functions added from PHP 4.0.2.

    
19.03.2014 / 14:53
16

For this you use file_exists , in addition to remote URL it works with absolute or relative paths of the server itself, like this:

    if(file_exists('http://www.dominio.com/imagens/minha-imagem.jpg')){
       //seu código...
    }

Other useful functions are:

10.01.2014 / 00:36
7

I've set up the function below that can check both images and web pages, or any other content that comes from the web. I get the header response from the request and compare the codes. If it is 200 or 302 exists; if it is 500 has an internal error on the server; if it is 404 does not exist.

It is worth remembering that the one who will make the request is your web server, and the same should have access to the internet.

<?php
function validarext($url)
{
    $validar = get_headers($url);
    $validar = explode(" ",$validar[0]);
    $validar = $validar[1];
    if($validar == "302" || $validar == "200")
        return true;
    else
        return false;
}

if(validarext("http://www.urldaimagem.com.br/imagem.jpg")){
    //Imagem existe
    echo "Sim";
}
else
{
    //Imagem não existe...
    echo "Não";
}
?>
    
03.02.2014 / 14:59
0

In the system that implements the fileUpload you do a routine that will search if a certain photo already exists. This function will be useful for all processes:

1st: As said, check if the photo exists before creating the links to it, how to do is using the implementation of file_exists () ;. It is recommended that you use a database to store the name of your file so you can request it and check with the absolute path of your server.

2nd: When you verify that the image exists, and then you are told to execute the replacement process, you will delete the existing image using the unlink () function; and then retrieve the new ~ temp image and rename it to the name that is in the database.

3rd: Make an implementation of a hash pattern to append to your files, every time someone uploads a file, get the name of the file and concatenate it with the following statement uniquid (rand (6, 8));

<?php

$nome = $_FILE['image']['name'];
$novoNome = $nome . uniquid( rand(6, 8) );
    
29.01.2014 / 04:23