Search code examples
phpfile-get-contentsproduction-environment

file_get_contents not working on production server, fine on local


I have a PHP script that fetches an image from a remote server so that I can manipulate it using HTML5 canvas API.

<?php
if ((isset($_GET['url']))) {
    $url = $_GET['url'];
    $file_format = pathinfo($url, PATHINFO_EXTENSION);
    try
    {   
        header("Content-Type: image/$file_format");
        header("Content-disposition: filename=image.$file_format");
        $img = file_get_contents($url);
        echo $img;
    }

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

else die('Unknown request');
?>

A typical request would look like this:

fetch_image.php?url=http://example.com/images/image.png

Everything works fine on my local server but the production server gives me this error:

NetworkError: 500 Internal Server Error.

The error log registers this message:

PHP Warning: Cannot modify header information - headers already sent.

I have tried some of the suggestions but its not working:

allow_url_fopen = 1

Solution

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