problem with fopen and fwrite - php

hi when i execute this code nothing happen in browser but when i delete lines with star,the contents printed correctly,whats wrong??
/////////////////
$documentroot=$_SERVER['DOCUMENT_ROOT'];
$handle=fopen("$documentroot/order/order.txt",'r+');
if(!$handle) {
echo 'error opening file';
}
$content="pepsi\ncola\npeperoni";
$write=fwrite($handle,$content); //*
if(!$write){ //*
echo 'error writing'; //*
} //*
while(!feof($handle)) {
$string=fgets($handle);
echo $string;
}

this line should be like this.
$handle=fopen("$documentroot/order/order.txt",'w');
file should be open in the write mode.try this.
Thanks.

/* This is the opening tag on PHP and it needs to be closed with another */ but the * in front this time. You can stick with // for just one line of commenting.

You are opening the file in r+ mode which means read+write mode. But if the file orders.txt does not exist, it'll not be created. So ensure file exists.
Also when there is problem with opening the file, you immediately exit.
if(!$handle) {
echo 'error opening file';
exit; // MISSING
}
Assuming the file already exists, it's contents will be wiped after the fopen. Next the fwrite will write the contents. Now the file pointer is at the end of the file so your call to feof() in the while loop will return true and the while is never entered.
To fix this you rewind the file pointer before you start reading from the file:
rewind($handle); // ADD THIS
while(!feof($handle)) {
...
}

$documentroot=$_SERVER['DOCUMENT_ROOT'];
$handle=fopen("$documentroot/order/order.txt",'r+');
if(!$handle) {
echo 'error opening file';
}
$content="pepsi\ncola\npeperoni";
$write=fwrite($handle,$content);
if(!$write){
echo 'error writing';
}
fseek($handle, 0);
while(!feof($handle)) {
$string=fgets($handle);
echo $string;
}
After file write operation, your file pointer sets to the end of written data which needs to set to the start position for fgets. fseek does that.
fseek($handle, 0);
This will take your pointer to the beginning so that fgets now can read from file. fgets function needs valid file pointer to read which in this case is the start position.

Related

Can't get my php to add to my text document?

I'm currently working on a project for college but i'm having issues with it. I have two pages with a form on each which includes three text fields (des,act,date) I'm trying to make it so that it will add to the text document the information from the forms but at the minute all it is doing is overwriting it. Anyone know how to solve this?
Page 1
if (isset($_GET['logout'])){
session_destroy();
}
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] == false) {
header("Location: index.php");
}
//Send Data
$content = 'OBSERVATION'."\r\n".'Breif Description: '.$_POST['des1']."\r\n".'Agreed Action: '.$_POST['act1']."\r\n".'Close Date: '.$_POST['date1']."\r\n";
if (isset($_POST['submit'])){
$myFile=fopen("Observation.txt","w") or exit("Can’t open file!");
fwrite($myFile, $content);
fclose($myFile);
header( 'Location: http://www.murphy.sulmaxmarketing.com/GoodPractices.php' ) ;
}
?>
Page 2
if (isset($_GET['logout'])){
session_destroy();
}
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] == false) {
header("Location: index.php");
}
//Send Data
$content = "\r\n\r\n".'GOOD PRACTICES'."\r\n".'Breif Description: '.$_POST['des2']."\r\n".'Agreed Action: '.$_POST['act2']."\r\n".'Close Date: '.$_POST['date2']."\r\n";
if (isset($_POST['submit'])){
$myFile=fopen("Observation.txt","w") or exit("Can’t open file!");
fwrite($myFile, $content);
fclose($myFile);
}
?>
fopen() with a mode of 'w'
Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
fopen() with a mode of 'a'
Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.
Use file_put_contents function with FILE_APPEND flag.
This function is identical to calling fopen(), fwrite() and fclose()
successively to write data to a file.
FILE_APPEND : If file filename already exists, append the data to the file instead of overwriting it.
...
if (isset($_POST['submit'])) {
file_put_contents("Observation.txt", $content, FILE_APPEND);
header( 'Location: http://www.murphy.sulmaxmarketing.com/GoodPractices.php' ) ;
exit;
}
...
http://php.net/manual/en/function.file-put-contents.php
Use file_put_content
if (isset($_POST['submit'])) {
file_put_contents("Observation.txt", $content, FILE_APPEND);
... your code here
}
Here third parameter in file_put_content "FILE_APPEND" will append your file every time with new content in your previous code it was overwrite one content with another because of same name so if you want to do it on that way than you want to set different name of both file.
Here file_put_content function url : http://php.net/manual/en/function.file-put-contents.php

