PHP not writing to file from one source - php

I have an issue I can't seem to find the solution for. I am trying to write to a flat text file. I have echoed all variables out on the screen, verified permissions for the user (www-data) and just for grins set everything in the whole folder to 777 - all to no avail. Worst part is I can call on the same function from another file and it writes. I can't see to find the common thread here.....
function ReplaceAreaInFile($AreaStart, $AreaEnd, $File, $ReplaceWith){
$FileContents = GetFileAsString($File);
$Section = GetAreaFromFile($AreaStart, $AreaEnd, $FileContents, TRUE);
if(isset($Section)){
$SectionTop = $AreaStart."\n";
$SectionTop .= $ReplaceWith;
$NewContents = str_replace($Section, $SectionTop, $FileContents);
if (!$Handle = fopen($File, 'w')) {
return "Cannot open file ($File)";
exit;
}/*
if(!flock($Handle, LOCK_EX | LOCK_NB)) {
echo 'Unable to obtain file lock';
exit(-1);
}*/
if (fwrite($Handle, $NewContents) === FALSE) {
return "Cannot write to file ($File)";
exit;
}else{
return $NewContents;
}
}else{
return "<p align=\"center\">There was an issue saving your settings. Please try again. If the issue persists contact your provider.</p>";
}
}

Try with...
$Handle = fopen($File, 'w');
if ($Handle === false) {
die("Cannot open file ($File)");
}
$written = fwrite($Handle, $NewContents);
if ($written === false) {
die("Invalid arguments - could not write to file ($File)");
}
if ((strlen($NewContents) > 0) && ($written < strlen($NewContents))) {
die("There was a problem writing to $File - $written chars written");
}
fclose($Handle);
echo "Wrote $written bytes to $File\n"; // or log to a file
return $NewContents;
and also check for any problems in the error log. There should be something, assuming you've enabled error logging.
You need to check for number of characters written since in PHP fwrite behaves like this:
After having problems with fwrite() returning 0 in cases where one
would fully expect a return value of false, I took a look at the
source code for php's fwrite() itself. The function will only return
false if you pass in invalid arguments. Any other error, just as a
broken pipe or closed connection, will result in a return value of
less than strlen($string), in most cases 0.
Also, note that you might be writing to a file, but to a different file that you're expecting to write. Absolute paths might help with tracking this.

The final solution I ended up using for this:
function ReplaceAreaInFile($AreaStart, $AreaEnd, $File, $ReplaceWith){
$FileContents = GetFileAsString($File);
$Section = GetAreaFromFile($AreaStart, $AreaEnd, $FileContents, TRUE);
if(isset($Section)){
$SectionTop = $AreaStart."\n";
$SectionTop .= $ReplaceWith;
$NewContents = str_replace($Section, $SectionTop, $FileContents);
return $NewContents;
}else{
return "<p align=\"center\">There was an issue saving your settings.</p>";
}
}
function WriteNewConfigToFile($File2WriteName, $ContentsForFile){
file_put_contents($File2WriteName, $ContentsForFile, LOCK_EX);
}
I did end up using absolute file paths and had to check the permissions on the files. I had to make sure the www-data user in Apache was able to write to the files and was also the user running the script.

Related

My php script won't open files that aren't in its root directory

