Skip to content

Instantly share code, notes, and snippets.

@parweb
Last active December 7, 2016 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parweb/73867316c4bba6d718e8d1db6b751afd to your computer and use it in GitHub Desktop.
Save parweb/73867316c4bba6d718e8d1db6b751afd to your computer and use it in GitHub Desktop.
defer any code in PHP
{
"require": {
"opis/closure": "^2.1.0"
}
}
<?php
require __DIR__ . '/vendor/autoload.php';
use Opis\Closure\SerializableClosure;
function defer ( Closure $closure, $id = null ) {
$wrapper = new SerializableClosure( $closure );
$serialized = serialize( $wrapper );
// $serialized = str_replace( "\n", ' ', $serialized );
$serialized = str_replace( '$', '\$', $serialized );
// $serialized = addslashes( $serialized );
// print_r($serialized);exit;
$autoload = __DIR__ . '/vendor/autoload.php';
$raw = 'require \'' . $autoload . '\';
$serialized = <<<EOD
'.$serialized.'
EOD;
$wrapper = unserialize( $serialized );
call_user_func(
$wrapper->getClosure()
);';
$encoded = base64_encode( $raw );
$raw = base64_decode( $encoded );
// echo($raw."\n---\n\n");
$script = 'eval( base64_decode( \'' . $encoded . '\' ) );';
// exec('php -r "' . $script . '"', $output);
// return $output;
if ( is_string( $id ) ) {
$script = '/* id:' . $id . ' */' . $script;
}
$shh = '> /dev/null 2> /dev/null &';
// $shh = '';
exec(
'php -r "' . $script . '" ' . $shh,
$output
);
return $output;
}
// begining of how to use it
// with very crazy syntax
$var = 'plop';
$$var = function () use ( $var ) {
return [ "{$var}-( ".microtime().' ).txt', 'hey' ];
};
$output = defer( function () use ( $plop ) {
$files = glob( '*.txt');
array_walk( $files, function ( $file ) { unlink("$file"); });
file_put_contents( ...$plop() );
}, 'yolo' );
var_dump($output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment