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

Asked

Viewed 15,751 times

27

In order to have the administration of a website to be performed from a server other than the one where the website is hosted, the problem of dealing with remote images has arisen.

Common problems:

  • Check if the image actually exists before linking to it;
  • When replacing a particular image, check if the previous one exists to be deleted;
  • Check that the image uploaded to the server is not named after an existing image.

Normally, this type of operations is carried out with the is_file(), but as it does not support URL, only absolute or relative paths of the server itself, it is thus impossible for this scenario.

Question

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

  • 1

    Check if there is an image, or if there is a file? This changes the answer a lot. In the file question, it was answered, in the same picture question, "came close". (there may be a file in the place that is not image)

4 answers

18

For this you use the file_exists, apart from remote URL it works with absolute or relative paths of the server itself, in this way:

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

other useful functions are:

  • is_readable - It says if the file can be read.
  • file - Reads the entire file to an array
  • file_get_contents - Reads the entire file to a string (extremely useful)
  • fread - Binary-safe file reading
  • readfile - Reads and displays the contents of a file
  • 6

    Just remembering that the results of the function file_exists() are curly. Don’t forget to check the documentation on PHP.net.

  • 1

    A solution for URL caching: 'http://www.dominio.com/imagens/minha-imagem.jpg?'. (time() * Rand(),0,''''),0,10)

  • I have already had the opportunity to return to this subject, indeed by the tests carried out in PHP 5.3.22, the file_exists always return FALSE even being absolutely sure that the image exists and is accessible via URL.

  • 1

    The problem is that depending on the size of the image, it will be beautiful to use file_get_contents that returns all content for a string :p

17


My approach to dealing with this issue is to use Client URL Library (Curl) (English) to collect the HTTP Status code (English) and with the same knowing whether or not the image exists in 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"
}

Example of use:

$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.

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 answer from header request and compare codes. If 200 or 302 exists; if so 500 has internal error on the server; if 404 there is no.

It is worth remembering that who will make the request is your web server, and the same should have access to 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";
}
?>

0

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

1º: As said, check if the photo exists before creating the links to it, how to do it 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.

2º: When verified that the image exists, and soon was informed the execution of the substitution process, you will delete the existing image using the unlink() function; and soon after recover the new image of ~temp and rename it to the name that is in the database.

3º: Implement a hash pattern to add to your files, every time someone uploads a file, take the file name and concatenate with the following statement uniquid( Rand(6, 8) );

<?php

$nome = $_FILE['image']['name'];
$novoNome = $nome . uniquid( rand(6, 8) );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.