No errors, but fwrite() won't write to file - php

I've been following PHP and MySQL Web Development 5th edition, but I'm stuck on Chapter 2 because I cannot write to a file.
Here's the code:
// open file for appending
$fp = fopen('orders.txt', 'ab', true);
if (!$fp) {
echo "<p><strong> Your order could not be processed at this time.
Please try again later.</strong></p>";
exit;
}
flock($fp, LOCK_EX);
$bytes = fwrite($fp, $outputstring, strlen($outputstring));
echo $bytes;
flock($fp, LOCK_UN);
fclose($fp);
The echo gives me 65, which seems right, but orders.txt is always completely blank. Could someone give me some advice? I'm using Webstorm with a server hosted on GoDaddy if that matters.

Perhaps you meant
$fp = fopen('orders.txt', 'a', true);
instead of
$fp = fopen('orders.txt', 'ab', true);
Note that you can also use the 'w' mode instead of 'a' if you would like to overwrite the file instead of appending at the end of it.

Related

Shared access: How to fix "fread(): Length parameter must be greater than 0"?

When I run this function on multiple scripts one script generated warning:
fread(): Length parameter must be greater than 0
function test($n){
echo "<h4>$n at ".time()."</h4>";
for ($i = 0; $i<50; $i++ ){
$fp = fopen("$n.txt", "r");
$s = fread($fp, filesize("$n.txt") );
fclose($fp);
$fp = fopen("$n.txt", "w");
$s = $_SERVER['HTTP_USER_AGENT'].' '.time();
if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
fwrite($fp, $s);
// fflush($fp);// flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't get the lock!";
}
}
}
I try to write reading of the file for multiple users, but only one user can write the file. I know that when I use fwrite with flock - LOC_EX, next scripts must wait till the write is finished. But here it seems like filesize doesn't wait till the write operation is finished. My opinion is that it tries to reach the file when the file size is 0, and as a result this produces the problem: 0 bytes will be read from the file, when it is written by original script.
Is it possible to fix this for fread function?
Purpose of this script is to test fread with some limit and to check the data which I read later, if the data are really written when I did not used fflush.
function test($n){
echo "<h4>$n at ".time()."</h4>";
for ($i = 0; $i<50; $i++ ){
$start = microtime(true);
$fp = fopen("$n.txt", "r");
if(filesize($n.txt) > 0)
{
$s = fread($fp, filesize($n.txt) );
fclose($fp);
$fp = fopen("$n.txt", "w");
$s = $_SERVER['HTTP_USER_AGENT'].' '.time();
if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
fwrite($fp, $s);
// fflush($fp);// flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't get the lock!";
}
}
else
{
echo "Filesize must be greater than 0";
}
}
}
please change $s variables name its use same things two time
$fp = fopen("$n.txt", "r");
$s = fread($fp, filesize("$n.txt") );
fclose($fp);
The error occurs in the middle line of the above three lines.
Firstly, these three lines could be rewritten into a single line as follows:
$s = file_get_contents("$n.txt");
However, these isn't necessary, as these three lines are entirely redundant in your code. They don't do anything useful.
What they do is open a file, store its contents to $s and then close it.
But you are then immediately setting $s to a different value, thus throwing away the previous value, and making it pointless to have read it from the file in the first place.
If you need to keep the original contents of the file, then use file_get_contents() and make sure you don't overwrite the contents of the variable.
If you don't need the original contents of the file, then just delete those three lines from your code.
Incidentally, this error highlights a couple of good coding practices that you should take on board: Firstly, never re-use a variable for two different things, and secondly always give your variables (and functions) good names. $s is not a good name; $previousFileContents would be a better name; it would have made the error much more obvious.

PHP: Problems reading and write back to file

$fh = fopen(PATH_TO_FILE, "r+");
flock($fh, LOCK_EX);
$data = fgets($fh);
$data = json_decode($data, true);
$data['mod_1'] = 1;
$data_write = json_encode($data);
ftruncate($fh, 0);
fwrite($fh , $data_write);
clearstatcache();
flock($fh, LOCK_UN);
fclose($fh);
This works only if I prepare JSON file by myself. The problem is, next time I try to call this method, json_decode() returns false and the file is partial corrupted. json_decode() can not parse it anymore.
What is the problem with this code?
My JSON File contents:
{"mod_1":0,"mod_2": 0}
All I want is to read file, modify its content and write back to file(overwrite). I must use LOCK_EX, so I assume file_put_contents is not for me.
The problem was that ftruncate didn't set the pointer at the beginning of empty file. So I added rewind($fh) right after ftruncate and the problem was solved.

Text file-based sequential url rotator isn't working

