Search code examples
phpimagedomdocumentscraper

How to save image from remote server where image extension is missed using PHP


I use DOMDocument to extract the html page which contains the image file,html page looks like this

<div>
   <img src="http://pic.aa.com/a/b/0525">
</div>

After I extracted src address,I put it in this function

copy('http://pic.aa.com/a/b/0525', 'd:tmp/img_name');

Where I don't get is how to decide what extension the file should has,there's no clue from the uri,and the only possible way is by using chrome browser tool to check the response header,but it seems lack of efficiency,anybody knows the proper way to do it?


Solution

  • well than i can just give you the hint to use the exif_imagetype(); function provided here:

    http://php.net/manual/en/function.exif-imagetype.php

    you can use a for/while/foreach loop to determine the imagetype like:

    <?php
    if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
        echo 'The picture is not a gif';
    }
    ?>
    

    also something like this might help you out:

    <?php 
    $filename = 'http://myhost/myunkownimagefiletype'; 
    $size = getimagesize($filename); 
    
    switch ($size['mime']) { 
        case "image/gif": 
            echo "Image is a gif"; 
            break; 
        case "image/jpeg": 
            echo "Image is a jpeg"; 
            break; 
        case "image/png": 
            echo "Image is a png"; 
            break; 
        case "image/bmp": 
            echo "Image is a bmp"; 
            break; 
    } 
    ?>