How To Check If a Remote Page Has a 301 Redirect via CURL?

Discussion in 'PHP' started by ColorWP.com, Jan 30, 2010.

  1. #1
    Hello.

    I want to check if a specific remote page (an image in my case, e.g. http://i38.tinypic.com/2nv8l1k.jpg - (safe for work)) redirects to another page via CURL.

    Sometimes TinyURL deletes the image unexpectedly and redirects all requests to http://tinypic.com/images/404.gif

    I want to check if a remote image I try to request like this:
    <? get_file("http://i38.tinypic.com/2nv8l1k.jpg") ?>
    PHP:
    ...redirects to the 404 image or not. If it does I will show a default image of my own.

    If I could do this without having to download the image (in case it exists at TinyURL) so I don't put load on the server with a lot of CURL downloads - it would be great.

    Currently I have this CURL downloading function:
    function get_data($url)
    {
    	$ch = curl_init();
    	$timeout = 5;
    	curl_setopt($ch,CURLOPT_URL,$url);
    	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    	curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
    	$data = curl_exec($ch);
    	curl_close($ch);
    	return $data;
    }
    PHP:
    Is it possible?
     
    ColorWP.com, Jan 30, 2010 IP
  2. HivelocityDD

    HivelocityDD Peon

    Messages:
    179
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Please give it a try with

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

    I hope this will help you to redirect to a referred page if one is there.
     
    HivelocityDD, Jan 30, 2010 IP
  3. Bec0de

    Bec0de Well-Known Member

    Messages:
    46
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    115
    #3
    <?php
    $headers = get_headers("http://i38.tinypic.com/2nv8l1k.jpg", 1);
    if ($headers[0] == "HTTP/1.1 200 OK"){
      echo "Image found";
    } else {
      echo "Image not found";
    }
    ?>
    PHP:
     
    Bec0de, Jan 30, 2010 IP
  4. ColorWP.com

    ColorWP.com Notable Member

    Messages:
    3,120
    Likes Received:
    100
    Best Answers:
    1
    Trophy Points:
    270
    #4
    This will just make CURL follow the image URL to the 404 image URL, which I want to avoid.

    I've tried this and it works. However, is the get_headers() function resource friendly? I mean, it won't put much stress to the server, right? I am guessing it's not actually downloading the remote file to the server, but only it's headers.
     
    ColorWP.com, Feb 1, 2010 IP
  5. Bec0de

    Bec0de Well-Known Member

    Messages:
    46
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    115
    #5
    Better than CURL, it will only get the headers.
     
    Bec0de, Feb 1, 2010 IP