Home > Back-end >  Execute a shell script from HTML page with PHP
Execute a shell script from HTML page with PHP

Time:10-21

I'm trying to execute a shell script from an HTML page using PHP. I have found a previous example here that I have been trying to follow but I'm having an issue. I'm not sure what the cause is but no errors are returned and no file is created from the bash script.

index.php:

<!DOCTYPE html>
<html>
<head>
<style></style>
</head>
<body>
<form action="./test.php">
    <input type="submit" value="Open Script">
</form>
</body>
</html>

test.php

<?php
    exec("./bash_script.sh");
    header('Location: http://local.server.edu/ABC/abc_test/');
?>

bash_script.sh

#!/bin/bash
touch ./test_file.txt

One thing I have noticed that may be the cause of the issue is that it seems the path on the local server doesn't match with the file system exactly.

If I switch all the relative paths in the scripts to absolute paths such as: /local/sequence/temp/abc_test/file.exe

Then after clicking the button to run the script I get an error saying: The requested URL /local/sequence/temp/abc_test/test.php was not found on this server

Edit: The three files They're located at /local/sequence/temp/abc_test And there is a symbolic link pointing to that directory at /export/www/htdocs/ABC

CodePudding user response:

The error message seems to be indicating that test.php is not being found. It needs to be in the same directory as index.php

You’ve tested the actual bash script, so we can proceed with the assumption that it’s in the execution of the script receiving the submission.

I would suggest putting all the web stuff into one page, because you can test sending and receiving input.

<?php
// for testing
// exec("./bash_script.sh");

// check for POST submission (this is not just reading data)
if(isset($_POST['runScript'])) {
     // die('Request received');

    exec("./bash_script.sh");

    // It’s always proper to redirect after post :)
    header('Location: http://local.server.edu/ABC/abc_test/');
    die;
}

// finished with logic; show form
?>

<!DOCTYPE html>
<html>
<head>
<style></style>
</head>
<body>
<form method="POST">
    <input type="submit" name="runScript" value="Open Script">
</form>
</body>
</html>

Note that I added the name attribute to the submit button, and made the form use POST method while submitting to the calling page (no action means submit to yourself).

I’ve also left a few commented actions to aid in debugging if necessary

You may have to adjust the path to the bash script. Currently it’s going to look in the same directory as index.php, which is not something you’d want to do in production.

CodePudding user response:

You will be able to do that somehow, but its always very risky to allow such operations to execute from the php page.

  • Related