PHP method of loading remotely stored files

197 Views Asked by At

I am using SmartFile to store user submitted files. To display image files on the site I could just link to them, but if the file is missing I have no option to display a default image instead. Or to prevent hot linking. Or to setup browser cache etc.

Their API is throttled to 180 requests per min. So it’s no good for displaying images on a busy site.

I have tried using get_headers to check the expected file exists and then file_get_contents, if it does, but that is very slow and inefficient. Just using file_get_contents with out get_headers first is very slow!

What’s my best option here? I haven’t tried using curl yet. I think I could get headers and file with just one request with that, but as file_get_contents is slow, I imagine curl won't be any faster.

2

There are 2 best solutions below

2
On

You can do this loading and checking in browser by JavaScript. So your application just passes the link to file and user will see loading image while JavaScript will check if image exists.

Example using jQuery:

<img src="loading.gif">
<script>
    $.ajax({
        type: 'HEAD',
        url: 'http://example.com/image.jpg',
        success: function() {
            $('img').attr('src','http://example.com/image.jpg');
        },
        error: function() {

        }
    });
</script>

You don't have to load the image with file_get_contents if you don't need to hide the image path.

You can also have some database table where you will cache the image address. And check every hour if the link is still working or broken. And if it is broken, you will change the url to that image to missing.jpg in database.

You can also consider to move from smartfile to DropBox or other service.

0
On

Try it grabbing image from another site, yes it use file_get_content

<?php 

if(!isset($_GET['read'])){
 $url = "http://mangaku.web.id/baca-komik-naruto-terbaru-bahasa-indonesia/"; 
 $input = @file_get_contents($url) or die("Could not access file: $url");
 $regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>"; 
 if(preg_match_all("/$regexp/siU", $input, $matches, PREG_SET_ORDER)) {
 foreach($matches as $match) {
     if (strpos($match[2],'chapter')!== false OR strpos($match[3],'naruto-chapter')!== false) {
    echo "<a href='http://localhost/mangaku.php?read=".$match[2]."'>".$match[3]."</a><br>";
}
 } 
 }
}

 if(isset($_GET['read'])){
 $url = $_GET['read']; 
 $input = @file_get_contents($url) or die("Could not access file: $url");
 $regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>"; 
 if(preg_match_all("/$regexp/siU", $input, $matches, PREG_SET_ORDER)) {
 foreach($matches as $match) {
     if (strpos($match[2],'bp.blogspot.com') !== false) {
  echo "<center><image src='".$match[2]."'></center><br>";
  //echo $match[2]."<br>";
}
 } 
 }
}
?>