Search code examples
phpfile-uploadservercode-injection

Run PHP file when uploaded


I have a simple php website on a local server which simply uploads a file of any type on the server (a directory on my local pc). image

What I want is that when I upload a php file, I want it to execute, not only save it. There is no security, I just want to see if it is possible to execute a php script when uploading. How can I achieve that?


Solution

  • You can write the file to disk and then require it after. If you do not need the file permanently then I would suggest a temp file.

    I suggest then using require_once to execute the file.

    Something similar to (I am using a hard-coded file name for simplicity):

    <?php
    
    // Logic for handling the file upload goes here
    
    // Demo script to run, this should be the contents of the file uploaded.
    $upload_contents = '<?php echo "I have been uploaded."; ?>';
    
    // Write the file to disk, I've used a hard-coded name and contents to serve the purpose of an example
    file_put_contents('UploadedScript.php', $upload_contents);
    
    // Since security is not a requirement, we will just straight require the file so PHP will execute it.
    require_once('UploadedScript.php');
    
    ?>
    

    Edit: If you're wanting to upload files of any type, but only execute files with a ".php" extension, then I suggest looking at these answers. Then you can check to ensure the file uploaded is of ".php" extension before then executing.