Gijo Varghese
Gijo Varghese

Reputation: 11780

How to fetch all images from a url in PHP?

I have got a PHP code to get all images in a URL. It will display the URL of the image. But there are some problems with the URL of the image obtained.

1: If the images are hosted in the root directory, it will not show the domain. For example, if the given URL is www.google.com, the URL of the image obtained is

"/logos/doodles/2014/womens-day-2014-6253511574552576.3-hp.png"

and what I need is

"www.google.com/logos/doodles/2014/womens-day-2014-6253511574552576.3-hp.png"

2: The URL obtained is always between " ". How can I remove it??

Here the PHP code

<?php
$url_image = $_GET['url'];
$homepage = file_get_contents($url_image);
preg_match_all("{<img\\s*(.*?)src=('.*?'|\".*?\"|[^\\s]+)(.*?)\\s*/?>}ims", $homepage, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
echo $val[2];
echo "<br>";
}
?>

Upvotes: 1

Views: 3075

Answers (2)

ehmad11
ehmad11

Reputation: 1395

try this:

$url_image = $_GET['url'];
$homepage = file_get_contents($url_image);
preg_match_all("{<img\\s*(.*?)src=('.*?'|\".*?\"|[^\\s]+)(.*?)\\s*/?>}ims", $homepage, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {

    $pos = strpos($val[2],"/"); 
    $link = substr($val[2],1,-1);
    if($pos == 1)
        echo "http://domain.com" . $link;
    else
        echo $link;
    echo "<br>";
}

Upvotes: 3

R&#225;pli Andr&#225;s
R&#225;pli Andr&#225;s

Reputation: 3923

You can remove the "" using substr($url,1,-1);

Upvotes: 0

Related Questions