php如何在不知道扩展名的情况下从url获取图像

标签 php file-exists

我想从给定的网址检索图像,我有文件名,但问题是扩展名未知。它可以是 jpg、gif 或 png。

这就是我的处理方法,但似乎不起作用:

$extensions = array('jpg', 'png', 'gif');
    foreach ($extensions as $ext) {
        if (file_exists('https://mytestimage.com/products/3c763dce-666b-4ba9-a05a-cca846391aea/thumb.' . $ext)) {
            echo 'Found filename.' . $ext;
            break;
        }
    }

有什么建议吗?

最佳答案

由于文件不在现场,请检查 URL 是否存在。

$file = 'http://example.com/image.jpg';
$fileHeaders = @get_headers($file);
if( $fileHeaders[0]=='HTTP/1.1 404 Not Found')
{
    // File doesn't exist
}
else
{
    // File exists
}

您可以将此逻辑应用于不同扩展的循环。

引用文献:PHP.net & SO

关于php如何在不知道扩展名的情况下从url获取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30329021/

相关文章:

php - 有没有办法找到/删除孤立文件(未在 SQL 数据库中列出)?

php - 获取图像 JPG 和 jpg

c++ - C++ 检查文件是否存在

php - 如果我成功连接后,有效的 mysql 查询会失败吗?

php - WordPress php.ini 文件设置 upload_max_filesize 以获得 2MB 左右的上传大小

php - 在php继承中执行__constructor()

php - 文件目录和自动加载问题 PHP MVC

android - File.exists() 对现有文件返回 false

codeigniter - php 文件总是不返回任何内容 - CodeIgniter

php - MySQL SELECT where if 条件组