I make a site map, and make it with php file, that generate it from mysql. I change host and now I have problem with writing into file. I can't understand something.
Here is my example:
<?php
$xml = 'bla bla xml'; //... some xml generating code
$fp = fopen($_SERVER['DOCUMENT_ROOT'].'/my_site_map.xml', 'w');
if($fp)
echo 'we opened it';
else
echo 'we failed';
$fwrite=fwrite($fp, $xml, strlen($xml));
if($fwrite==false)
echo "another fail";
fclose($fp);
echo "we done";
?>
The question is: my file my_site_map.xml have a permission 664 (rw-rw-r--), and I can't use this script if I open this php page from browser, so, if I try to do this I'll see: "we failed another fail we done"; But if I open this through crontab and see a log file, I can see this: "we opened it we done". I want exactly this but the main problem is that the file isn't have been rewritten. Why? And how can I fix this? Thanks.
My server is nginx not an Apache, didn't thought that this info will valuable
Well I don't have enough rep to comment so this will have to be an answer.
I'm going to take a stab in the dark and say the file is owned by your user or root, not the process that is running the webserver. Nor is the file owned by the group the webserver process is run under.
So either chown/chgrp the file to be owned by the apache(?!) process running, e.g. chown apache file or set the file to have write permissions to everyone, e.g. chmod 666 file
Don't chmod 777 as commented above unless it's an executable file and you want anyone to be able to run it. The 1st solution is a better practice than just giving anyone read access to a file.
Edit: In comment to the comments on the original answer above, if the file isn't an executable then don't give it 7 for any permisions. 6 is read/write and is suitable for a text file you are opening to write to (even 2 is if it comes to that).
Edit 2: Try catching any exceptions that your fopen function runs in a try catch block:
try {
$fp = fopen($_SERVER['DOCUMENT_ROOT'].'/my_site_map.xml', 'w');
} catch (Exception $e) {
echo "The error is" . $e->getMessage();
}
For PHP code here are the links to change it on the fly. You can change it to what ever make your edits then change it back as needed.
http://php.net/manual/en/function.chmod.php
http://php.net/manual/en/function.chown.php
http://php.net/manual/en/function.chgrp.php
Examples are included on each link with the documentations. Find the permissions that works best for what your doing. There isn't a one size fits all for permissions since it really depends on your end product (web app, page, what ever).
Related
I have this stupid little test PHP script running on a Ubuntu system inside an instance of a virtual server (Oracle Virtual Box) running on my pc:
<?
error_reporting(E_ALL);
ini_set('display_errors', 1); // show errors
echo "<p>test</p>";
$filename = "andy.txt";
$fh = fopen($filename, 'w') or die('fopen failed');
fwrite($fh, "qwerty") or die('fwrite failed');
fclose($fh);
?>
Despite all appropriate directory and file permissions being set, it is failing on the fwrite. The fopen works and creates the file, so write access is clearly enabled, but the fwrite dies, and the 'fwrite failed' message is output (no other error output is displayed).
The same script works perfectly well when I upload to my real server, so I am completely stumped as to why it won't write to the file; maybe it's something about my virtual server that is causing the problem.
Seems like such a pathetic thing, but it's driving me nuts! Considerable time Googling has failed to yield an answer, so can anybody here please provide some insight? Many thanks.
Not sure why the fwrite() call would die, as it returns the number of bytes written.
That said, have you tried with file_put_contents() instead? It's a simpler way of writing to a file, and is the recommended way since early PHP 5.
With it you only need to do the following
$filename = "andy.txt";
if(!file_put_contents ($contents, $filename)) {
// Write failed!
}
No need to bother with opening and closing the file pointer, as that's automatically handled by the function. :)
Solved! It was a disk space error on my virtual server. At the back of my mind, I knew I had seen this mentioned elsewhere as an issue with write fails, but in this case I failed to make the connection.
#ChristianF Thanks! Switching to file_put_contents() was very helpful, since it also failed, but gave me a meaningful error message:
'file_put_contents(): Only 0 of 6 bytes written, possibly out of free disk space'
Aha! Having recalled that growing log files can be a problem, I took it upon myself to delete everything inside /var/log (after saving them) and Presto! it now works! So, thank you for that tip - I will switch to using file_put_contents from now on. BTW: The contents of error.log itself was 2GB, while the remaining size of everything else in /var/log was only about 15MB, but deleting error.log by itself did not work, so I deleted everything.
#Clayton Smith Thank you, but removing the "or die('fwrite failed')" part did not result in any further error info - which is what is so frustrating: It's a shame that those error reporting directives at the start of the script didn't seem to do much.
#NaeiKinDus Thank you, but I don't think I have SELinux running (I'm afraid I don't know anything about this). Although I have a /etc/selinux directory present, there's no config file in it, just what appears to be a skeleton semanage.conf - whatever that is. Commands such as sestatus are not recognised.
I am wrestling with a problem. I stripped the example to this script that can be run as stand-alone application:
<?php
if(file_exists("x")){
print "<div>Deleting dir</dir>";
rmdir("x");
} else {
print "<div>Not exists</dir>";
}
clearstatcache();
mkdir("x");
If I call it repeatedly (F5 in browser) then sometimes this error occurs:
Deleting dir
Warning: mkdir(): Permission denied in F:\EclipseWorkspaces\Ramses\www\deploy\stripped_example.php on line 9
10-20 times it works OK and next time this error occurs. I googled more users has this problem but without solution.
https://github.com/getgrav/grav/issues/467
My example creates the directory in cwd, where anybody has full control. In addition the mkdir $mode parameter is ignored in windows. After the error the "x" directory truly not exists and in next attempt (F5) it is always created without error. I hopped later added "clearstatcache()" will help but nope.
In my full application I am using full file path. The deleted directory is not empty and I must clean it first. After successfull deleting the error occurs almost always.
My system is Windows 7, PHP 7.0.5, Apache 2.4
Windows doesn't let you delete things if another process is accessing them.
Check if your antivirus or some other process is opening the folder.
You can check this in resource monitor, from task manager.
Try the code with additional check on existing:
<?php
if(is_dir("x")){
print "<div>Deleting dir</dir>";
rmdir("x");
} else {
print "<div>Not exists</dir>";
}
clearstatcache();
if (!is_dir("x")) {
mkdir("x");
}
Had the same problem with Windows 10, Xampp and PHP 7. Problem was Kaspersky Internet Security, scanning and blocking the directory. Disabling KIS mkdir always works for me. Instead of directly recreating you can try rename, if disabling security software is not an option for you.
$time = time();
mkdir($path . $time);
rename($path . $time, $path);
juste delete espace name folder with Function Trim in php
I had a Apache HTTP server on CentOS, I installed PHP (yum install php) and then tested a simple script that writes text in a file, so I do
$file = fopen($filename,"w") or die("Failure");
The problem is that it's always a failure, even after I did a chown apache:apache /var/www/html/* or a chmod 777 * in that directory, so anyone knows a way to understand / fix this?
EDIT : So there the problem was thath the directory itself did'nt have the chown
It's hard to say what it is without the actual error message from PHP.
Have a look at this page:
http://www.w3schools.com/php/php_error.asp
Long story short, create and set a custom error handler, like so:
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr";
}
//set error handler
set_error_handler("customError");
//trigger error
$file = fopen($filename,"w")
?>
In your case, I think that in order for it to be able to create new files in the given directory, you would want to add a '-R' flag to chmod or chown and call it on the directory itself rather than the children -- that way, if PHP has to create the file, it has permissions to do so.
EDIT: Just curious about why this has a downvote -- what is the "egregiously sloppy, no-effort-expended post, or an answer that is clearly and perhaps dangerously incorrect."? I told the OP to examine the error messages and set their permissions in a properly recursive fashion.
Change w mode to w+ - it will allow php to create file if it's not exist.
$file = fopen($filename,"w+") or die("Failure");
Why open file is deleted? On Windows Xamp, I get message "still working", but on other PHP serwer file is deleted, even if it is open and I get message "file deleted". I can delete file from FTP too, even if first script is still working :(
<?php
$handle = fopen("resource.txt", "x");
sleep(10);
?>
<?php
if (file_exists("resource.txt") && #unlink("resource.txt") === false) {
echo "still worning";
exit;
}
else
echo "file deleted";
?>
UNIX systems typically let you do this, yes. The underlying C unlink function is documented as such:
The unlink() function removes the link named by path from its directory
and decrements the link count of the file which was referenced by the
link. If that decrement reduces the link count of the file to zero, and
no process has the file open, then all resources associated with the file
are reclaimed. If one or more process have the file open when the last
link is removed, the link is removed, but the removal of the file is
delayed until all references to it have been closed.
In other words, you can basically mark the file for deletion at any time, but the system will actually keep it around as long as applications are still accessing it. Only when all applications have let go of the file will it finally actually be removed. Windows apparently does not do it that way. Update: Since PHP 7.3 it's now possible to unlink open files.
As a side note, UNIX' behaviour is the only sane behaviour in a multi-process environment. If you have to wait for all processes to close access to a file before the system lets you remove it, it's basically impossible to remove frequently accessed files at all. Yes, that's where those Windows dialog boxes about "Cannot delete file, still in use, retry?" come from which you can never get rid of.
So, I have this simple little php script. It runs and compiles fine and works the way I want it to on the machine that I coded it. I'm running it on a personal home web-server running Debian 6.0.6, 32bit. It's apache with php. And I know for a fact that php is working on the server.
<?php
$hitsfile = "hits.txt"; #name of file
$filehandle = fopen($hitsfile, 'r') or die ("Couldn't read file."); #Opens file, 'hitsfile' to be read.
$hits = fread($filehandle, 5); #reads file to the introduced variable, 'hits'
fclose($filehandle); #closes file
$hits++; #increments the variable that it read.
$filehandle = fopen($hitsfile, 'w') or die ("Couldn't write to file."); #opens file to be read.
fwrite($filehandle, $hits); #writes the hits variable to file.
fclose($filehandle); #closes file.
echo $hits; #outputs the hits variable.
?>
When I access the file from the server, via a web browser, I get the "Couldn't write to file." error. So then, it's opening the file properly, and reading it. And when it opens it to write, it fails. I'm assuming this is some sort of problem with permissions or something. I'm sort of at a loss as to how to solve the issue. Any ideas? Assistance would be greatly appreciated! I've googled for a couple days now, and I can't solve the issue. I'm a php 'noob' and I'm very new to running a linux-based web-server, but hey, you gotta learn somehow. :*l
tried to check the permissions to the file? The Linux file system have a very strict permission system. Write on terminal:
ls -la /path/to/my/file.txt
This would give you your permissions on the left column. Please read this article to be sure, and check if Apache have the "write" permissions to the file. If not, use the chmod command to give Apache access to the file (or the chown command, to change the owner of this file to apache, if the owner of this file have writing permissions).