【问题标题】:How to pass PHP variables to Shell?如何将 PHP 变量传递给 Shell?
【发布时间】:2014-12-23 19:41:06
【问题描述】:

我有两个文件:

wget.php

<?php
include 'theme.php';
/*ceklogin();*/
css();
if($_POST['wget-send'])
    {
        $dir=$_POST['dir'];
        $link=$_POST['link'];
        exec('touch /tmp/wget-download-link.txt',$out);
        exec('echo "'.$link.'" >> /tmp/wget-download-link.txt',$out);
        exec('/www/wget_download.sh,$out);
        echo $out[2];
        exit();
    }
echo "<form action=\"".$PHP_SELF."\" method=\"post\">";
echo "Download directory:<br><input type=\"text\" name=\"dir\" size=\"15\" value=\"/mnt/usb/\"/><br>";
echo '<br>Download link (one URL per line):<br>';
echo ("<textarea name=\"link\" rows=\"13\" cols=\"60\"></textarea><br><br>");
echo '<input type="submit" name="wget-send" value="Send" />';
echo "</form></div>";

foot();
echo '
</div>
</body>
</div>
</html>';
?>

wget_download.sh

while [ true ] ; do
    urlfile=$( ls /tmp/wget-download-link.txt | head -n 1 )
    if [ "$urlfile" = "" ] ; then
        sleep 30
        continue
    fi

    url=$( head -n 1 $urlfile )
    if [ "$url" = "" ] ; then
        mv $urlfile $urlfile.invalid
        continue
    fi

    mv $urlfile $urlfile.busy
    wget $url -o /tmp/wget.log -P $dir
    mv $urlfile.busy $urlfile.done
done

如何将变量从 PHP 中的 $dir 传递到 shell 中的 $dir?例如,我的 PHP 中的 $dir 是: /mnt/usb

我希望/mnt/usbwget_download.sh 中执行,所以它会是这样的:

wget $url -o /tmp/wget.log -P /mnt/usb

我该怎么做?

【问题讨论】:

  • 你可以把它写在一个文件中,然后通过shell读取它。我不确定你想在 shell 中使用表单来实现什么。

标签: php shell


【解决方案1】:

首先,这是非常非常危险的。确保您完全信任任何能够通过在您的服务器上运行任意命令来访问您的站点的人。我建议确保 SSL 和正确的密码身份验证。

除此之外,您可以通过putenv("DIR=".$dir); 联系我们,请参阅“http://php.net/manual/en/function.putenv.php”了解可能需要的限制和配置列表。您可能需要在 php 和 shell 脚本中为变量名称添加前缀“PHP_”。

【讨论】:

    【解决方案2】:

    我第二次丹尼尔斯警告。也就是说,我只会将其作为参数传递:

    dir="$1"
    
    while [ true ] ; do
        urlfile=$( ls /tmp/wget-download-link.txt | head -n 1 )
        if [ "$urlfile" = "" ] ; then
            sleep 30
            continue
        fi
    
        url=$( head -n 1 $urlfile )
        if [ "$url" = "" ] ; then
            mv $urlfile $urlfile.invalid
            continue
        fi
    
        mv $urlfile $urlfile.busy
        wget $url -o /tmp/wget.log -P $dir
        mv $urlfile.busy $urlfile.done
    done
    

    这会改变你的 exec 调用:

    // the command would actually look like:
    // /www/wget_download.sh /path/to/dir
    exec('/www/wget_download.sh ' . escapeshellarg($dir),$out);
    

    【讨论】: