php - sudo_exec 什么都不返回

标签 php linux ping shell-exec

我尝试使用 shell_exec ping www.google.de 并将结果存储到一个变量中,但我没有从 shell_exec 返回任何结果.

<?php
    $ping           = 'sudo ping -c 4 ';
    $url            = 'www.google.de';

    $command        = $ping . $url;

    $ping_result    = shell_exec($command);

    $datei          = fopen("/var/www/myProject/result_ping","w") or die ("Could not open file!"); 
    sleep(10);

    if ($datei == false)
    {
        $ping_result = "Cannot open file!";
    }
    else
    {
        fwrite ($datei , $ping_result);
        fclose ($datei);
    }

    echo $command;      //Output:       sudo ping -c 4 www.google.de
    echo $ping_result;  //Output:       nothing
?>

文件 result_ping 拥有所有权限 (chmod 777)。 也许网络服务器不允许执行ping

最佳答案

2>&1 添加到您的命令中,以确保您不会收到 shell_exec 会过滤掉的错误消息:

$command        = $ping . $url . ' 2>&1';

shell_exec 将在出错时返回 NULL。通过该修改,您可以将任何错误消息重定向到正常输出,从而强制 shell_exec 显示您通常会在控制台 session 中收到的每条消息。

关于php - sudo_exec 什么都不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33646275/

相关文章:

php - 如何使用 PHP IMagick 将 CMYK/RGB TIFF 转换为 RGB JPEG

php - 如何为 get_headers PHP 函数设置用户代理

php - Zend MySQL 检查表是否存在

cocoa - 如何在 Objective-C/Cocoa 中执行 shell 命令 "ping"并将结果转换为字符串?

Perl - 如何使用 Ping 检查服务器是否在线?

php - 正在备份 MySQL 数据库...转义字符串的正确方法?

linux - gentoo geoip安装

c - 如何使用原始套接字 ping 本地主机?

linux - 当我在 Linux 上运行使用 Hard Float 选项构建的 Neon 代码时出现段错误

android - 为什么 ping 在某些设备上有效而在其他设备上无效?