PHP manages a block without creating a file


I there a way to handle a blob(a file saved to mysql) without having to create a file?

I need to retrive a blob from the db, wich can be any kind of file, img, text, video, etc. and be able to show it in html.

So far, what I managed to do is to create a file and work with it. But this has a little problem and it is that i have to delete it after the user stop working with the file. But I can not create a cronjob(or something simillar) to delete these files after some time.

Any Ideas?


You can have a script that prints the content of the file on-the-fly from the database. All you have to do is to store its content-type and retrive the content from the database.

$contenttype = ... // retrive content type from database
$blob = ...  // retrive blob from database

header('Content-type: ' . $contenttype);
echo $blob;

If you don't have MIME type saved in your database, you can try this: Determinate mime type from MySQL column

function mimetype($data)
    //File signatures with their associated mime type
    $Types = array(
    "474946383761"=>"image/gif",                        //GIF87a type gif
    "474946383961"=>"image/gif",                        //GIF89a type gif
    "FFD8FFE0"=>"image/jpeg",                           //JFIF jpeg
    "FFD8FFE1"=>"image/jpeg",                           //EXIF jpeg
    "FFD8FFE8"=>"image/jpeg",                           //SPIFF jpeg
    "377ABCAF271C"=>"application/zip",                  //7-Zip zip file
    "504B0304"=>"application/zip",                      //PK Zip file ( could also match other file types like docx, jar, etc )

    $Signature = substr($data,0,60); //get first 60 bytes shouldnt need more then that to determine signature
    $Signature = array_shift(unpack("H*",$Signature)); //String representation of the hex values

    foreach($Types as $MagicNumber => $Mime)
        if( stripos($Signature,$MagicNumber) === 0 )
            return $Mime;

    //Return octet-stream (binary content type) if no signature is found
    return "application/octet-stream";