Reputation: 1787
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
Upvotes: 4
Views: 15626
Reputation: 788
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.
Upvotes: 1
Reputation: 39704
Upvotes: 0
Reputation: 146460
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.
Upvotes: 1
Reputation: 2237
Check that the server allows you to open remote URLs with the file functions (the php.ini "allow_url_fopen" setting must be "true").
Upvotes: 11
Reputation: 5504
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.
Upvotes: 0
Reputation: 6223
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
.
Upvotes: 1