Reputation: 11
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;
}
Upvotes: 1
Views: 592
Reputation: 4075
$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.
Upvotes: 0
Reputation: 455360
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)) {
...
}
Upvotes: 0
Reputation: 1464
/*
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.
Upvotes: 0
Reputation: 3828
this line should be like this.
$handle=fopen("$documentroot/order/order.txt",'w');
file should be open in the write mode.try this.
Thanks.
Upvotes: 2