www-data is the user running the PHP script which is executed from an HTML button which passes several variables to the PHP script successfully.
The PHP script then passes those variables to a bash script successfully.
The issue comes when the bash script tries to make a directory in /media/bh/STORAGE/V/ folder. That folder is owned by www-data and has executable permissions.
If I comment out the mkdir line, all works fine and the expected output is sent back to my PHP script. But if I leave the mkdir comment, it throws an error.
Thanks for any assistance if the issue seems obvious enough to somebody willing to share their thoughts.
Bash Script code:
!/usr/bin/bash
echo "Here we go!"
echo "PHP Path: $PATH"
echo "Image Path: $1"
echo "Seed: $2"
echo "Prompt: $3"
echo "Batch Size: $4"
echo "Output Filename: $5"
mkdir /media/bh/STORAGE/V/test/
# the above mkdir will only work if I run the script as user
# ie www-data executing this script through PHP throws an error at the mkdir part
# despite www-data being the owner of /media/bh/STORAGE/V/ and having execute priv
My PHP code:
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$image_path = '/media/bh/STORAGE/V/example.png';
$seed = rand(); // Generate a random seed instead of using a hardcoded one
$prompt = "a pixar cartoon man flies through the air with a smiling sun above him";
$batch_size = 5;
$output_filename = "/media/bh/STORAGE/V/Temp/example.png";
// Create an array of arguments to pass to exec()
$args = [
'./I2T2I.sh',
$image_path,
$seed,
$prompt,
$batch_size,
$output_filename
];
// Use escapeshellarg on all arguments to ensure they're safe for shell execution
$escapedArgs = array_map('escapeshellarg', $args);
echo "Running command: <br><br>" . implode(' ', $escapedArgs);
// Use exec() instead of shell_exec(), which allows you to get the output and return code
$output = [];
$return_var = 0;
exec(implode(' ', $escapedArgs), $output, $return_var);
if ($return_var !== 0) {
// There was an error running the command
$error = error_get_last();
echo "<br><br>Error executing command. Return code: $return_var";
if($error != null){
echo "<br><br>Last PHP error occurred: '" . $error['message'] . "'";
}
} else {
// The command ran successfully
echo "<br><br>Command executed successfully!";
// Output the STDOUT and STDERR from the bash script
echo "<br><br>Output:<br><br>";
foreach ($output as $line) {
echo htmlspecialchars($line).'<br>';
}
}
}
?>