This forum is in archive mode. You will not be able to post new content.

Author Topic: PHP - Returning values from a linux shell script  (Read 1216 times)

0 Members and 1 Guest are viewing this topic.

Offline m0l0ko

  • Peasant
  • *
  • Posts: 129
  • Cookies: -4
    • View Profile
PHP - Returning values from a linux shell script
« on: November 30, 2012, 08:07:49 AM »
In PHP, you can run shell scripts with the command:
Code: [Select]
shell_exec("shell_script.sh");and if you echo it:
Code: [Select]
echo shell_exec("shell_script.sh");It will echo anything that is printed by the shell script, so for example if your shell script contains the pwd command, then PHP will echo that. I'm wondering how to return multiple pieces of info from a shell script though. For example, with a PHP function, if I wanna return various different pieces of data, I'll just load all the data into an array and return the array. If I make an array in the shell script, will PHP be able to use it? I shoulda tested this out before starting this thread, I'll test it out now but I don't think its gonna work because bash is a different language so I don't see how PHP could interpret a bash array.

EDIT: From experimenting, heres what I've found. Lets say this is your shell script:
Code: [Select]
#!/bin/bash

pwd

Unix[0]='Debian'
Unix[1]='Red hat'
Unix[2]='Ubuntu'
Unix[3]='Suse'

echo ${Unix[1]}

If I run:
Code: [Select]
echo $sh1 = shell_exec('./test.sh');heres what it outputs:
Quote
/var/www/test Red hat

and if I run:
Code: [Select]
$sh2 = exec('./test.sh',$sh_arr); echo $sh_arr[0];it outputs:
Quote
/var/www/test
if I echo $sh_arr[1] it outputs "Red hat". So obviously I can pass data from the shell script to PHP by echoing the variables in the shell script but thats not gonna work if I need to pass arrays and stuff. For example, if I want to pass the whole Unix array, how do I do it? I could use a loop echo every single value in the array but there must be a more eligant way to do it than that.
« Last Edit: November 30, 2012, 08:26:57 AM by m0l0ko »

 



Want to be here? Contact Ande, Factionwars or Kulverstukas on the forum or at IRC.