PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 22, 2022

[FIXED] How to pass a varible through a php file to bash script

 July 22, 2022     bash, exec, php, shell     No comments   

Issue

I need to run a bash script from php file. Here is my try...

$old_path = getcwd();
chdir('/home/svradmin/scripts');
$output = shell_exec('./testbash.sh');
chdir($old_path);

My testbash.sh as follows..

#!/bin/bash
echo "Hello World"

This works fine... Now I need to pass an variable from my php function and according to that the bash script should run.. lets say as an example..

   function fcn1() {
    $old_path = getcwd();
    chdir('/home/svradmin/scripts');
    $output = shell_exec('./testbash.sh');//need to pass variable 'fcn1'
    chdir($old_path);
    }



   function fcn2() {
    $old_path = getcwd();
    chdir('/home/svradmin/scripts');
    $output = shell_exec('./testbash.sh');//need to pass variable 'fcn2'
    chdir($old_path);
    }

So the bash script need to change as below,

     #!/bin/bash
//If variable fcn1 received
    echo "Hello World!! fcn1 has executed.."

//If variable fcn2 received
    echo "Hello World!! fcn2 has executed.."

Solution

EXAMPLE

Just put your variable(s) after the call --

$output = shell_exec('./testbash.sh your_var_1 your_var_2');

Then in your bash script:

#!/bin/bash

var1=$1
var2=$2

echo "Hello World, var 1 is $var1 and var 2 is $var2"

UPDATE

So your function would look like:

function fcn2() {
    $old_path = getcwd();
    chdir('/home/svradmin/scripts');
    $var = "Hello Hello";
    // Or as Fravadona suggested:
    $var = escapeshellarg("Hello Hello");
    $output = shell_exec("./testbash.sh $var");
    chdir($old_path);
    return $output;
}

function fcn1() {
    $old_path = getcwd();
    chdir('/home/svradmin/scripts');
    $var = "Hello";
    // Or as Fravadona suggested:
    $var = escapeshellarg("Hello");
    $output = shell_exec("./testbash.sh $var");
    chdir($old_path);
    return $output;
}

echo fcn1();
echo fcn2();

And your bash ..

#!/bin/bash

var=$1

echo "Hello World!! $var has executed.."


Answered By - Zak
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing