Search code examples
phpimagefile-get-contentssrc

Change img src to direct link, for use in photo gallary


I'm trying to make a page that will accept a URL input by the user then it will display all the images from that address. I have this working, however if the image src on the page is written like this:

/image/picture.jpg

Rather than this:

http://www.site.com/image/picture.jpg

Then my page wont display it because its not local to my server. What I want to know, is there a simple way to directly link to that files location?

My Code is below:

<?php 
$html = file_get_contents('http://www.deviantart.com/');

$dom = new domDocument;
@$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
  $data = $image->getAttribute('src');
  echo "<img src='".$data."' />";
}
?>

Solution

  • Simply prepend site url to src element. I would aslo add check, if src starts with http://

    foreach ($images as $image) {
      $data = $image->getAttribute('src');
      if (!preg_match('/https?:\/\//i', $data)) {
        // If src attribute does not start with "http://" or "https://", then prepend site base url
        $data = 'http://site.com/' . ltrim($data, '/');
      }
      echo "<img src='".$data."' />";
    }