file_get_contents not working on production server, fine on local

早过忘川 提交于 2019-12-05 14:49:58

Check that the server allows you to open remote URLs with the file functions (the php.ini "allow_url_fopen" setting must be "true").

Try

ob_start()

in the beginning and

ob_end_flush()

at the end of the script. Also make sure that the script contains no characters before the <?php.

You should make sure that your hosting provider has not disabled remote URL fetching for security reasons. The setting is allow_url_fopen and you can inspect current configuration with phpinfo(). In such case, file_get_contents() should return FALSE so you must test $img against false with the === operator.

yogs

Try this way

<?php
if ((isset($_GET['url']))) {
    $url = $_GET['url'];
    $file_format = pathinfo($url, PATHINFO_EXTENSION);
    try
    {   
        ob_clean();
        ob_start();

        header("Content-Type: image/$file_format");
        header("Content-disposition: filename=image.$file_format");
        $img = file_get_contents(urlencode($url));
       // as per manual "If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode(). " 
        echo $img;
        echo ob_get_clean();
        exit();
    }

    catch(Exception $e)
    {
        echo $e->getMessage();
    }
}

else die('Unknown request');
?>

one more solution from manual

Sometimes you might get an error opening an http URL. even though you have set "allow_url_fopen = On" in php.ini

For me the the solution was to also set "user_agent" to something.

The headers gets sent when you start outputting content. So somewhere before the code you've supplied above, content gets echoed out (from PHP or in plain HTML or javascript). You need to hunt down where that happens.

  1. you should check for encoding of the file as utf8 will break the headers
  2. check if your file does not print any other data before it runs the script.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!