This is a php script for a user login system that I am developing.
I need it to read from, and write to, the /students/students.txt file, but it won't even read the content already contained in the file.
<?php
//other code
echo "...";
setcookie("Student", $SID, time()+43200, "/");
fopen("/students/students.txt", "r");
$content = fread("/students/students.txt", filesize("/students/students.txt"));
echo $content;
fclose("/students/students.txt");
fopen("/students/students.txt", "w");
fwrite("/students/students.txt", $content."\n".$SID);
fclose("/students/students.txt");
//other code
?>
You are not using fopen() properly. The function returns a handle that you then use to read or edit the file, for example:
//reading a file
if ($handle = fopen("/students/students.txt", "r"))
{
echo "info obtained:<br>";
while (($buffer = fgets($handle))!==false)
{ echo $buffer;}
fclose($handle);
}
//writing/overwriting a file
if ($handle = fopen("/students/students.txt", "w"))
{
fwrite($handle, "hello/n");
fclose($handle);
}
Let me know if that worked for you.
P.S.: Ty to the commentators for the constructive feedback.
There are many ways to read/write to file as others have demonstrated. I just want to illustrate the mistake in your particular approach.
fread takes a file handle as param, NOT a string that represents the path to the file.
So your line:
$content = fread("/students/students.txt", filesize("/students/students.txt")); is incorrect.
It should be:
$file_handle = fopen("/students/students.txt", "r");
$content = fread($file_handle, filesize("/students/students.txt"));
Same thing when you write contents to file using fwrite. Its reference to the file is a File Handle opened using fopen NOT the filepath. when opening a file using fopen() you can also check if the $file_handle returned is a valid resource or is false. If false, it means the fopen operation was not successful.
So your code:
fopen("/students/students.txt", "w");
fwrite("/students/students.txt", $content."\n".$SID);
fclose("/students/students.txt");
Needs to be re-written as:
$file_handle = fopen("/students/students.txt", "w");
fwrite($file_handle, $content."\n".$SID);
fclose($file_handle);
You can see that fclose operates on file handles as well.
File Handle (as per php.net):
A file system pointer resource that is typically created using fopen().
Here are a couple of diagnostic functions that allow you to validate that a file exists and is readable. If it is a permission issue, it gives you the name of the user that needs permission.
function PrintMessage($text, $success = true)
{
print "$text";
if ($success)
print " [<font color=\"green\">Success</font>]<br />\n";
else
print(" [<font color=\"red\">Failure</font>]<br />\n");
}
function CheckReadable($filename)
{
if (realpath($filename) != "")
$filename = realpath($filename);
if (!file_exists($filename))
{
PrintMessage("'$filename' is missing or inaccessible by '" . get_current_user() . "'", false);
return false;
}
elseif (!is_readable($filename))
{
PrintMessage("'$filename' found but is not readable by '" . get_current_user() . "'", false);
return false;
}
else
PrintMessage("'$filename' found and is readable by '" . get_current_user() . "'", true);
return true;
}
I've re-written your code with (IMO) a cleaner and more efficient code:
<?php
$SID = "SOMETHING MYSTERIOUS";
setcookie("Student", $SID, time()+43200, "/");
$file = "/students/students.txt"; //is the full path correct?
$content = file_get_contents($file); //$content now contains /students/students.txt
$size = filesize($file); //do you still need this ?
echo $content;
file_put_contents($file, "\n".$SID, FILE_APPEND); //do you have write permissions ?
file_get_contents
file_get_contents() is the preferred way to read the contents of a
file into a string. It will use memory mapping techniques if supported
by your OS to enhance performance.
file_put_contents
This function is identical to calling fopen(), fwrite() and
fclose() successively to write data to a file. If filename does not
exist, the file is created. Otherwise, the existing file is
overwritten, unless the FILE_APPEND flag is set.
Notes:
Make sure the full path /students/students.txt is
correct.
Check if you've read/write permissions on /students/students.txt
Learn more about linux file/folder permissions or, if you don't access to the shell, how to change file or directory permissions via ftp
Try to do this:
fopen("students/students.txt", "r");
And check to permissions read the file.

fgets() returns false even though file is not empty

