PHP: How to get all images from an HTML page
I was curious to how I could make something similar to what Facebook does when you add a link. Somehow it loads images found on the page your link leads to, and then it presents them to you so you can select one you want to use as a thumbnail.

Well, step one to solve this is of course to find all the images on a page, and that is what I will present in this post. It will be sort of like a backend service we can use later from an AJAX call. You post it a URL, and you get all the image URLs it found back. Let’s put the petal to medal!

Getting the URL

We’ll use POST for this, and it shouldn’t require much explanation.

$url = array_key_exists('url', $_POST)
    ? $_POST['url']
    : null;

Loading the HTML

To load the HTML we’ll use the handy cURL library, which I’ve used in earlier posts as well.

$request = curl_init();
curl_setopt_array($request, array
    CURLOPT_URL => $url,
    CURLOPT_CAINFO => 'cacert.pem',

$response = curl_exec($request);

We just create and execute a request for the supplied URL. The response is stored in a variable so we can use it later.

💡 We won’t bother with any fancy error handling or anywhere else. If it doesn’t work, we’ll just give an empty list back. Bad URLs, faulty HTML, not our problem 😛

💡 The SSL and cacert.pem stuff is explained in an earlier post.

Parsing the HTML

You might have seen examples on how to find things in HTML using regular expressions. This is by most experienced developers regarded as A Bad Idea™. What we can, and probably should, use instead is the DOMDocument class you find in PHP. This class can parse XML and HTML into a neat DOM which is a lot easier to work with.

$document = new DOMDocument();

Not everyone writes perfectly formed HTML without errors so we load the HTML, the DOMDocument class will do its best to plow through the HTML and figure it all out. When it does come across things that are a bit out of wack, it will let us know by spitting out warnings. There’s a big chance it managed to deal with it fine, but just for our information. However, like I mentioned earlier, we don’t care about errors here and we definitely don’t want those warnings messing up our output.

So, what we do here is to tell libxml (which is used internally) to enable user error handling instead. When we now load the HTML, those errors and warnings are then instead collected quietly. We can get to them afterwards by calling libxml_get_errors, but since we don’t care about them at all we just clear them out instead. Easy peasy.

Dealing with relative URLs

As you perhaps know you can have both absolute and relative URLs in HTML. The relative URLs are relative to the base path of the HTML page. Unless the HTML page has a base tag. In that case we need to use whatever that specifies instead. So, how do we deal with all of that?

Well, I decided to stick that in a different post. What’s important here is that we can get the base tag from the DOM like this:

$tags = $document->getElementsByTagName('base');

foreach($tags as $tag)
    return $tag->getAttribute('href');

Of course if there is a base tag, it should only be one, but since we get a collection back from getElementsByTagName I just use foreach for simplicity.

Next up we have a function which turn a relative URL into an absolute one. The signature looks like the following and the content you can read more about in that earlier mentioned post.

private static function make_absolute($url, $base)
    // "Magic"

Getting the images

Now to the fun part. With the HTML loaded up and the base path figured out, we just need to fetch the images.

$images = array();

foreach($document->getElementsByTagName('img') as $img)
    // Extract what we want
    $image = array
        'src' => self::make_absolute($img->getAttribute('src'), $base),
    // Skip images without src
    if( ! $image['src'])

    // Add to collection. Use src as key to prevent duplicates.
    $images[$image['src']] = $image;
$images = array_values($images);

Now that was pretty simple, wasn’t it? The perhaps weird thing here is that I first collect them in an array, using the image source as a key. This way we won’t end up with duplicate image URLs. We also skip images which for some reason were to not have any URL.

We could of course also get other stuff from the image tag here, like the height, width, alt text or title, or we could do some more elaborate filtering to try to weed out uninteresting images. For example really tiny ones or whatever else we might think of.

Echo it all out

Now we just need to echo it all out in a format we can use easily on the client side. And we will, surprise, surprise, of course use our good friend JSON for this :)

