How to save several pictures into a single PHP file

A solution is to read the files, encode them using base64 algorithm and to save them as variables of type String.

The following script reads the whole directory, encodes the files and prints the result as the PHP code (Array).

To display encoded pictures the PHP script must send a proper Content-type header, unencode the contents of a string and print it.

Download

<?php
$_start_directory = './inputdir/';

function file_rnti_text($file) {

    file_exists($file) or die('The file '.$file.' does not exists! <br /><strong>The application will terminate.</strong>');
    $fp = fopen($file, 'r') or die('Unable to open the file '.$file.'! <br /><strong>The application will terminate.</strong>');
    $binaryData = fread($fp, filesize($file)+1) or die('Unable to read the file! '.$file.'<br /><strong>The application will terminate.</strong>');
    fclose($fp);
    $textData = base64_encode($binaryData);
    
    return $textData;
}

$directory=opendir($_start_directory) or die('Unable to open the directory!');
    while($file=readdir($directory)){
        if(is_file($_start_directory.$file)) {
          
            $fileex=strtolower(str_replace('.','', strrchr($file, '.')));
            if($fileex == 'gif' || $fileex == 'png') {
                $textData = file_rnti_text($_start_directory.$file);
                echo '$_graphics[\''.$file.'\'] = \''.$textData.'\';'."\n";
            }
        }
    }
?>

Powered by PepisCMS