PHP file writing problem - php

I'm trying to write to a file in PHP to cache the output of a small portion of code.
ob_start();
echo "Hello";
$fp = fopen("cache/ttcache.php", 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
The file exists and is blank. The fwrite function points to the correct location. It just doesn't write.
Any help?

Try to write first small word or sentence first.
fwrite($fp, 'hello')
Also check your file permission's should be writable.

Make sure ob_get_contents() is really not empty. Then try
fflush($fp);
right before fclose().

Related

PHP Understanding stream_get_contents on existing file opened with w+

I was trying to figure out file pointers in PHP, so I wrote a small script to test it out:
$fp = fopen('test.me', 'w+');
fwrite($fp, '12345');
rewind($fp);
echo 'contents: ['.stream_get_contents($fp)."]\n";
fseek($fp, 0, SEEK_END);
fwrite($fp, '6789');
fclose($fp);
echo 'contents: ['.file_get_contents('test.me')."]\n";
Nice and easy. Open a file to read/write from it. Write to it. Go back to the beginning of the file, print out its contents. Go to the end of the file, append some more to it. Finally, print out the entire contents of the file.
I run it and get the exact results that I expect:
contents: [12345]
contents: [123456789]
Being so proud of myself for writing this masterpiece, I go to my terminal and hit up and enter to run it again.
This time:
contents: []
contents: [123456789]
Turns out that if the file exists at the start of the script, the first block is always contents:[]. If I delete the test.me file, then the first block is contents:[12345].
What's going on here?

Should I use flock when reading a file in PHP?

Ok so I am new to PHP and the example from the book shows that when I write to a file in php i should use flock($fp, LOCK_EX) after opening the file and then flock($fp, LOCK_UN) before closing the file. Like this:
$fp = fopen("$DOCUMENT_ROOT/order.txt", 'ab');
flock($fp, LOCK_EX);
fwrite($fp, $outputstring, strlent($outputstring));
flock ($fp, LOCK_UN);
fclose($fp);
But in the other example of how to read a file I am not sure if the author forgot to put flock() or it is not necessary to put flock() when reading a file. Here is the example:
$fp = fopen("$DOCUMENT_ROOT/order.txt", 'rb');
while (!feof($fp))
{
$order = fgets($fp, 999)
echo $order."<br/>";
}
fclose($fp);
So should I put flock() in the second example or not?
Thank you in advance.
It is only necessary to use flock if there are going to be multiple processes accessing the file at the same time.
If the code that writes to the file is only ever going to have have one copy running at any time, then you probably don't need to use flock. However if it is possible that multiple processes could try to run the code (and therefore access the file) at the same time, then you should use flock to make sure they do it one at a time.

opening a .txt file with php (read / write) and deleting the old content and replacing it with a new one

I want to change the old values of a text file with a new values (delete the old content and replace it), when I use the code below it shows me an error page , don't really know how to fix this , even used the different types of file opening methods (w , r+ , a ...) and didn't work !
$i=$_POST['id'];
$fp = fopen ("/test/member_dl.txt", "r+");
$ch = fgets ($fp);
$t=explode('||',$ch);
$t[$i-1]='';
$ch2=implode('||',$t);
fwrite($fp,$ch2);
fclose ($fp);
As you want to completely replace the contents, why not just delte it, and re-create it?
unlink ("/test/member_dl.txt");
$fp = fopen ("/test/member_dl.txt", "r+");
// Continue with your code.
// Not sure I follow what you are doing with it
Edit: I am not sure I understand what that part of your code is doing to be honest.
The unlink() command deletes the file. From there you can start over and write the file out as you need it?
Whilst it's open as $fp = fopen ("/test/member_dl.txt", "r+");
You will not be able to fwrite($fp,$ch2);
Opening it with 'w+' should enable read and writing.
Try this:
$i=$_POST['id'];
$fp = fopen("/test/member_dl.txt", "w+");
$ch = fread($fp, filesize($fp));
$t=explode('||',$ch);
$t[$i-1]='';
$ch2=implode('||',$t);
fwrite($fp,$ch2);
fclose ($fp);
EDIT:
Tested this, this works
$ch = file_get_contents("test.txt");
$t=explode('||',$ch);
$t[$i-1]='';
$ch2=implode('||',$t);
file_put_contents("test.txt","hello");

file create error in php

I'm creating the file using the php function but it is not working.I have created the folder and set its permission 0777 but it is not creating the file.
I'm using the following code. plz let me know what is going wrong.
$cachefile ='/cache/cache.text';
$file=chmod($cachefile, 777);
if (file_exists($file)) {
include($file);
} else{
$fp = fopen('/cache/cache.txt', 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
for ob_get_contents() function I'm using the ob_start () function. If I create the file manually it is working and showing the buffering data.Plz let me know how can I create the file using the fopen function.
This line has several issues:
$file=chmod($cachefile, 777);
At that time, the file may not exist, so it may show an error (you cannot do chmod on a file that does not exist).
chmod() will return either true or false. You are trying to use this return value in your code later, saved in the $file variable.
This should work if the cache folder is writable:
$cachefile ='cache/cache.txt';
if (file_exists($cachefile)) {
include($cachefile);
}
else {
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
}

Php fopen write in css file -> file empty

i have this following php code :
$filename = '/front/style.css';
$cssfile='#h1{font-size:12px}';
if($id_file=fopen($filename, "w+"))
{
echo'file exist';
$id_file=fopen($filename, "w+");
flock($id_file,1);
fwrite($id_file,$cssfile);
flock($id_file,3);
fclose($id_file);
}
else
{
echo "file don t exist";
}
My file is empty but with space.
My file exist and it s writable.
I have nothing in my apache logs.
I m using Mamp with php 5.3.2.
Any ideas ?
Thx
A few mistakes I can see are:
You are using fopen to check if a file exists. That does not work. With the w+ mode PHP will try to create the file if it does not exist. Use the file_exits function to check the existence of a file.
You are opening the same file twice.
Also use PHP constants(LOCK_SH, LOCK_UN) for the second argument of flock. That will make your program more readable.
Updated
Have you checked if its writing to a different directory than you expect? Check your path to see where it defaults to, or even just do a search for the file and see where else it turns up. getcwd() will show what the current working dir is.
Have you checked the return value of fwrite to see if the write is actually working? If fwrite is successful, then try read the file in the code using the same $id_file and see if there is anything there while the program is still running.
You are calling fopen twice. w+ truncates the file and you are writing to the 2nd $id_file so my guess is that its being truncated when the 1st $id_file is being closed.
You can use this approach if your file empty after using fopen w+ option.
// only read
$filename = '/path/to/blah.txt';
$myfile = fopen($filename, "r");
$mydata = fread($myfile, filesize($filename));
$mynewdata = $mydata + 'abc';
fclose($myfile);
// only write
$myfile = fopen($filename, "w");
fwrite($myfile, $mynewdata);
fclose($myfile);

Categories