header('content-type: application/json; charset=utf-8');
$result = array('images' => $images);
echo json_encode($result);

We set the appropriate header, wrap it up in a result array, encode it, and spit it out. And that’s pretty much all there is to that part.

Working sample

When I implemented this I decided to wrap most of this up in a class I called Image_Finder. I have also created a tiny interface for this so you can test it out for yourself. Will go through that interface (or a variant of it) later, but since that’s all HTML and JavaScript you are of course more than welcome to have a peek at the source of it :)

Either way, you can find it all, code and sample, at Let me know if you like it. And definitely let me know if you find any bugs 😉

Bugs, improvements, suggestions, praise; please leave a comment. I like to learn :)

  • Niels van Kerkhoven

    The program for fetching the images works great.
    However when I run it on my server it wants a file named get-images.php but I cannot find it on your site.
    Could you help me?

    • Torleif

      Seems to be a left-over from while I was messing around with this. It should probably be changed to scan.php. See there was a slight mismatch between my local version and the one uploaded as well. Have re-uploaded it, so hopefully it’s error free now :p

      Thanks for the heads up!

      • Niels van Kerkhoven

        With the new version firefox and IE opens the scan.php for saving/opening (localhost version).

        • Torleif

          Then I think you’re doing something wrong. Works here in all my browsers. I’m guessing you have forgotten the JavaScript file, or perhaps you have the path wrong? And that’s probably what was wrong before too actually, when I come to think about it…

  • Niels van Kerkhoven

    when adding the url of my site the reply is not shown.
    Is this correct?

    • Torleif

      Depends what your site is 😛 Tried using the domain of your email address and got 8 images. So if that’s your URL, then it should get some images :)

      If you have an online version of this I could try it and see if I find something obviously wrong.

  • Niels van Kerkhoven

    Could you please run the imagefetcher from the url I supplied in the previous post?
    Maybe it works for you.

    • Torleif

      No, the scan.php file doesn’t return anything. So that’s where the error must be.

      By the way, when you copy things from others, don’t hot-link graphics and scripts, and definitely don’t leave tracking code. You have just copied the whole HTML of the index page, which is not good. Please remove the Clicky script code at the bottom of the page at least.

  • Niels van Kerkhoven

    Could it be that your scan file is different then the one from the website, because that is the code I copied.
    BTW All links are removed

    • Torleif

      The one in the sample is the one. The source code viewer is dynamic, so it’s the same as the contents of the actual file used. So, shouldn’t be any problems there.

      Thank you for removing the links :)

  • Graham

    Having similar problems with script execution. Think the version you uploaded may be faulty.

    • Torleif

      Rather than thinking it is faulty, how about finding the fault? 😉 How does it not work? Do you get an error message? When you view the source of the sample, you see the actual code that is running. And if what I uploaded was faulty, then the sample wouldn’t run. And it runs fine here on all my browsers, no problems at all.

      Check instead your script and your extensions. Does your web server support cURL for example?

  • Pinazinho

    If you add on line 70 of image_fetcher.class.php this code:

    $numargs = func_num_args();
    if ($numargs == 2) {
    list($width, $height, $type, $attr) = getimagesize(@$image[‘src’]);
    if($width <= func_get_arg(0) && $height <= func_get_arg(1) )

    you can choose to select only images with, at least, a minimum with and height. If you don’t pass any arguments, it will does the same till now.

    scan.php line 19:

    $images = $finder->get_images(100,100);

    • Torleif Berger

      Yeah, you could probably add a lot of functionality and smartness here, but the main points were basic cURL usage and how to parse HTML without using regex :)

  • Óscar Palacios Ruiz

    Great coding. I had written a small method on my own, but it was really slow, and I have to deliver this today! I included your class in my code, but of course retained your credits. Thank you so very much.

    • Torleif Berger

      Thanks! Fun to know the code is useful for others :)

  • Tommaso Cardone

    Thank you for this script :)

  • glurl

    Hi, good coding. I made some changes to suit my needs. I need the script returns only the url links of a page. Basically, I got this by changing the occurrences of tags ‘src’ to ‘href’ and ‘img’ with ‘a’. However, I am having difficulty in getting the name of the link appear associated with its URL. What I did was the following:

    var image = $ (‘‘)
    . prop (data.images [n])
    . html (‘test’)
    . appendTo (‘# output’)
    . load (imageLoaded);

    How do I do to every link appear in a line and with its name instead of word ‘test’? Thank you.

    • Torleif Berger

      You need to get the content of the ‘a’ tag. Probably a property called innerHTML or something. Read up on the documentation for DOMDocument on for how to do that. Note that this might end up a huge pain though, as links can contain text, images, and other stuff.

      • glurl

        Thank you!

  • chipi92

    Is this post alive? I cannot get the curl_exec working, it is stucked there. What can be? Any idea?

    • Torleif Berger

      Well, the post has never been alive, but its author still is! No idea why it’s not working for you. You kind of need to debug it yourself. Google, PHP docs, etc. Use the curl_error function, check the return status code, etc. If all else fails, you can always post a question at Good luck :)

  • chipi92

    It might be Twitter is blocking request from my free host provider.


    The request return a json encode variable.

    I cannot get data.images without decoding the return variable from scan.php

    In function getImagesFromUrlDone:

    data = jQuery.parseJSON(data);

    And then we can do data.images

  • Mike

    Hye, I want to display urls of images on a page with php and i don’t know how. You can help me?

    • Torleif Berger

      If you can’t figure it out from the code above, then no. Try

  • elijah

    This is an awesome plugin, one question. How would you go about using it in Laravel? I know its a noob question.
    Can this be made into a package and installed thru composer?

    • Torleif Berger

      You could just copy it in as a regular class you’d write manually I suppose. Anything is possible of course, but not sure I’d want this as a Composer package as it’s kind of narrow and very customized to specific usage. And besides, the code is quite short, so it’s probably just as easy to just re-implement it where you need it.

  • Goktug Yenisen

    Good work but it doesnt work for me. When i click get images button, its going to scan.php page and showing json encoded codes.
    Can you help me ?

    • Torleif Berger

      Sounds like you haven’t hooked up the Javascript correctly.

  • Junax

    I tried your demo above but its not working on this URL:
    Is there any workaround on this? Thanks!

  • hi

    soooooooooooooooooooooo gooooooooooooooooood

    Is it possible we use this code for save image in own host that the script is running now?

    If yes How is it possible ?

    • Torleif Berger


  • Jose

    Why I cannot load pages like facebook or twitter?? It works fine with other website except with a few, even the DOMDocument doesn’t work with either

    • Torleif Berger

      This script reads the HTML of the page you give it. Sites like Facebook and Twitter loads their content dynamically through Javascript, so the actual image tags aren’t found in the HTML.

  • Don Lester

    Hello nice coding by the way.
    but i have a problem, when i used your codes.
    I mean when i copied all of it ( index.php,
    image_finder.class.php, scan.php, and script.php ), when i clicked the button it redirects to http://localhost/htmltest/scan.php.
    and it just displays the json code.

    • Torleif Berger

      Did you forget the javascript file? The sample is using javascript to load the images returned in the JSON.

  • Getulio Jr

    But I can´t make it work with “data-src” too… Already tried many things =(
    Can you help me doing this, please?

    • Torleif Berger

      In addition to, or instead of? If instead of, just swap ‘src’ with ‘data-src’. If addition to, just add a case for it in the $image array where it fetches the ‘src’ attribute, and then afterwards add some checks for which one is present and which one you want.

  • Poogie

    Some pages have images loaded by JS or external CSS includes. How do I extract images mentioned by those methods? For instance take a look at this:

    The big blue chair image is loaded by JS.

    • Torleif Berger

      For that you’d have to get creative, and would depend a lot on how the site does it exactly… might not even be possible…

      As for your example, I do get big blue chair image back using my sample thing though… JS might just be for switching the images around and not actually loading them?