Wednesday, February 11, 2015

PHP file_put_contents is not working on CentOS Linux

When I tried to use PHP to write the debug information to the /tmp directory, I've noticed that my data was not written to the file I have specified. I was wondering why my file was not created, or it's empty. My first assumption was because of SELinux (tail -F /var/log/audit/audit.log). However, it has nothing to do with SELinux. It turned out that both Apache and PHP-FPM use a private /tmp directory. So, the location would be:

/tmp/systemd-private-<uuid>/debug1

instead of:

/tmp/debug1

Note: this is only important if you want to access the files from outside apache.

Sample PHP code:

<?php
$date = date('Y-m-d H:i:s');
$fileName = '/tmp/debug1';

echo $date;
echo "<br>\n";

$charCount = file_put_contents($fileName, 'test message ' . $date);
echo $charCount . ' characters written';
echo "<br>\n";

$str = file_get_contents($fileName);
echo $str;
echo "<br>\n";
?>

Find the debug log file:

# find /tmp -type f -mmin -500 | xargs -I {} ls -l {}

Note: if you run the sample PHP script above through command line, the debug1 would be stored in /tmp/debug1.

Note: if you run the sample PHP script above through the browser, the debug1 would be stored in /tmp/systemd-private-<uuid>/debug1.

The Private Tmp setting are defined in systemd service files:

# grep -ri 'PrivateTmp' /usr/lib/systemd/system

Reference:

http://0pointer.de/blog/projects/security.html

http://blog.oddbit.com/2012/11/05/fedora-private-tmp/

http://danwalsh.livejournal.com/51459.html

No comments: