PHP Cannot write to file even though it has 777 permissions - php

Im trying to make a php file write to a file that resides in the same folder. Both the php file and the file its trying to write to have their permissions set to 777 (its a linux server) as well as the folder they reside in. Whenever I called fopen() with the 'w' or 'w+' mode, the function just returns false. Its on my school's webserver, so there is no way I can get root access to change the owner of the file to the same user as apache. Does anyone know whats wrong?
Update:
As a test, I was using this code:
$handle = fopen("test.txt", 'w');
if($handle === FALSE)
echo "\nfailed";
else
echo "\nsuccess";
fclose($handle);
The output now with error reporting enabled is:
Warning: fopen(test.txt) [function.fopen]: failed to open stream: Permission denied in /<snip>/public_html/test.php on line 58
failed
Warning: fclose(): supplied argument is not a valid stream resource in /<snip>/public_html/test.php on line 63
Above that is some code I copied from the php website for the fileperms() function which checks the permissions of the text file, and its reporting -rwxrwxrwx
The ls -al output of the relevant files is
ls -al *test*
-rwxrwxrwx 1 mag5 30 1475 Dec 9 00:02 test.php*
-rwxrwxrwx 1 mag5 30 8 Dec 8 14:54 test.txt*
Also Im not sure if this matters, but my school uses something called the Andrew File system (http://en.wikipedia.org/wiki/Andrew_File_System).

Telanor, AFS is a very big clue.
AFS (Andrew File System) has a whole level of directory permissions beyond that of traditional unix filesystems. Check AFS permissions on the directory to make sure you have the ability to access files in the directory. Also it may not be your permissions that matter, but the permissions of the webserver (or rather the userid it's running under). It's been a long time since I used AFS so I don't know the commands offhand to check directory permissions.

Do this instead:
$fh = fopen($filename, "a");
I imagine the problem is that you don't have the correct permissions for the directory. When you attempt to delete a file you need write permission in the directory and "w" will do that.
Alternatively, if you need to truncate/delete the file, change the directory permission so you have write permissions.

More than likely php is not running as the same user as the owner of the file. Have you tried creating a new file in the directory using php (just make a randomly named file in the same directory)?

There's a couple reasons this could fail. Based on the information around, it isn't a problem with file permissions. The first, and possibly most likely, is that your web server is running in a configuration that it has read-only access to the entire filesystem. This could be because NFS is mounted read-only, or because PHP or the server is configured in such a way as to prevent writing.
Also, please, never set a file to be 777. Even 666 is dangerous enough. This is especially true in a shared environment like a school server.
At this point, assuming you have limited control over the server environment, you should ask your administrator for more information.

It is like MadCoder says.
From the AFS Docs:
AFS ACLs work in conjunction with the standard Unix "owner" permissions. Only the owner permissions have an effect on AFS file access; Unix permissions for "group" and "other" do not affect AFS file access.
These rules apply. A user with appropriate AFS permissions can:
read a file only if the UNIX "owner read" mode is set.
write to a file only if the UNIX owner "read" and "write" modes are set.
execute a file only if the UNIX owner "read" and "execute" modes are set.
To set the AFS permissions, you need to use the fs setacl command.

Related

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?
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.
The return values of the file_get_contents method explains on the php manuel page as This function returns the number of bytes that were written to the file, or FALSE on failure. So file_get_contentsit's must be a return. First, you have to check this returns.
Second, you wants create a file to a folder that looks like has a permission only root user. Apache user has not root permission, so you can't write. Please check this url for permissions and I suggest to you be careful when you changing permission of folders.

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
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.

PHP: creates file but can't append with (apparently) correct server permissions (LAMP)

I have seen many questions and answers on this topic but none seem to help my situation. My PHP code is successfully creating a new logfile, but then cannot access that file to append further info, close it, etc.
I am migrating an application from local XAMPP onto LAMP: hence problem only showing up now due to Windows/XAMPP giving no permission troubles.
I started with a default Bitnami LAMP stack, and then manually setup relevant directory permissions on server:
- my sftp user has rwx on htdocs and assorted out-of-web-root directories
- apache is running as 'daemon' so I have given read & execute permissions to relevant directories for 'daemon' as group
- in most directories I have disallowed write permissions for 'daemon'
- however for my (application generated, internal) logs I have a 'logfiles' directory which has rwx for both my user and the 'daemon' group
- 'other' is -rwx for all
When I run my application it falls over pretty much immediately. The error logs showing fopen failed to open stream: permission denied. However, the permissions indicate that it should have access.
When I check the file involved it has following permissions:
-rw-r--r-- 1 daemon daemon 962 Oct 3 10:14 20151003logfile03-10-33530.txt
This tells me that the file was created by Apache (i.e. by my PHP script) and that it has read and write permissions, from when I fopen() with "w"
EDIT: adding directory info:
Folder level permissions give my ftps user and daemon (group) full rwx access:
drwxrwx--- 2 ftpuser daemon 4096 Oct 3 10:30 logfiles
BUT it can't then fopen with "a"
I am assuming that this IS a file permission problem because:
a) it works fine on XAMPP
b) it states permission error in the error log
However, I can't see why it should be a problem, given directly-specified OS-level permissions ... maybe Apache requires an .htaccess 'allow' on this directory also?
Any ideas?
Clarification re why I don't think CHMOD is the answer (sorry #RedAcid):
CHMOD 777 etc is simply a way to set the underlying permissions I already have. Each digit represents 3 binary chars, so 7 is 111 (i.e. read, write and execute). As you can see above, I have read/write/execute for PHP/Apache on folder, together with read/write for file. What I've read suggests that you need execute at directory level, but not at file level because its not trying to execute the file.
So what am I missing here? Why else might it be denying permission?
use chmod 666 for the file and proper user group permissions. folder where files are located must be writable with chmod 777
OK - I found out the problem was higher level parent directory not having read/execute permissions. Now working! (AT LAST!)
For more detail see this previous question:
PHP fopen() fails on files even with wide-open permissions

