开发者

Why would file_put_contents() succeed but touch() fail?

开发者 https://www.devze.com 2022-12-10 18:27 出处:网络
I\'m running a script that makes some changes to the contents of a file then resets its modification time to what it was before.Intermittently, I\'ll find the following errors in my log:

I'm running a script that makes some changes to the contents of a file then resets its modification time to what it was before. Intermittently, I'll find the following errors in my log:

开发者_开发百科
touch() [function.touch]: Utime
failed: Operation not permitted

This on the line immediately after a file_put_contents() call appears to have changed the contents of the file I tried to touch(). There are no errors associated with the file_put_contents() line.

Has anyone had this happen? Can anyone figure out what set of permissions would allow me to write a file but not change its modification time? I'm doing this on Linux.


This is a bug with PHP's touch command. Even if you have write permission to the file, it fails if PHP isn't also the "owner".

If you're using Apache and Linux, use this command on your server's console to make PHP the file's owner:

sudo chown www-data:www-data /YourPATH/YourFILE

Better still, update the entire folder containing files you want PHP to control:

sudo chown -R www-data:www-data /YourPATH/YourFOLDER

Side Note: Because PHP can write to the file, that means it must have user or group write permission. Since that's the case, touch should not behave this way. It seems like a bug.


It could be possible that the file gets created with wrong permissions. Try to chmod 777 the file just after the file_put_contents and then touch the file.


As rossoft says, PHP is probably not the owner of the file. But setting the permissions to 777 might not be the best solution. I'd preferr:

function touch_file($file) {
    fclose(fopen($file, 'a'));
}

touch_file('/path/to/file');


Only recently, I've had a similar problem and I think I know the answer.

The actual purpose of touch() is to update the modification and access times of a file. Creating the file is just a side-effect.

If you're using Linux, but writing to an NTFS partition as you might with a dual-boot configuration, depending on how the partition is mounted, touch() might have problems changing the access time on files. The file will be created, but touch() will still fail because the underlying system returns an error status. The same thing can be observed from the command line where you'll get a "permission denied" message.

There doesn't seem to be any documentation regarding this in the man pages for mount, ntfs-3g, or touch (Linux command), but the problem is mentioned in the comments on the touch() PHP function page.

Tweaking mount options might provide a solution, but you're better off using is_writable() to check permissions and fopen() to create files.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号