I'm trying to create a text file-based sequential url rotator by using the following code (original source):
<?php
$linksfile ="urlrotator.txt";
$posfile = "pos.txt";
$links = file($linksfile);
$numlinks = count($linksfile);
$fp = fopen($posfile, 'r+') or die("Failed to open posfile");
flock($fp, LOCK_EX);
$num = fread($fp, 1024);
if($num<$numlinks-1) {
fwrite($fp, $num+1);
} else {
fwrite($fp, 0);
}
flock($fp, LOCK_UN);
fclose($fp);
header("Location: {$links[$num]}");
?>
After my testing, I found that it keeps appending new position number as a string after the existing content of pos.txt and thus the script only works at the first time.
I tried adding the following line of code before the if else statement in order to clear the existing content of pos.txt before updating it.
file_put_contents($posfile, "");
But then error ocurred at the line of redirection saying Undefined index: ...... .
Where could possibly go wrong?
I believe your problem comes from the mode you are using. When you say
After my testing, I found that it keeps appending new position number as a string after the existing content of pos.txt and thus the script only works at the first time.
it points me to the mode usage of fopen.
The mode you should use is w, as it will "replace" the content of what is inside pos.txt.
$fp = fopen($posfile, 'w') or die("Failed to open posfile");
Doing so will prevent your from accessing what was in pos.txt. So you need to have something like this:
$num = file_get_contents($posfile);
$fp = fopen($posfile, 'w') or die("Failed to open posfile");
flock($fp, LOCK_EX);
if($num<$numlinks-1) {
fwrite($fp, $num+1);
} else {
fwrite($fp, 0);
}
flock($fp, LOCK_UN);
fclose($fp);

php text line by line not working

I have a text file called things.txt with:
thing1
thing2
thing34
and php:
$fp = fopen('things.txt');
while (!feof($fp)) {
$line = fgets($fp);
echo $line."<br>";
}
fclose($fp);
and it's not working...any ideas?
fopen() requires at least two parameters!
$fp = fopen('things.txt', 'r');
The second one is the mode. r ("readonly, pointer at the beginning, no truncate") should work fine here, because you only read it. For the other modes, refer the manual (linked above).
You should change your development settings to
error_reporting = E_ALL | E_STRICT
because you should get an error for this. However, the reason for the infinite loop is, that fopen() returns null and feof(null) returns false and while(!false) is an infinite loop.
When using fopen, you need to specify a mode (reading, writing, etc). So you should change your code to:
$fp = fopen('things.txt', 'r');
while (!feof($fp)) {
$line = fgets($fp);
echo $line."<br>";
}
fclose($fp);
try $fp = fopen('things.txt', 'r') or die('unable to open file'); to see if your script can actually find your file

How to write into a file in PHP?

I have this script on one free PHP-supporting server:
<html>
<body>
<?php
$file = fopen("lidn.txt","a");
fclose($file);
?>
</body>
</html>
It creates the file lidn.txt, but it's empty.
How can I create a file and write something into it,
for example the line "Cats chase mice"?
You can use a higher-level function like:
file_put_contents($filename, $content);
which is identical to calling fopen(), fwrite(), and fclose() successively to write data to a file.
Docs: file_put_contents
Consider fwrite():
<?php
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
?>
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase');
fwrite($fp, 'mice');
fclose($fp);
http://php.net/manual/en/function.fwrite.php
$text = "Cats chase mice";
$filename = "somefile.txt";
$fh = fopen($filename, "a");
fwrite($fh, $text);
fclose($fh);
You use fwrite()
It is easy to write file :
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
Here are the steps:
Open the file
Write to the file
Close the file
$select = "data what we trying to store in a file";
$file = fopen("/var/www/htdocs/folder/test.txt", "w");
fwrite($file, $select->__toString());
fclose($file);
I use the following code to write files on my web directory.
write_file.html
<form action="file.php"method="post">
<textarea name="code">Code goes here</textarea>
<input type="submit"value="submit">
</form>
write_file.php
<?php
// strip slashes before putting the form data into target file
$cd = stripslashes($_POST['code']);
// Show the msg, if the code string is empty
if (empty($cd))
echo "Nothing to write";
// if the code string is not empty then open the target file and put form data in it
else
{
$file = fopen("demo.php", "w");
echo fwrite($file, $cd);
// show a success msg
echo "data successfully entered";
fclose($file);
}
?>
This is a working script. be sure to change the url in the form action and the target file in fopen() function if you want to use it on your site.
In order to write to a file in PHP you need to go through the following steps:
Open the file
Write to the file
Close the file
$select = "data what we trying to store in a file";
$file = fopen("/var/www/htdocs/folder/test.txt", "a");
fwrite($file , $select->__toString());
fclose($file );
fwrite() is a smidgen faster and file_put_contents() is just a wrapper around those three methods anyway, so you would lose the overhead.
Article
file_put_contents(file,data,mode,context):
The file_put_contents writes a string to a file.
This function follows these rules when accessing a file.If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of filename
Create the file if it does not exist then Open the file and Lock the file if LOCK_EX is set and If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content
Write the data into the file and Close the file and release any locks.
This function returns the number of the character written into the file on success, or FALSE on failure.
fwrite(file,string,length):
The fwrite writes to an open file.The function will stop at the end of the file or when it reaches the specified length,
whichever comes first.This function returns the number of bytes written or FALSE on failure.

Categories