php fopen fails to open a file for writing in Mac OS X

I'm running php script updreading.php locally on my laptop (with Mac OS X 10.6.7).
Here's the contents of updreading.php
<?php
$outFile = "examples-output.txt";
$out = fopen($outFile, 'w') or die("can't open write file");
?>
When I run it, I get "can't open write file" error message. I think it should have something to do with permissions. I've made myself (arman) an owner of /Library/WebServer/Documents/ with Read&Write permissions and 'applied settings to enclosed items'. My script and file I'm writing to (examples-output.txt) is located in /Library/WebServer/Documents/wabun/. Here are the permissions for files in /Library/WebServer/Documents/wabun/:
-rw-r--r--# 1 arman admin 0 May 1 01:03 examples-output.txt
-rw-r--r--# 1 arman staff 1657 May 1 01:04 updreading.php
I was trying to resolve the issue for the last 4 hours trying different permissions without luck. Any ideas how to resolve this issue, guys? Thanks!
I was having this exact same problem. I had to make sure the permissions were correct for all of the parent folders as well. For instance, if (in OSX) trying to write to the directory
~/foo/bar/baz, I solved it with the command chmod -R 777 ~/foo.
I bet the issue is that your webserver or PHP instance is not running under the same user (arman), you can check this using the get_current_user() function. You can either configure apache to run with your privileges (ask in ServerFault) or give the folder more generous permissions, like 0777.
Another thing, are you sure $outFile maps to an absolute path? Try doing:
var_dump(is_file($outfile));
you need to make apache (assuming apache is server you are using) the owner or put in group (and give group write access) or give write access to all or etc.. IOW apache is the one actually executing the script, not you.

test.php cannot output file into Leopard filesystem

may i know what permission do i need to add, to allow test.php to able to write file into macos filesystem
PHP Error: <br />
<b>Warning</b>: file_put_contents(20090915203127.jpg) [<a href='function.file-put-contents'>function.file-put-contents</a>]: failed to open stream: Permission denied in <b>/Library/WebServer/Documents/testphp/test.php</b> on line <b>8</b><br />
ERROR: Failed to write data to 20090915203127.jpg, check permissions
this is the error i get on leopard, i already chmod ugo+x for test.php
It's not the file that needs permissions, it's the process running PHP. Assuming you're using (Snow) Leopard in it's default state, you'll need to give the _www user write permissions to the given directory, or give the world write access (a less savoury idea). Both of these can be accomplished with a combination of chown and chmod.
You need to make sure the user the script is running under is allowed to write to the file trying to write to (i.e. 20090915203127.jpg, not the PHP script). If 20090915203127.jpg does not exist, you'll need to make sure the directory that file's going to is writable (by default this will be the present working directory).
You may need to read about chmod.
As far as I know you need root rights to be able to write directly to /Library. Is it absolutely necessary to write to this directory?
If you just write files to your own account, under /Users/accountname it should work (although that depends on the user who is executing the php script).
You need to make the target file / directory writable to the web server. test.php is not into that...

Categories