Search code examples
phpsystemshellexecute

PHP read command from file and run it


I have a unix command written in a file and I need PHP to read it and execute it. The reason it needs to be read from a file is because the commands symbols mess up the script when put them directly in it. So far I have this:

<?php
$command = readfile("http://localhost/command.txt");
echo shell_exec($command);
?> 

Upon running this all I get is the value of the text file and the command is not executing. Is there a way this can be done?

Thanks for any help


Solution

  • The readfile() function does not do what you think it does. It outputs the contents of the file to the browser, and returns the number of bytes read.

    Instead, you want file_get_contents():

    $command = file_get_contents('http://localhost/command.txt');
    echo shell_exec($command);
    

    But one question: Why are you pulling the command file from a website? Why not the local files-ystem?