0

I've embedded this html in my site. As you can see it creates a text file if one doesn't exist, or it reads an existing one. it increments what it reads, and then rewrites it to the text file. I can understand that this code might be sloppy, so as well as solving my main problem, I was wondering if there are any ways to improve the code.

My main problem is making the echo output the text lower down. I have tried using lots of variations of "\n" and < b r> (No space), but the read variable is just not moving. Any help or advice?

<!DOCTYPE html>
<html>
<body>
<link href="css/stylesheet.css" type="text/css" rel="stylesheet">
<p style="font-size: 100px; color: blue ; text-align:center ;">
<?php
$filename = "number.txt" ;
if (!file_exists($filename)) {
$f = fopen($filename, "x");
fwrite($f,"0000000000") ;
fclose($f) ;
}
$f = fopen($filename, "r");
$i = fgets($f); 
fclose($f);
$f = fopen($filename, "w");
$i = $i+1 ;
echo "<br>$i" ;
fwrite($f, "$i"); 
fclose($f);
?>
</p>
</body>
</html>
Ross
  • 1,313
  • 4
  • 16
  • 24
  • _text lower down_ I don't get it. Can you provide a example what the output looks like and what you are expecting. – Rahil Wazir Jun 19 '14 at 19:48
  • As written, the code looks like it's just going to output an integer to the browser, with markup that looks like this `


    42

    ` That should leave a blank line before the number - is that what you want?
    – Kryten Jun 19 '14 at 20:03

2 Answers2

0
<!DOCTYPE html>
<html>
<body>
<link href="css/stylesheet.css" type="text/css" rel="stylesheet">
<p style="font-size: 100px; color: blue ; text-align:center ;">
<?php
$filename = "number.txt" ;
if (!file_exists($filename)) {
$f = fopen($filename, "x");
fwrite($f,"0000000000") ;
fclose($f) ;
}
$f = fopen($filename, "r");
$i = fgets($f); 
fclose($f);
$f = fopen($filename, "w");
$i = $i+1 ;
echo "$i" ;
echo "\r\n"; 
fwrite($f, "$i"); 
fclose($f);
?>
</p>
</body>
</html>

See: Writing a new line to file in PHP

Community
  • 1
  • 1
eyoung100
  • 168
  • 9
0

one-line-ified:

file_put_contents($filename, file_get_contents($filename) + 1);

If you can seed the file with a "0" you won't get a warning on the first hit. Or, you can do this:

file_put_contents($filename, @file_get_contents($filename) + 1);
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98