Convert a file to php code04 Jun 2007, 507 read(s) Tags:
Is it possible to embed a whole file into a php script? No? Actually yes! However, this operation is rarely needed and is used only in some special cases...
Why would you need that?
I needed this because I had to write a php library that has a self-test module. This library included image manipulation functions. In order to test these functions, I needed an image. However, the self-test file should have been one single and simple file. In this case I wasn't able to use an external image, I had to use an "internal" one, one embeded into the php script.
I cannot define when you should use embeded images into php files. You shouldn't. But in extreme cases like mine, this could be useful. I will now explain you how I accomplished this simple thing.
How is this accomplished
The method is quite simple. The file is embeded into a normal string variable in the script. The value of this variable is represented as a sequence of ASCII codes. This has disadvantages. First of all, the the initialization of the variable takes some time. I'm not sure which of the two will take longer - to read an external file or to initialize an "embeded" file. Second, in order to use the file externally you will first have to save it. This will take some time too. If the embeded file is too large, the initialization and/or saving might not work. Last, but not least, the embeded file will take more space when it is "saved" into the script.
However, if you have to deal with some small files and by all means they should be embeded, then this will do the trick. If not, I would recommend you using normal external files...
The code/file (embed.php)
Here is the simple file I wrote. It does exactly what I explain. I will now explain you how to use/call each function in it.
embed.php <? /* * Embed a file into a php file * * Written by Martin Tsarev, www.mt-soft.org * Last change: 4 Jun 2007 * Released under GPL, use at your own risk. */ function getfile($filename){ $handle = fopen($filename, "rb"); return $contents; } function setfile($filename, $contents){ $handle = fopen($filename, "wb"); } function appfile($filename, $contents){ setfile($filename, $contents.getfile($filename)); } function embed($file, $phpfile = __FILE__){ $img = getfile($file); $ret .= "\$p = ''; for(\$i = 0; \$i < ". strlen($img). "; \$i++) \$p.='%c'; "; $ret .= "\$embed['$file'] = sprintf(\$p,"; for($i = 0; $i < strlen($img); $i++ ){ if($i < strlen($img) - 1 ) $ret .= ","; } $ret .= ");"; $ret = "<? ".$ret."?>"; appfile($phpfile, $ret); } function unembed($file){ setfile($file, $embed[$file]); } ?>
Comments Anonymous:
|