My application sends urlencoded or base64encoded string via http get request, the string contain image data, that most be download from the php file, but i dont know how php would download image from my string that is either urlencoded or base64encoded, please help me out guys... im lost
Serve image to a user
// we assume $imageData is PNG
$image = urldecode($imageData);
// or
$image = base64_decode($imageData);
// in case of force download change Content-Type: image/png to
// application/octet-stream and Content-Disposition: inline to attachment
header('Content-type: image/png');
header('Content-Disposition: inline; filename=' . md5($image) . '.png');
header('Content-Length: ' . strlen($image));
echo $image;
exit;
The problem si to detect correct Content-Type if you don't know it. But browsers should be able to autodetect it on its own.
Some notes about caching
PHP implicitly sends headers which prevents browser caching of retrieved data. I suggest you to set these headers manually (Cache-Control, Expires, Pragma). To work properly, every single image must be served by an unique URL. Also try to avoid of starting sessions. On heavily accessed website with public access you can easily flood webserver with redundant session files.
Save image to a file
$image = urlencode($imageData);
// or
$image = base64_decode($imageData);
if (!file_put_contents('abs/path/to/save/file.png', $image)) {
throw new Exception('Image could not be saved');
}
Related
$file_name = $_GET['title'];
$file_url = $_GET['url'] . $file_name;
header('Content-Type: video/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$file_name."\"");
readfile($file_url);
exit;
I'm using this code to download files in my site fetching from another websites.
It works if my url looks like:-
https://www.example.com/video_download.php?title=video.mp4&url=http://googlevideo.com/video/download/223689/289048
(example)
So, it starts downloading by fetching the video file from http://www.googlevideo.com/video/play/221589 to my site.
But my problem is that the file can be accessed if the person uses a PC.
Can I change the User Agent by using header()?
Is it possible?
So if I change the user agent into a PC user agent, so it can be downloaded from a mobile!
I'm sorry, but the User Agent has nothing to do with readfile() function. Readfile() will just throw the raw file input into your browser. Useful for e.g. rendering images through PHP to the client without having to expose the real file name.
Indeed, it is possible to render video to the client with readfile(), but using a HTML5 video tag will dramatically improve performance. This will also provide better mobile support.
Hope this helps you,
You can use stream_compy_to_stream
$video = fopen($file_url);
$file = fopen('videos/' . $title . '.mp4', 'w');
stream_copy_to_stream($video, $file); //copy it to the file
fclose($video);
fclose($file);
I wrote a class for downloading youtube video files. you can find it here.
I have uploaded few images on my server which will be downloaded to my android application by passing a url. I have written a php file which displays the image. I pass the URL to my android application like this :
'http://myURL/getImage.php?image=logo.png'.
When I copy paste the URL directly in browser the image is displayed correctly.
However the image file is not getting downloaded on my android application. I know that android code is correct because when I am giving any other random image URL the image is downloading correctly. Do I have to give something else in my php file to make the image 'downloadable'.
Image.php
<?php
echo '<img src="Images/'.$_REQUEST['image'].'"/><br />';
?>
It seems you want the PHP to output the image directly. Instead, your code is generating an HTML with the image on it. Although your browser displays similar results, the underlying content is different.
What you actually need could be this:
<?php
$filepath = 'Images/'.$_REQUEST['image'];
$filename = basename($filepath);
$ctype = 'image/jpeg'; // assuming it is a .jpg file
if (is_file($filepath)) {
header('Content-Type: '.$ctype);
header('Content-Length: ' . filesize($filepath));
header('Content-Disposition: attachment; filename="'.$fileName.'"');
echo file_get_contents($file);
exit();
} else {
header("HTTP/1.0 404 Not Found");
// you may add some other message here
exit();
}
This is vulnerable to hazardous $_REQUEST['image'] input. Just filter it somehow. Also you must generate the correct $ctype for the image file.
How may I display an image without using any kind of HTML.
Let's say I have some protected images, which may only be shown to some users.
The protected image is in directory images/protected/NoOneCanViewMeDirectly.png
Then we have a PHP file in the directory images/ShowImage.php, which check if the user is permitted to view the image.
How may I display the image using PHP only.
If you're not sure what I mean this is how I want to display the image. http://gyazo.com/077e14bc824f5c8764dbb061a7ead058
The solution is not echo '<img src="images/protected/NoOneCanViewMeDirectly.png">';
You could just header out the image with the following syntax
header("Content-type: image/png");
echo file_get_contents(__DIR__."/images/protected/NoOneCanViewMeDirectly.png");
if (<here your logic to show file or not>)
$path = $_SERVER["DOCUMENT_ROOT"].<path_to_your_file>; // to get it correctly
$ext = explode(".", $path);
header("Content-Type: image/".array_pop($ext)); // correct MIME-type
header('Content-Length: ' . filesize($path)); // content length for most software
readfile($path); // send it
}
Note: 1. image/jpg is not correct MIME-type, use image/jpeg instead (additional check needed), 2. readlfile() is better than echo file_get_contents() for binary data, 3. always try to provide content length for browsers and other software
You can use imagepng to output png image to browser:
$im = imagecreatefrompng("images/protected/NoOneCanViewMeDirectly.png");
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
I am trying to download remote mp3 files with an audio/mpeg mime type instead of right clicking on the link then saving as. I have tried modifying the header content-type with php headers and then calling the file with readfile(). This worked very well but because of the readfile() command the files came out of my servers bandwidth. is there another way of changing the header without the cost of bandwidth? can i define how the browser handles with content type with javascript? has anyone had the same problem?
Thanks in advance.
By using the mime type audio/mpeg you tell the browser to "do your default action with this file". In example if you have an jpg file and set the mime type to image/jpeg the browser will read the jpg and display it inside the browser window.
The solution is to use the mime type application/data instead. This will download the file leaving the browser out of it.
That would be
header("Content-type: application/data");
== Updated ==
A more complete approach
header("Content-type: application/data");
header("Content-Disposition: attachment; filename=$this->filename");
header("Content-Description: PHP Generated Data");
readfile($this->file);
If you want a dynamic mime type reader you could use this
$type = $this->get_mime_type($this->filename);
header("Content-type: " . $type);
...
private function get_mime_type($filename) {
$fileext = substr(strrchr($filename, '.'), 1);
if (empty($fileext)) {
return (false);
}
$regex = "/^([\w\+\-\.\/]+)\s+(\w+\s)*($fileext)/i";
$lines = file("mime.types", FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
if (substr($line, 0, 1) == '#') {
continue; // skip comments
}
if (!preg_match($regex, $line, $matches)) {
continue; // no match to the extension
}
return ($matches[1]);
}
return ("application/data"); // no match at all, revert to something that will work
}
And, to get a list of mime types you can check my lab version, save the displayed content and save it to a file named mime.types in the root of your website.
http://www.trikks.com/lab/mime.html
Have fun
I think what you need to do is this:
$pathOfAudioFile = '/path/to/my/file.mp3';
header('Content-Type: audio/mpeg');
header('Content-Length: '.filesize($pathOfAudioFile));
// This next line forces a download so you don't have to right click...
header('Content-Disposition: attachment; filename="'.basename($pathOfAudioFile).'"');
readfile($pathOfAudioFile);
Using Content-Disposition: attachment... forces a download box to appear instead of having to right click -> save target as.
I really do not know any PHP but I'd love to do one simple thing:
I access a php page from within a <img src="/myhumbleimage.php" /> and I'd like to have an image returned from another URL.
I came up with:
<?php
header('Content-Type: image/png');
readfile('i' . rand(1,3) . '.png');
exit;
And it works:
Avatar selection http://vercas.webuda.com/img.php?.png
(Reload the page a few times!)
Check out readfile().
The basic idea is you send the appropriate MIME type headers (using header()) then deliver the file contents using readfile().
For example
<?php
// myhumbleimage.php
// Do whatever myhumbleimage.php does before the image is delivered
header('Content-Type: image/jpeg');
readfile('path/or/url/of/image/file.jpg');
exit;
Why not just reference the image directly then? If you are trying to hide the fact you are pulling an image from an external source, that external source will still be able to tell you are pulling their images.
Otherwise, pass a Content-Type header with the appropriate mime-type and echo the results of file_get_contents($imageUrl).
Just generate or read, then output the image using PHP.
...get image data from file or dynamically...
header('Content-type: image/png'); //or whatever MIME type
print $imgdata;
Or check out this: http://php.net/manual/en/function.imagepng.php
I've discovered problems if I didn't also include a 'Content-Length: ' header. The problems are crawler, proxy, and browser caching related. In worst cases the browser waits until timeout for more data.
It's in the spec' and solved all issues so I've always included it even if modern browsers may work without it. Who knows, there still may be a slight delay since the browser doesn't know when it has received the last segment.
Another problem I see here is that you are assuming a .png image format.
Better to create a specific function for the purpose so you can re-use it.
function returnImage( $path ) {
header( 'Content-Type: image/' . substr($path, -3) );
header( 'Content-Length: ' . filesize( $path ) );
readfile( $path );
exit;
}
I've made a lot of assumptions here (like the file exists and its extension is 3 characters) but this sequence seems to be the silver bullet in my experience.