php file_get_contents(“/ tmp / some_file”)不能运行php7.1

时间:2018-01-29 06:39:45

标签: php apache php-7.1

我在阅读/tmp/some_file文件时遇到了一个奇怪的问题。

  • 我的PHP版本 7.1.13-1 + ubuntu16.04.1 + deb.sury.org + 1
  • 服务器版本:Apache / 2.4.29(Ubuntu)服务器内置:2018-01-14T11:23:59

  • 文件/tmp/some_file肯定是0777

file_exists("/tmp/some_file")file_get_contents("/tmp/some_file")都返回 false

我试过了

$data =  file_get_contents("/tmp/some_file");
var_dump($data); //is false

// OR even this code outputs: Unable to open the file!
$myfile = fopen("/tmp/some_file", "r") or die("Unable to open the file!");
echo fread($myfile,filesize("/tmp/some_file"));
fclose($myfile);

上述代码均无效,我也没有收到任何错误消息。 当我使用www-data模式在终端中使用php -a用户执行PHP代码或直接运行php myfile.php时,所有上述功能都正常工作,文件通常会被读取。

有没有有效的方法来调试它,或者它与PHP版本有某种关系?

---更新---

经过一番挖掘后,我发现任何其他文件直接正常读取。似乎问题出在/tmp目录,但is_readable("/tmp")返回true而file_exists("/tmp/some_file")仍然返回false ...

3 个答案:

答案 0 :(得分:1)

我在这里找到了问题答案:https://serverfault.com/questions/614781/php-script-cant-access-tmp-folder?newreg=e8651c2bcaea4a718a38f4e1dc94805b

ubuntu 16.04apache有关。对于此配置文件/etc/systemd/system/multi-user.target.wants/apache2.service中的apache服务 PrivateTmp = true

这就是为什么在通过浏览器执行php文件时+ apache结果为false并且通过终端它是真的,因为在生成没有/ tmp / some_file存在的apache执行virtal / tmp目录的情况下

答案 1 :(得分:0)

尝试error_get_last()

  

获取上次发生的错误

例如:

$fp = fopen("/tmp/some_file", "r");
if($fp === false){
    print_r(error_get_last());
}

echo fread($myfile,filesize("/tmp/some_file"));
fclose($myfile);

或者

#include <stdbool.h>

/*
 * Register a function to be executed on event. A function may only be registered once.
 * Input:
 *   arg - function pointer
 * Returns:
 *   true on successful registration, false if the function is already registered.
 */
bool register_function_for_event(void (*arg)(void));

/*
 * Un-register a function previously registered for execution on event.
 * Input:
 *   arg - function pointer
 * Returns:
 *   true on successful un-registration, false if the function was not registered.
 */
bool unregister_function_for_event(void (*arg)(void));

答案 2 :(得分:0)

我尝试了“ multi-user.target.wants”解决方案,该解决方案已经奏效,但是在重新启动之后,但是在某些时候,PrivateTmp恢复为true。 就像我对Apache2的主要使用是PHP一样,我终于编辑了php.ini,并且取消了sys_temp_dir行的注释。

默认情况下,系统使用由函数sys_get_temp_dir分配的temp dir。函数sys_get_temp_dir将返回“ / tmp”,但事实是您的tmp文件存储在/tmp/systemd-private-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-apache2.service-YYYYYY//tmp/*这样的路径下。所以,对我来说工作是:

编辑php.ini(路径可以在PHP版本之间更改)

sudo nano /etc/php/7.2/cli/php.ini

然后取消注释sys_temp_dir行

; Directory where the temporary files should be placed.
; Defaults to the system default (see sys_get_temp_dir)
sys_temp_dir = "/tmp"