PHP not writing to file from one source

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.

PHP File include error

I have the following code in a PHP page. Some times when I delete the cache2.html file, I expect the php to recreate it and the next person will get the cache2.html instead of executing the php code. I get the following warning some times on the page and no content. Is it because of multiple users accessing the php concurrently? If so, How do I fix it? Thank you.
Warning: include(dir1/cache2.html) [function.include]: failed to
open stream: No such file or directory in
/home/content/54/site/index.php on line 8
<?php
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();
$cachefile = "dir1/cache2.html";
if (file_exists($cachefile)) {
include($cachefile); // output the contents of the cache file
} else {
/* HTML (BUILT USING PHP/MYSQL) */
$cachefile = "dir1/cache2.html";
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_flush(); // Send the output to the browser
}
?>
Calls to file_exists() are themselves cached, so it's likely you're getting a return value of true even after the file is deleted. See:
http://us.php.net/manual/en/function.clearstatcache.php
So, you could do:
clearstatcache();
if (file_exists($cache)) {
include($cache);
} else {
// generate page
}
Alternatively, you could do something like this:
if (file_exists($cache) && #include($cache)) {
exit;
} else {
// generate page
}
Or better, if you're deleting the cache file from within a PHP process, then just call clearstatcache() after you delete the file.

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.

Using php, how to insert text without overwriting to the beginning of a text file

I have:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
but it overwrites the beginning of the file. How do I make it insert?
I'm not entirely sure of your question - do you want to write data and not have it over-write the beginning of an existing file, or write new data to the start of an existing file, keeping the existing content after it?
To insert text without over-writing the beginning of the file, you'll have to open it for appending (a+ rather than r+)
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
If you're trying to write to the start of the file, you'll have to read in the file contents (see file_get_contents) first, then write your new string followed by file contents to the output file.
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
The above approach will work with small files, but you may run into memory limits trying to read a large file in using file_get_conents. In this case, consider using rewind($file), which sets the file position indicator for handle to the beginning of the file stream.
Note when using rewind(), not to open the file with the a (or a+) options, as:
If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.
A working example for inserting in the middle of a file stream without overwriting, and without having to load the whole thing into a variable/memory:
function finsert($handle, $string, $bufferSize = 16384) {
$insertionPoint = ftell($handle);
// Create a temp file to stream into
$tempPath = tempnam(sys_get_temp_dir(), "file-chainer");
$lastPartHandle = fopen($tempPath, "w+");
// Read in everything from the insertion point and forward
while (!feof($handle)) {
fwrite($lastPartHandle, fread($handle, $bufferSize), $bufferSize);
}
// Rewind to the insertion point
fseek($handle, $insertionPoint);
// Rewind the temporary stream
rewind($lastPartHandle);
// Write back everything starting with the string to insert
fwrite($handle, $string);
while (!feof($lastPartHandle)) {
fwrite($handle, fread($lastPartHandle, $bufferSize), $bufferSize);
}
// Close the last part handle and delete it
fclose($lastPartHandle);
unlink($tempPath);
// Re-set pointer
fseek($handle, $insertionPoint + strlen($string));
}
$handle = fopen("file.txt", "w+");
fwrite($handle, "foobar");
rewind($handle);
finsert($handle, "baz");
// File stream is now: bazfoobar
Composer lib for it can be found here
You get the same opening the file for appending
<?php
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
If you want to put your text at the beginning of the file, you'd have to read the file contents first like:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
$existingText = file_get_contents($file);
fwrite($file, $existingText . $_POST["lastname"]."\n");
}
fclose($file);
?>

Categories