Skip to content
Advertisement

PHP fopen ‘x+’ doesn’t work on ubuntu

I created an application which has an caching script on an Windows/Wamp environment. This script’s caching function is only allowed to run once at the same time.

To achieve this I used a ‘locking file’ with check to see if it exists.

On windows this script continues to work fine. But now it is moved to an Ubuntu environment is doesn’t work.

<?php
    date_default_timezone_set('Europe/Amsterdam');
    ini_set('max_execution_time', 300);
    ignore_user_abort(true);

    $path = 'locked.txt';

    if ($lock = fopen($path,'x+')) {
        fwrite($lock,time());
        fclose($lock);
        sleep(10);
        unlink($path);
    }
?>

Error: fopen(locked.txt): failed to open stream: Permission denied

Advertisement

Answer

From the PHP documentation (paraphrased a bit):

x+ Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.

From your description you are attempting to use a file as a lock file using the “x+” flag to ensure you’re not locking a file already locked.

The problem is that migrating from windows to *NIX systems (like Ubuntu) you will need to familiarise yourself with the difference in the permissions system.

The short story is:

Each file and folder “belongs” to a user.

The user who wants to create a file in a directory needs at least an execute and write permission on that directory.

Having this in mind you need to ensure that the current user has write and execute permissions on the directory with the script and to actually execute the script they will also need read permissions on the directory (in addition to read permissions on the script). Ensure that the directory has read-write-execute permissions (flag no. 7) for the user running the script.

If you’re running the script via a web interface this user will be www-data .

In general chmod 777 /directory/with/script should work and grant read-write-execute permissions on the directory for all users.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement