phpfile-put-contents

Why can't write info into /tmp directory instead of /var/www/html?


LAMP installed on my local pc, as I know the string xxxx can be written into /tmp/test with below PHP function.

file_put_contents("/tmp/test","test1 test2") 

cat ajax_get.php

<?php
    $str = "test1 test2";
    ini_set('display_errors', 1);
    error_reporting(E_ALL);
    $str = implode(" ",$_GET);
    file_put_contents("/tmp/test",$str);
    print($str);
?>

Why the command file_put_contents("/tmp/test",$str); in ajax_get.php can't work?

It is no use to replace file_put_contents with

$handle=fopen("/tmp/test","w");
fwrite($handle,$str);
fclose($handle);

Maybe it is an issue on directory permission, if I change below statement in ajax_get.php

    file_put_contents("/tmp/test",$str);

Into

    file_put_contents("test",$str);

And run the previous process, ajax_get.php create a file in /var/www/html/test

cat /var/www/html/test
test1 test2

Show the permission for /tmp directory.

ls -al /tmp
total 76
drwxrwxrwt 16 root    root    12288 Dec 10 18:39 .
drwxr-xr-x 23 root    root     4096 Dec  1 08:03 ..

. is the current directory /tmp, its permission is 777 (rwxrwxrwx), why can't write file into /tmp directory by PHP?


Solution

  • You are not sharing with us the return of file_put_contents("/tmp/test",$str);, but I'm going to assume that you are actually writing the appropriate bytes.

    Being that the case, and considering the permissions look OK and that you don't say that are getting an error message, the most likely scenario is a problem with systemd configuration.

    Your Apache/PHP process are writing to that location correctly, but systemd has a configuration setting that allows for each process to have its own /tmp directory.

    PrivateTmp=
        Takes a boolean argument. If true sets up a new file system
         namespace for the executed processes and mounts a 
         private /tmp directory inside it, that is not shared by     
         processes outside of the namespace. This is useful to secure 
         access to temporary files of the process, but makes sharing
         between processes via /tmp impossible. 
    
    Defaults to false.
    

    In this case, the tmp you see as a regular or root user is not the same tmp directory that apache/php sees. Read more about this here, for example.

    You could disable the PrivateTmp setting for Apache, but I think it would be easier to choose a different path to store your files, and give the apache/PHP process permission to write there.

    There could be other possible explanations for not being able to write to tmp despite the directory permissions: e.g. that that directory was not added to the open_basedir directive, or that somehow the directory immutable attribute got set (very unlikely for /tmp). But in any of these cases, you would be getting an error message.