Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling php scripts inside ruby code

I want to call a php scripts from my ruby code. From ruby it needs to pass the arguments to php as command line arguments. But for argument with spaces it is treating it as command.

For example:

result = 'php sample.php "#{name}" "#{location}"'

It is returning

sh: line 1: Blahh Blahh: command not found
sh: line 2: Some more Blahh: command not found

Can anyone tell how to pass ruby string as argument??

like image 537
protocolon Avatar asked Jul 23 '26 13:07

protocolon


1 Answers

You can use the backticks syntax to make system calls.

But the issue is really that you need to pass the -f option to PHP to tell PHP to execute a file instead of trying to run the command line arguments.

test.rb:

path = File.dirname(__FILE__) + '/'
args = ['arg1', 'arg2']
puts `php -f #{ path + 'sample.php'} { args.join(' ') }`

sample.php

<?php 
if (isset($argv)){
 print_r($argv);
}

Output:

Array
(
    [0] => ./sample.php
    [1] => arg1
    [2] => arg2
)

Edit

You can also use the StdLib component Shellwords to escape and quote the arguments for you:

require 'shellwords'
path = File.dirname(__FILE__) + '/'
args = ['arg1', 'arg2 asdas']
puts `php -e #{ path + 'test.php'} #{ Shellwords.join(args) }`

Output

Array
(
    [0] => ./test.php
    [1] => arg1
    [2] => arg2 asdas
)
like image 99
max Avatar answered Jul 26 '26 03:07

max



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!