I have a form from which I save the given input into a textfile,
but I have trouble reading from the saved file:
while(!feof($fileNotizen)) {
$rawLine = fgets($fileNotizen);
if($rawLine==false) {
echo "An error occured while reading the file";
}
$rawLine seems to be always false, even though I use this function before, to fill the textfile:
function addToTable($notizFile) {
fwrite($notizFile, $_POST["vorname"]." ".$_POST["nachname"]."#");
$date = date(DATE_RFC850);
fwrite($notizFile, $date."#");
fwrite($notizFile, $_POST["notiz"].PHP_EOL);
}
And after I submit the form and get the error message, if I check the textfile, everything is there, so the function works correctly.
If it is of value, I open the file with this command:
$fileNotizen = fopen("notizen.txt", "a+");
Could the problem be that the pointer is already at the end of the file and thus returns false?
$fileNotizen = fopen("notizen.txt", "a+");
a+ opens for read/write but places file pointer AT THE END. So you must fseek() to the beginning first or look into fopen() flags and choose more wisely based on your needs.
Use fseek($fileNotizen, 0, SEEK_SET); to rewind the file.
To read/get content of the file try this function:
function read_file($file_name) {
if (is_readable($file_name)) {
$handle = fopen($file_name, "r");
while (!feof($handle)) {
$content .= fgets($handle);
}
return !empty($content) ? $content : "Empty file..";
} else {
return "This file is not readable.";
}
}
and if you want to see content of the file displayed on separate lines then use <pre></pre> tag like this:
echo "<pre>" . read_file("notizen.txt") . "</pre>";
and if you want to write/add content to the file then try this function:
function write_file($file_name, $content) {
if (file_exists($file_name) && is_writable($file_name)) {
$handle = fopen($file_name, "a");
fwrite($handle, $content . "\n");
fclose($handle);
}
}
and you can use it like this:
$content = "{$_POST["vorname"]} {$_POST["nachname"]}#" . date(DATE_RFC850) . "#{$_POST["notiz"]}";
write_file("notizen.txt", $content);

Renaming file with PHP

I am using code that i found on here which works great but the moment i try to access a file in a sub-directory it just doesn't want to work.
It gets a file, creates a temp file to write to, then looks for some text in the file and replaces that text with new text, then saves the updated file, then deletes the temp file.
The below works fine:
$reading = fopen('links.htm', 'r');
$writing = fopen('links.tmp', 'w+');
$replaced = false;
while (!feof($reading)) {
$line = fgets($reading);
if (stristr($line,'::template::')) {
$line = "replacement line!\n";
$replaced = true;
}
fputs($writing, $line);
}
fclose($reading); fclose($writing);
// might as well not overwrite the file if we didn't replace anything
if ($replaced)
{
rename('links.tmp', 'links.htm');
} else {
unlink('links.tmp');
}
This doesnt work:
$reading = fopen('path/to/links.htm', 'r');
$writing = fopen('path/to/links.tmp', 'w+');
$replaced = false;
while (!feof($reading)) {
$line = fgets($reading);
if (stristr($line,'::template::')) {
$line = "replacement line!\n";
$replaced = true;
}
fputs($writing, $line);
}
fclose($reading); fclose($writing);
// might as well not overwrite the file if we didn't replace anything
if ($replaced)
{
rename('path/to/links.tmp', 'path/to/links.htm');
} else {
unlink('path/to/links.tmp');
}
Any suggestions?
The path is absolute i defined it in the code earlier and use it to create file and write files to but when i want the code above to work in the same way it just doesn't want to.
Also the folders permissions has been set to write and read which also works fine.
Ran the code in the sub folder and works fine but not from the top level directory.
Error reporting is turned off, turned it on now:
The process cannot access the file because it is being used by another process. (code: 32)
So after a week of looking around, testing, breaking and recoding a lot i found a simple way to do this.
Since most of the content is dynamically created as well as the links.htm file, it was quite hard finding where and when the file is accessed since the code accesses about 300 of my clients sites and updates the links file.
Simple fix:
$path = "path/on/server/";
$conn_id = ftp_connect("ftp.testftp.com") or die("Could not connect");
ftp_login($conn_id,"admin","ert456");
$old_file = $path.'links.htm';
$new_file = $path.'_template.htm';
ftp_rename($conn_id, $old_file, $new_file);
$source = fopen($new_file, "w");
$localTarget = "path/to/links.htm";
ftp_fget($conn,$source,$localTarget,FTP_ASCII);
$reading = fopen('path/to/links.htm', 'r');
$writing = fopen('path/to/_template.htm', 'w+');
$replaced = false;
while (!feof($reading)) {
$line = fgets($reading);
if (stristr($line,'::template::')) {
$line = "replacement line!\n";
$replaced = true;
}
fputs($writing, $line);
}
fclose($reading); fclose($writing);
// might as well not overwrite the file if we didn't replace anything
if ($replaced)
{
rename('path/to/_template.htm', 'path/to/links.htm');
} else {
unlink('path/to/_template.htm');
}
$local_file = "path/to/links.htm";
ftp_put($conn_id, $path, $local_file, FTP_BINARY);
ftp_close($conn_id);
There is probably easier ways to do this but this is what worked for me, hope it helps someone.
PHP will need to have write permissions to that directory in order to write to it. It may be that it has write permissions to the current directory ., but does not have permissions to write to the subdirectory ./path/to/.
Edit: If you get a PHP error, you should include it in your question.
Edit after OP Edit:
That error means that something currently has links.htm opened. I see that you're fclose()ing the file before renaming it, so my guess is that you probably have links.htm open in some other application (e.g. browser or text editor).
Edit #3:
If you do not have one of the links.htm or links.tmp files open in another application, it could be that you're using Windows - in which case the rename() call will execute before the fclose() even though it comes after it in the code. The solution to this is to add a sleep() call after closing the handle:
fclose($reading); fclose($writing);
sleep(1); // this should allow the handle to be properly closed before the rename() call

Php writing to file - empty?

I've been struggling with writing a single string into a file.
I'm using just a simple code under Slackware 13:
$fp = fopen('/my/absolute/path/data.txt', 'w');
fwrite($fp, 'just a testing string...');
fclose($fp);
The file gets created (if it's not already created) but it's empty ?!
The directory in which this file is written is owned by apache's user & group (daemon.daemon) and has 0777 permissions.
This has never happened to me before. I'm curious what's the reason I'm not able to write inside the file ?
Thanks in advance.
Try $ df -h
It probably means your disk is full.
In my opinion you could check the return values:
$fp = fopen('/my/absolute/path/data.txt', 'w');
// $fp -> manual: "Returns a file pointer resource on success, or FALSE on error."
if ($fp) {
$bytes_written = fwrite($fp, 'just a testing string...');
if ($bytes_written) {
echo "$bytes_written bytes written!\n";
} else {
echo "Error while writing!\n"
}
$success = fclose($fp);
if ($success) {
echo "File successfully closed!\n";
} else {
echo "Error on closing!\n";
}
} else {
echo "No filepointer ressource!\n";
}
I suggest using file_put_conents($file_name, $file_cotents);
And to retrieve content: file_get_contents($file_name);
Code looks cleaner too.
http://php.net/manual/en/function.file-put-contents.php and
http://www.php.net/manual/en/function.file-get-contents.php
Could be something is happening to the script/file before the file is closed. Check if there are any other processes that try to access the file (you can use lsof). Also try writing to a new file to see if the same thing occurs.
Also, check the return value on fclose() to make sure the file is being closed successfully.

Unpack large files with gzip in PHP

I'm using a simple unzip function (as seen below) for my files so I don't have to unzip files manually before they are processed further.
function uncompress($srcName, $dstName) {
$string = implode("", gzfile($srcName));
$fp = fopen($dstName, "w");
fwrite($fp, $string, strlen($string));
fclose($fp);
}
The problem is that if the gzip file is large (e.g. 50mb) the unzipping takes a large amount of ram to process.
The question: can I parse a gzipped file in chunks and still get the correct result? Or is there a better other way to handle the issue of extracting large gzip files (even if it takes a few seconds more)?
gzfile() is a convenience method that calls gzopen, gzread, and gzclose.
So, yes, you can manually do the gzopen and gzread the file in chunks.
This will uncompress the file in 4kB chunks:
function uncompress($srcName, $dstName) {
$sfp = gzopen($srcName, "rb");
$fp = fopen($dstName, "w");
while (!gzeof($sfp)) {
$string = gzread($sfp, 4096);
fwrite($fp, $string, strlen($string));
}
gzclose($sfp);
fclose($fp);
}
try with
function uncompress($srcName, $dstName) {
$fp = fopen($dstName, "w");
fwrite($fp, implode("", gzfile($srcName)));
fclose($fp);
}
$length parameter is optional.
If you are on a Linux host, have the required privilegies to run commands, and the gzip command is installed, you could try calling it with something like shell_exec
SOmething a bit like this, I guess, would do :
shell_exec('gzip -d your_file.gz');
This way, the file wouldn't be unzip by PHP.
As a sidenote :
Take care where the command is run from (ot use a swith to tell "decompress to that directory")
You might want to take a look at escapeshellarg too ;-)
As maliayas mentioned, it may lead to a bug. I experienced an unexpected fall out of the while loop, but the gz file has been decompressed successfully. The whole code looks like this and works better for me:
function gzDecompressFile($srcName, $dstName) {
$error = false;
if( $file = gzopen($srcName, 'rb') ) { // open gz file
$out_file = fopen($dstName, 'wb'); // open destination file
while (($string = gzread($file, 4096)) != '') { // read 4kb at a time
if( !fwrite($out_file, $string) ) { // check if writing was successful
$error = true;
}
}
// close files
fclose($out_file);
gzclose($file);
} else {
$error = true;
}
if ($error)
return false;
else
return true;
}

Categories