Mitchell
Mitchell

Reputation: 23

Sending data from PHP to bash script

I am trying to send data from PHP to a bash script and then output the data back to the user. Why am I unable to send "beans" to the simple.sh and get it echoed back?

In the end, my goal is to get my web browser to output "beans". Very simple but I can't get it to work (complete noob).

Here is my test.php:

<?php
echo "<pre>";
    $var = 'beans';
    exec("/var/www/html/dev/simple.sh $var", $output);
    echo var_dump($output);
echo "</pre>";    
?>

Here is my simple.sh:

read var
echo $var

What am I doing wrong?

Upvotes: 2

Views: 4124

Answers (4)

Kannika
Kannika

Reputation: 2558

You didn't execute your shell script so here is the correct code :

echo "<pre>";
    $var = 'beans';
    exec("sh /var/www/html/dev/simple.sh $var", $output);
    echo var_dump($output);
echo "</pre>";

Also, your have something wrong with your shell script :

#!/bin/sh
echo $1

Note : command READ is for scan the string from the keyboard only!! if you want to pass it by arguments please just echo these $1, $2, $3,... that is your number of argument you entered one by one.

Upvotes: 2

Trott
Trott

Reputation: 70065

Your shell script doesn't do what you think it does. read var will read user input, not a command line argument. Change simple.sh to something more like this:

#!/bin/bash

echo $1

That script assumes you only want the first argument passed to the shell script. If you need more than that, you'll have to modify the script appropriately. I'm guessing you're going to do something very different with your shell script eventually and that command line parameters are not the goal, so this should be good enough for your test.

Upvotes: 1

MZB
MZB

Reputation: 2111

"read var" is trying to read a line from standard input and putting it in a variable.

You are passing $var as a command line argument to the script, not piping it to standard input.

Upvotes: 0

ennuikiller
ennuikiller

Reputation: 46965

you access shell arguments via $1, $2, etc., so try this:

var=$1
echo $var

Upvotes: 0

Related Questions