Jump to content

[SOLVED] help with script


bga89031

Recommended Posts

yeah hi

 

im trying to use this script to write to the second half of any line in a text file

 

<?php
$i = "";

$file = file("stats.txt");
$init = $file[$_GET["i"]];
$param = explode(",", $init);
$name = $param[0];
$num = $param[1];

if (file_exists('stats.txt')) 
{
$param[1]++;
$fil = fopen('stats.txt', r);
echo $param[1]+1;
fclose($fil);
$fil = fopen('stats.txt', w);
fwrite($fil, implode(",", $param));
fclose($fil);
}
else
{
$param[1]++;
$fil = fopen('stats.txt', w);
fwrite($fil, implode(",", $param));
echo '1';
fclose($fil);
}
echo implode(",",$param);
?>

 

where each line in the text file is composed of "string,number". basically, $i should determine the line number to write to and $num should work like a basic counter but i can't quite get this right- it replaces all of my text file with a single-digit "1". im new at this and i nothing i try seems to work.

 

help?

 

p.s. i realize this would be easier to do with mysql database but i find myself unable to acquire a decent working one at the moment

Link to comment
Share on other sites

Try this code:

 

<?php
if (is_numeric($_GET["i"])) {
  $file = file("stats.txt");
  $init = chop($file[$_GET["i"]]);
  list($name, $num) = explode(",", $init);
  $num++;
  $file[$_GET["i"]] = implode(",", array($name, $num)) . "\n";

  # $file is now updated - write it back
  $fp = fopen("stats.txt", "w");
  foreach ($file as $line) {
    fwrite($fp, $line);
  }
  fclose($fp);
} else {
  print "'i' was not set";
}
?>

 

The chop() is related to the newline character, which separates lines in a file.  It strips it off.  Then on the implode() line I add it back in.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.