I want to monitor how often some external images are loaded. So my idea is instead of giving a uri directly like this:
www.site.com/image1.jpg
I can create a PHP script which reads the image, so I built a PHP file and my HTML would look like this:
<img src="www.site.com/serveImage.php?img=image1.jpg">
but I don't know how to read the image from disk and return it. Would I return a byte array or set the content type?
Kind regards, Michel
You cant echo an image using PHP. echo is for strings only. However, you can echo the image source - img src="" Just make sure you put the picture extension at the end of the file you are grabbing.
Draw Lines You can draw a simple straight line between two given points using the imageline($image, $x1, $y1, $x2, $y2, $color) function. The $image parameter is an image resource that will have been created earlier using functions like imagecreatetruecolor() or imagecreatefromjpeg() .
Sending images through a script is nice for other things like resizing and caching on demand.
As answered by Pascal MARTIN the function readfile
and these headers are the requirements:
header('Content-Type: image/gif');
mime_content_type
image/gif
image/jpeg
image/png
But beside the obvious content-type you should also look at other headers such as:
header('Content-Length: 348');
filesize
header('Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT');
filemtime
and date
to format it into the required RFC 2822 format
header('Last-Modified: '.date(DATE_RFC2822, filemtime($filename)));
header("HTTP/1.1 304 Not Modified");
For last modified time, look for this in $_SERVER
If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT
$_SERVER
with the key http_if_modified_since
List of HTTP header responses
To achieve something like this, your script will need to :
This is done with the header
function, with some code like this :
header("Content-type: image/gif");
Or
header("Content-type: image/jpeg");
or whatever, depending on the type of the image.
To send the data of the image, you can use the readfile
function :
Reads a file and writes it to the output buffer.
This way, in one function, you both read the file, and output its content.
As a sidenote :
serveImage.php?file=/etc/passwd
should be OK, for instance.I use the "passthru" function to call "cat" command, like this:
header('Content-type: image/jpeg');
passthru('cat /path/to/image/file.jpg');
Works on Linux. Saves resources.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With