open a file in PHP CLI - php

The file was created by apache using mkdir() and fopen() etc..
How do i let my php CLI program be allowed to read that file that apache (that is what it says the user is) created so i dont get this error:
Warning: file_get_contents(./sessions/nl2larsjl6n3315mesghmspts7.txt): failed to open stream: No such file or directory in /var/www/html/cli.php on line 58
in the cli this my code for getting the file:
$alert = file_get_contents('./sessions/'.$sessionID.'.txt');

Short answer:
when you create it, you should run chmod(0777) on it.
Long answer:
chmod(0777) means "world readable and writable, and not actually recommended. Checkout http://en.wikipedia.org/wiki/Filesystem_permissions, http://www.linuxforums.org/articles/file-permissions_94.html for a complete explanation on these numbers.
Basically if you need it to be writable by a user, and readable by any user, do a chmod(0644)
EDit: i was quick to wrinte an answer... without reading the question carefully.
You seem to try and open the file from a different directory than the folder where you created it.
Try and see the result on echo getpwd() in the CLI script and then in the script running under www. I bet you will see different locations.
When executing CLI scripts you should either do a chdir() before running the command or use absolute paths at all times for the files you access.
I personally prefer the chdir() method.

Related

Issue with calling php script with cron

I have set up a cron to call a php script to run some download tasks at a regular interval.
The website is hosted at Bluehost. I have followed the instructions on how to set up a cron and that basically works fine, but the behaviour is different from when calling the script manually which i suspect has to do with directory settings. When using the cron i get errors:
Warning: copy(wp-content/uploads/feeds/full/1.csv): failed to open stream: No such file or directory in /home1/user1/public_html/import/custom-downloader.php on line 86
my php code is copy( $row["externalURL"] , 'wp-content/uploads/feeds/full/'. $localfilename );
I have also tried below with same result.
copy( $row["externalURL"] , $_SERVER['DOCUMENT_ROOT'].'wp-content/uploads/feeds/full/'. $localfilename );
I think think that i need to construct the path to /home1/user1/public_html/import/wp-content/uploads/feeds/full/ but i don't see how to do that.
First thing's first, make sure that 1.csv exists and that it can be read (there's read permissions on the file)
Second thing, double check if 'wp-content/uploads/feeds/full/1.csv' really is what you want to copy. Your error message indicates that the php script calling the copy method is /home1/user1/public_html/import/custom-downloader.php. However, the path you specified is relative. So your PHP script (barring any changes to the PATH to look for other directories) will look for /home1/user1/public_html/import/wp-content/uploads/feeds/full/1.csv -- which may not be what you intended!
This can be solved by using an absolute path to your wp-content folder, or by moving this script to the parent directory of wp-content.

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.

Executing a linux command with php exec() and running a shell script

i am trying to run this piece of php code on my server:
<?php
$cmd = 'echo "this is a test" > /home/ubuntu/scripts/test_file';
echo exec($cmd);
?>
From my understanding it should add the piece of text to the file test_file . The file exists in the appropriate location and i have tried chmod 755 and chmod 777 on the php file. But i dont see the text being added to the text_file . I tried running the linux command directly on the server and it works. Could some one tell me what i am doing wrong?
Also, i am trying to create a virtual host file on the server through a php script. Rather than running the commands through php exec() , i thought it would be better to run a shell script, with the shell script reading the required parameters from a text file and setting the directory path in the virtual host file. I am new to linux, is this a good approach or is there a better way in going about this? All this is being done to setup a magento based site programatically. Thanks.
Your code is OK. The problem probably either lies with your php being in safe mode (though it's deprecated, see link) or with file/directory permissions.
No need to give the file permissions 0777 since that makes the file executable, 0666 should suffice. It is not enough however for the file to have the right permissions, each directory on the path must be traversable. Try a different directory to which the user with whose privileges the php code runs has access, /tmp is a good start.
General way to debug problems like this is to execute a different command which gives you extra information about the context in which echo is executed, e.g.
<?php
echo exec("id");
echo "<br/>";
echo exec("ls -l /home/ubuntu/scripts/test_file");
?>
(remember exec() only returns the last line of command's output, these display just one line though). These commands will tell you the user which runs the code and whether they can see the file at all.
As the comment already said: this is actually bad way to accomplish what you're trying to do, as writing Apache configuration based on user input through web could open you up to multiple issues.
What you might consider, is to have the PHP side write the required information to a file, or a database, which is then polled every now and then via a cron script or similar by a different process that does the actual configuration changes. This eliminates the need to exec() from PHP (which is always bad). With this, your process that runs PHP wouldn't need to have write permissions to important system files.

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

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

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.

Categories