file_get_contents() for short urls
Asked Answered
D

3

6

file_get_contents() doesn't read data for short urls Example:

  • http://wp.me/pbZy8-1WM,
  • http://bit.ly/d00E2C

Please help me in handle this. OR Is there any CURL function to handle above links?

Disenthrone answered 30/5, 2011 at 5:6 Comment(7)
@erisco if you use file_get_contents with a URL, it defers to cURL to get the dataCollocate
According to php.net/manual/en/wrappers.http.php HTTP redirects are supported.Sibert
i tagged it in curl becoz can any one help me out by using curl functions.Disenthrone
CURLOPT_FOLLOWLOCATION is how you'd handle this with cUrlEssary
@Rafe I don't believe that is entirely correct.Outdoors
I think you'll find it does.Outdoors
Do you have allow_url_fopen on in php.ini?Outdoors
A
7

This in general works fine. If you find it doesn't do the right thing you can explicitly use a stream context:

$url = "http://bit.ly/d00E2C";
$context = stream_context_create(array('http' => array('max_redirects' => 5)));
$val = file_get_contents($url, false, $context);

should do it. No need to touch CURL for that.

Alsatian answered 30/5, 2011 at 5:24 Comment(2)
I stole your contribution of 'max_redirects'... not sure how I feel about that. Can you merge answers on Stackoverflow?Sibert
Since there is really no merge, my expectation is you get the answer given yours is more complete. Since we can't split the points...Alsatian
S
4

On my machine, I cannot replicate your problem; I receive the page as intended. However, should the issue be with the redirect, this may solve your problem.

<?php
$opts = array(
    'http' => array(
        'follow_location' => 1,
        'max_redirects' => 20
    )
);
$context = stream_context_create($opts);
echo file_get_contents('http://wp.me/pbZy8-1WM', false, $context);

I imagine there may be a directive that toggles redirect following, but I have not yet found it. I will edit my answer should I.

Sibert answered 30/5, 2011 at 5:22 Comment(0)
A
1

What you can do is using curl with CURLOPT_FOLLOWLOCATION set to True:

$ch = curl_init("http://bit.ly/d00E2C");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);
curl_close($ch);

echo $result;
Assimilation answered 30/5, 2011 at 5:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.