Skip to content

Instantly share code, notes, and snippets.

@mecha
Last active November 7, 2023 20:01
Show Gist options
  • Save mecha/8375f91e511c4bfb132c0406159f21fd to your computer and use it in GitHub Desktop.
Save mecha/8375f91e511c4bfb132c0406159f21fd to your computer and use it in GitHub Desktop.
1-line PHP File Bomb
<?php
file_put_contents(__FILE__, substr(file_get_contents(__FILE__), 7), FILE_APPEND);
@mecha
Copy link
Author

mecha commented Mar 20, 2021

This script reads its own source code, copies the code from the 7th character (the beginning of line 3) till the end of the script, and appends that copied code to the end of the script.

This yields a script that runs the same code as the original, but twice as many times.

Run it once and the script will have 2 copies of line 3.
Run it again and the script will have 8 copies of line 3.
Run it again and the script will have 2,048 copies of line 3.
Run it again and the script will have 6.619 x 10^619 copies of line 3.

The script will require approximately 4.996 x 10^609 TERABYTES of disk space. That's more terabytes than there are particles in the universe, which makes it literally impossible to run this script more than 3 times given the laws of physics.


For the math nerds

The number of lines (not counting the opening PHP tag) follows this sequence:

S(0) = 0
S(n) = 2^[S(n-1) + S(n-2) + ... + S(0)]

Or:

S(0) = 0
S(n) = 2^P(n-1)

Where P(n) is the partial sum of S up till the (n-1)th term:

P(0) = 0
P(0) = P(n-1) + 2^P(n-1)

Which grows stupidly fast:

S(0) = 0
S(1) = 2^(0) = 1
S(2) = 2^(1 + 0) = 2
S(3) = 2^(2 + 1 + 0) = 8
S(4) = 2^(8 + 2 + 1 + 0) = 2048
S(5) = 2^(2048 + 8 + 2 + 1 + 0) = 6.619 x 10^619

I've tried running the script a 3rd time, and while PHP did give up after some time do to memory exhaustion, the script ended up taking around 300Mb of storage space.

Increasing the memory limit and the execution time can yield bigger scripts, but I'll leave that to the reader to try out! If you do decide to go big, post a comment with the resulting script size - let's get a friendly competition going!! 🥼

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment