Search code examples
phpimageurlgettumblr

Can't copy images from Tumblr to my site, connection timed out error


Tumblr image example:

https://69.media.tumblr.com/ec3874e541a767ab578495b762201a53/tumblr_ph9je0Akck1r89eh5o1_1280.jpg

Code:

<form method="get">
    <input type="text" name="url"/>
    <input type="submit" value=" загрузить "/>
</form>

<?php
 $name = md5(date('Y-m-d H:i:s').rand(0, 1000));
 $folder = 'upload/';
 $source = ($_GET['url']);
 $dest = $folder.$name.'.png';

 copy($source, $dest);
 echo 'http://mysite.example/'.$folder.$name.'.png';
?>

I found this in another question on this site:

If you can view the image in a browser that is on the same machine as your program, then it might be that the server won't send the picture unless you look like a user rather than a program. In that case, modifying the browser identification string might fix your problem. If you cannot view the image from a browser running on the program's PC, you will need to look elsewhere for the source of your problem.

I think, a problem i have is similar to this. Tumblr gives picture to view in a browser, but doesn't allow to copy it with a script.

How to fix that? For example, sites like imgur can upload Tumblr images by url with no any problem.

P.S. For images from other sites copying with this script goes normally.

Addition 01:

As it turned out, the problem is with my site. When i run this code on another site, it works normally with Tumblr images. I have a free domain .ml and free hosting Byethost. I have two guessings. The first is, my domain or hosting is in a blacklist on Tubmlr. The second one, i have some wrong settings on my site. If first guessing is right, is there any way to make it works without changing domain or hosting? If the second is true, what a settings i must check and change?


Solution

  • Tumblr appears to be inspecting the HTTP request and generating different responses depending on how you get it. Your code is fine, as you know, for most sites. When I run it as-is, I get a 403 denied error.

    Changing the code to use Curl instead allowed me to download your file. My guess is the default headers used in PHP's copy() are blocked.

    <?php
    function grab_image($url,$saveto){
        $ch = curl_init ($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
        $raw=curl_exec($ch);
        curl_close ($ch);
        if(file_exists($saveto)){
            unlink($saveto);
        }
        $fp = fopen($saveto,'x');
        fwrite($fp, $raw);
        fclose($fp);
    }
    
    $name = md5(date('Y-m-d H:i:s').rand(0, 1000));
    $folder = 'upload/';
    $source = ($_GET['url']);
    $dest = $folder.$name.'.png';
    
    grab_image($source, $dest);
    

    The grab_image() function was a SO answer for another question.