2012-08-07 24 views
1

我想在PHP運行這一點,但它並沒有因爲行情的工作....我需要使用單引號兩次 - 如何逃脫?

$cmd="sudo -u postgres sh -c 'psql -c \"alter user edumate with encrypted password \'BLAH_BLAH\';\" template1 2>&1' "; 
    $shellOutput = exec($cmd, $output); 

psql -c "alter user edumate with encrypted password 'BLAH_BLAH';" template1 2>&1作爲Postgres的用戶運行時執行確定。

我試過了,但它對我不起作用。

sudo -u postgres sh -c 'psql -c \"alter user edumate with encrypted password \'BLAH_BLAH\';\" template1 2>&1' 
sudo -u postgres sh -c 'psql -c "alter user edumate with encrypted password \'BLAH_BLAH\';" template1 2>&1' 

我該如何逃避$ cmd才能執行它?

更新我

$subcommand="alter user edumate with encrypted password 'BLAH_BLAH';"; 
    $sub = escapeshellarg($subcommand); 
    $cmd="sudo -u postgres sh -c 'psql -c \"".$sub."\" template1 2>&1'"; 
    $shellOutput = exec($cmd, $output); 
    echo "<pre>Output = " . print_r($output,1) . "</pre>"; 

回報

Output = Array 
(
) 

更新II

感謝@Hawili的工作代碼。我想知道如何使用sh -c命令來運行,他省略了。

$shellOutput=`sudo -u postgres psql -c "alter user edumate with encrypted password 'BLAH_BLAH';" template1 2>&1`; 
+0

不需要\'當用字符串「 – Teson 2012-08-07 06:16:34

+0

@ user247245封裝:您能詳細說明還是提供確切的語法? – Radek 2012-08-07 06:20:28

回答

1

可以使用反引號`這是使用PHP執行命令直接進入外殼

例如:

$output = `ls -l`; 

你的情況可能是這樣的:

$shellOutput=`sudo -u postgres psql -c "alter user edumate with encrypted password 'BLAH_BLAH';" template1 2>&1`; 
+0

它什麼都沒有返回。沒有錯誤,沒有輸出。 – Radek 2012-08-07 06:42:45

+0

?檢查我在'ls -l'之前發佈的簡單示例是否適合您? – Hawili 2012-08-07 06:44:10

+0

是的,一些簡單的作品。 – Radek 2012-08-07 06:47:10

2
+0

escapeshellarg也可能工作得很好。所以$ sub = escapeshellarg($ subcommand); $ cmd =「sudo -u postgres sh -c $ sub」; – EPB 2012-08-07 06:19:07

+0

@EPB:在我的問題中查看'更新I'。 – Radek 2012-08-07 07:03:23

+0

$ subcommand ='psql -c「使用加密密碼更改用戶edumate \'BLAH_BLAH \';」 template1 2> &1'; $ sub = escapeshellarg($ subcommand); $ cmd =「sudo -u postgres sh -c $ sub」;因爲整個psql命令基本上是sh的一個參數。 – EPB 2012-08-07 16:26:20