Wednesday, May 25th, 2005
A Quine is a piece of self-reproducing code. There are plenty of resources out there to explain the theoretical side of this, about Quine himself, examples in other languages, etc. I don’t want to reproduce that information, but I’d like to walk you through the step-by-step way to making your own quine in PHP.
If you want more background information on quines, here are some places to start:
http://en.wikipedia.org/wiki/Quine
http://www.nyx.net/~gthompso/quine.htm
http://www.philosophypages.com/ph/quin.htm
So, on with the PHP example.
You will need two PHP scripts to accomplish the task at hand. My examples will be run from the command line, though you could just as easily run these from a browser.
First, create the ‘quine’ script:
#!/usr/local/bin/php <?php $dna = '*'; echo str_replace(chr(42), $dna, base64_decode($dna)); ?<
Second, create the ‘generator’ script:
#!/usr/local/bin/php
<?php
echo base64_encode(file_get_contents('./quine'))."n";
?>
Now, run the generator:
$ ./generator
Provided the files are exactly as mine, you will get a long string of characters, like “IyEvdXNyL2xvY2FsL2Jpbi9waHAKPD9 …”. Replace the asterisk in the ‘quine’ script with this long string of characters, like so:
#!/usr/local/bin/php <?php $dna = 'IyEvdXNyL2xvY2FsL2 ... '; echo str_replace(chr(42), $dna, base64_decode($dna)); ?>
Note that I have not included the full string of characters here; I’ve put an elipses where the rest of the string should be. Including it would have caused it to run way off to the right of the screen.
Now, run the ‘quine’ script:
$ ./quine
Pretty!
Notes: To follow this example exactly, you’ll need to have PHP-CLI enable (so that you can run PHP scripts from the command line). Also, your scripts will need to have the executable bits set:
$ chmod +x generator $ chmod +x quine
The idea for this was stolen from Sam Barnum at 360works. His original program is here. There’s no step-by-step method of how he made his program, though, which I thought needed to be mentioned. Thanks Sam for the idea!
