Question:
In order to have the administration of a website to be performed from a different server from the one where the website is hosted, the problem of dealing with remote images arose.
Common Problems:
- Check if the image actually exists before creating links to it;
- When replacing a certain image, check if the previous one exists so that it can be deleted;
- Check that the image uploaded to the server does not have the same name as an existing image.
Normally, this type of operation is performed with is_file()
, but as 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?
Answer:
For that 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:
- is_readable – Tells if the file is readable.
- file – Read the entire file into an array
- file_get_contents – Reads entire file to a string (extremely useful)
- fread – Binary-safe read from file
- readfile – Reads and displays the contents of a file