PHP Accessing a file that has been locked for editing - Permission Denied error
-
18-03-2021 - |
Вопрос
I'm doing some csv parsing, and if I cancel the parsing (by navigating to a different page or refreshing) before the fclose() function gets called, I get the below error when I go back and start up the program again:
Warning: unlink(spreadsheet.csv) [function.unlink]: Permission denied
When I try to open the spreadsheet.csv file in excel, I get a "File in Use" error, saying "spreadsheet.csv is locked for editing by 'another user.'" I understand that my php server is currently stuck in a state of trying to access the file. Is there a way I can use php to check if the file is locked for editing, and unlock it?
Решение
You can try to unlock a file with php like this:
$rFile = fopen("path/file.txt", "r+");
flock($rFile, LOCK_UN);
fclose($rFile);
And the best way to get read-write access to the file is this:
$iOldumask = umask(0);
chmod("path/file.txt", 0777);
umask($iOldumask);
Другие советы
Take a look at flock().
I use it like:
if (!$file->flock(LOCK_EX)) {
throw new Exception('Unable to obtain lock on file');
}
Не связан с StackOverflow