Reading and modifying a text file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
m0u53m4t
Forum Contributor
Posts: 101
Joined: Wed Apr 19, 2006 7:47 am
Location: Wales

Reading and modifying a text file

Post by m0u53m4t »

This is my code

Code: Select all

<?php

$serial = $_GET["serial"];

$data = file_get_contents("keys.php");
$elements = explode(',', $data);
if(in_array($serial,$elements)){
echo "Well done!";
}else{
echo "You stuffed it...";
}
?>
But I want it to delete the correct serial from the file "keys.php" once its done. how could I do that?
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

Besides the fact that keys.php is probably not a valid PHP file, you could hack something out like this:

Code: Select all

// continuing inside "Well done!"

$key = array_search($serial, $elements);
array_splice($elements, $key, 1); // modifies array
$new_file_contents = implode(',', $elements);
file_put_contents('keys.php', $new_file_contents); //if you use PHP 5
Although I seriously recommend using a database at this point.
User avatar
m0u53m4t
Forum Contributor
Posts: 101
Joined: Wed Apr 19, 2006 7:47 am
Location: Wales

Post by m0u53m4t »

I'm getting this error:

Fatal error: Call to undefined function: file_put_contents() in /home/freehost/t35.com/j/u/juniorfiles/rssupreme/reg.php on line 13

What can I do?
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

Yep, PHP5. Substitute that with:

Code: Select all

$fh = fopen('keys.php', 'w');
fwrite($fh, $new_file_contents);
fclose($fh);
User avatar
m0u53m4t
Forum Contributor
Posts: 101
Joined: Wed Apr 19, 2006 7:47 am
Location: Wales

Post by m0u53m4t »

That works. Thanks. This is some php code I have:

Code: Select all

<?php
$filename = "time.php";
$hours = $_GET["hours"]

if $hours > 24 then {
   if $hours > 48 then {
      if $hours > 72 then {

      $days = 3;
      $hours = $hours - 72;
   }

   $days = 2;
   $hours = $hours - 48;
}

$days = 1;
$hours = $hours - 24;
}
and I want it to write $days and $hours to the file time.php in this format: " $days:$hour ". How can I do that?
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

I think you need to check out date()
User avatar
m0u53m4t
Forum Contributor
Posts: 101
Joined: Wed Apr 19, 2006 7:47 am
Location: Wales

Post by m0u53m4t »

Not like that. I want it to manually write a file with figures like "1:0" to be read by some other php.
Post Reply