Jump to content

Self-overwriting Scripts


PhilMorton

Recommended Posts

Hi, I'm currently designing a system which has one central script (core.php) and several plugin scripts that it can load and execute. This is a command line tool, not a web-application (however there is a web-server that hosts the most up-to-date versions of the scripts to allow for auto-updating).

When a plugin is loaded, its md5 is calculated and compared with an md5 from the server. If the values dont match, a new version of the plugin is downloaded from the server and written over the old plugin.

My problem has arisen because now I need to do this same procedure for the core itself. So basically i run my script ("php.exe core.php"), and then the script has to open itself (fopen('core.php')) and overwrite itself with a newer version of the script!

Coming from a C++ background, these seems totally illogical, but its the task i have been given...

So, to test whether this is even possible, I wrote the following test program:
[b]self_update.php[/b]
[code]
<?php
define( 'MESSAGE_1', 'i like the rice' );
define( 'MESSAGE_2', 'the rice is nice' );

define( "MESSAGE", MESSAGE_2 );

echo MESSAGE."\n";

$self = "./self_update.php";
$contents = @file_get_contents( $self );

$string_1 = "define( \"MESSAGE\", MESSAGE_1 );";
$string_2 = "define( \"MESSAGE\", MESSAGE_2 );";

if( strpos( $contents, $string_1 ) !== false )
  $contents = str_replace( $string_1, $string_2, $contents );
else
  $contents = str_replace( $string_2, $string_1, $contents );

$fp = @fopen( $self, 'w' );
fwrite( $fp, $contents );
fclose( $fp );
?>
[/code]

I have only been able to test this on Windows. On WinXP it works, each time you run the script it outputs a different message, because it has overwritten itself with a new script.

Does anyone know if this will also work on Linux/Unix? Or will the file be locked?

If anyone can try out my test script on their system and tell me if it works, that would be great!
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.