How to create a self extracting PHP script
By Justin Silverton
PHP has a built-in command called __HALT_COMPILER__. This command Halts the execution of the compiler. This can be useful to embed data in PHP scripts. Below is an example of a self-extracting php script. When executed, a second php file will be extracted in the same directory called testscript1.php.
<?php
//gzdecode function
function gzdecode ($data) {
$flags = ord(substr($data, 3, 1));
$headerlen = 10;
$extralen = 0;
$filenamelen = 0;
if ($flags & 4) {
$extralen = unpack('v' ,substr($data, 10, 2));
$extralen = $extralen[1];
$headerlen += 2 + $extralen;
}
if ($flags & 8 ) // Filename
$headerlen = strpos($data, chr(0), $headerlen) + 1;
if ($flags & 16) // Comment
$headerlen = strpos($data, chr(0), $headerlen) + 1;
if ($flags & 2) // CRC at end of file
$headerlen += 2;
$unpacked = gzinflate(substr($data, $headerlen));
if ($unpacked === FALSE)
$unpacked = $data;
return $unpacked;
}
$fp = fopen(__FILE__, 'r');
// seek file pointer to data
fseek($fp, __COMPILER_HALT_OFFSET__);
// and output it
$buffer = fread($fp,8192);
$decoded = gzdecode(base64_decode($buffer));
//$uncompressed = gzdecode($decoded);
$filename = "testscript1.php";
$fd = fopen($filename,"w");
fwrite($fd,$decoded);
fclose($fd);
__halt_compiler();H4sICKE9CEcAC3Rlc3RmaWxlMS5waHAAs
7EvyCjg5eLlSk3OyFdQKsnILFYAopLU4hKFtMycVAVDJWteLns7AKhVcUooAAAA
How it works
The file that is extracted is gzipped, base64 encoded, and stored at the end of the the file (right after the __halt_compiler directive). The script uses a custom function called gzdecode to gunzip the file, it is then base64 decoded and written to a file. This is just a simple example to show what is possible with PHP. A more advanced version could use a function to tar and gzip a file so multiple files can be extracted.
The code example from this article can be download here
댓글