Welcome Guest, Not a member yet? Register   Sign In
Random image script
#1

[eluser]Joe_Archer[/eluser]
Hi, I'm fairly well versed with CI and have been using it for around a year, successfully, both inside and outside of work.

As a little side project I'd like to produce a random image script which when called, selects an image from a folder at random and returns it to the browser.

I don't have a problem writing the code to do this, it's very straight forward, what I'm not sure about though, is how to return "just an image" to the browser. I don't want to output any HTML, I just want to return an image file as though the file had been browsed to directly on the server. I assume I'll need to set a mime type/header to do this, but I'm not sure how I'd go about doing so.

Any help greatly appreciated.
#2

[eluser]xwero[/eluser]
you need to write an independent script for this to work.
Code:
<?php
$path = $_GET['path'];
/*
* random code
*/


header('Content-type: '.$contenttype);
header('Content-Disposition: attachment; filename="'.$filename.'"');
readfile($filepath);
?>
Almost unchanged php.net code Smile

To make a helper function out of this you do as follows
Code:
function random_image($path)
{
   include('random_image.php?path='.$path);
}
It is untested but it should work.
#3

[eluser]Joe_Archer[/eluser]
ok thanks, that makes sense.

much appreciated.
#4

[eluser]Joe_Archer[/eluser]
I ended up doing it thus:

Code:
<?php
class Randomimage extends Controller{
    function Randomimage(){
        parent::Controller();
        $this->load->helper('file');
    }
    
    function index(){
        $path = '/path/to/image/folder/';
        $filenames = get_filenames($path);
        $key = array_rand($filenames);
        $image = $filenames[$key];
        Header("Content-Type: image/jpg");
        readfile($path.$image);
    }
}
?>

I didn't need any independent scripts in the end.




Theme © iAndrew 2016 - Forum software by © MyBB