簡體   English   中英

在 php 文件上調用 exec 並傳遞參數?

[英]calling exec on a php file and passing parameters?

我想使用exec調用 php 文件。

當我調用它時,我希望能夠通過(一個id)傳遞一個變量。

我可以調用echo exec("php /var/www/unity/src/emailer.php"); 很好,但是當我添加類似echo exec("php /var/www/unity/src/emailer.php?id=123"); exec 調用失敗。

我怎樣才能做到這一點?

您的呼叫失敗,因為您使用的是帶有命令行調用的 web 樣式語法 ( ?parameter=value )。 我明白你在想什么,但它根本行不通。

你會想要使用$argv來代替。 請參閱PHP 手冊

要查看實際情況,請將此單行代碼寫入文件:

<?php print_r($argv); ?>

然后使用 arguments 從命令行調用它:

php -f /path/to/the/file.php firstparam secondparam

您將看到$argv包含腳本本身的名稱作為元素零,后跟您傳入的任何其他參數。

這個改編的腳本顯示了從 php exec 命令將參數傳遞給 php 腳本的 2 種方法:CALLING SCRIPT

<?php 
$fileName = '/var/www/ztest/helloworld.php 12';
$options = 'target=13';
exec ("/usr/bin/php -f {$fileName} {$options} > /var/www/ztest/log01.txt 2>&1 &");

echo "ended the calling script"; 
?>

調用腳本

<?php
echo "argv params: ";
print_r($argv); 
if ($argv[1]) {echo "got the size right, wilbur!  argv element 1: ".$argv[1];}
?> 

不要忘記驗證執行權限並創建具有寫入權限的 log01.txt 文件(您的 apache 用戶通常是 www-data)。

結果

argv 參數:數組

(

[0] => /var/www/ztest/helloworld.php

[1] => 12

[2] => target=13

)

尺寸合適,wilburargv 元素 1:12

選擇您喜歡的任何解決方案來傳遞參數,您需要做的就是訪問 argv 數組並按照傳遞的順序檢索它們(文件名是 0 元素)。

謝謝@hakre

試試echo exec("php /var/www/unity/src/emailer.php 123"); 然后在你的腳本中讀入命令行參數

如果您想向其傳遞 GET 參數,則必須提供php-cgi二進制文件以供調用:

exec("QUERY_STRING=id=123 php-cgi /var/www/emailer.php");

但這可能需要更多虛假的 CGI 環境變量。 因此,通常建議重寫被調用的腳本並讓它使用正常的命令行 arguments 並通過$_SERVER["argv"]讀取它們。

(您也可以通過在腳本頂部添加parse_str($_SERVER["QUERY_STRING"], $_GET);來使用普通的 php 解釋器和上面的示例來偽造 php-cgi 行為。)

我知道這是一個舊線程,但它幫助我解決了一個問題,所以我想提供一個擴展的解決方案。 我有一個 php 程序,該程序通常通過 web 接口調用,並獲取一長串參數。 我想使用 shell_exec() 在后台使用 cron 作業運行它,並將一長串參數傳遞給它。 每次運行時參數值都會發生變化。

這是我的解決方案:在調用程序中,我傳遞了一串參數,這些參數看起來就像 web 調用將在?之后發送的字符串。 例如:sky=blue&roses=red&sun=bright 等。在被調用的程序中,我檢查 $argv[1] 的存在,如果找到,我將字符串解析到 $_GET 數組中。 從那時起,程序讀取參數,就好像它們是從 web 調用中傳遞的一樣。

調用程序代碼:

$pars = escapeshellarg($pars); // must use escapeshellarg()
$output = shell_exec($php_path . ' path/called_program.php ' . $pars); // $pars is the parameter string

在讀取 $_GET 參數之前插入的調用程序代碼:

if(isset($argv[1])){ // if being called from the shell build a $_GET array from the string passed as $argv[1]
    $args = explode('&', $argv[1]); // explode the string into an array of Type=Value elements
    foreach($args as $arg){
        $TV = explode('=', $arg); // now explode each Type and Value into a 2 element array
        $_GET[$TV[0]] = $TV[1]; // set the indexes in the $_GET array
        }
    }
//------------------------
// from this point on the program processes the $_GET array normally just as if it were passed from a web call.

效果很好,並且需要對被調用程序進行最少的更改。 希望有人發現它的價值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM