file_get_contents() for short urls

馋奶兔 提交于 2019-12-21 14:46:53

问题


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?


回答1:


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.




回答2:


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.




回答3:


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;


来源:https://stackoverflow.com/questions/6172459/file-get-contents-for-short-urls

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!