saving, loading & setup of user data via .txt files

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
Disloxic
Forum Newbie
Posts: 2
Joined: Tue Nov 17, 2009 1:41 pm

saving, loading & setup of user data via .txt files

Post by Disloxic »

Hi,

I have assembled the following code that saves a specific data array to a .txt file based on the users name ('user_id_0000001.txt' will be dynamic in the final code).

I was wondering how I might tweak the code so that if a user's .txt file already exists, it will read the array saved in that file, and if a user's .txt file doesnt exist yet, then it will create the .txt file and save a default data array there.

Then, each time the user's .txt file is loaded, I would like to +1 to the variables in their array and save to their .txt file.

Its basically the bare-bones for a game where i need to be able to save the user's variables without overighting existing users with the default variables.

any help would be sorely appreciated,

many thanks,

Dave


Code: Select all

<?php
 
$filepath='user_id_0000001.txt';
 
 
//
// load a tab seperated text file as array
//
function load_tabbed_file($filepath, $load_keys=false){
    $array = array();
 
    if (!file_exists($filepath)){ return $array; }
    $content = file($filepath);
 
    for ($x=0; $x < count($content); $x++){
        if (trim($content[$x]) != ''){
            $line = explode("\t", trim($content[$x]));
            if ($load_keys){
                $key = array_shift($line);
                $array[$key] = $line;
            }
            else { $array[] = $line; }
        }
    }
    return $array;
}
 
 
// save an array as tab seperated text file
 
$array = array(
    'line1'  => array('data-1-1', 'data-1-2', 'data-1-3'),
    'line2' => array('data-2-1', 'data-2-2', 'data-2-3'),
    'line3'  => array('data-3-1', 'data-3-2', 'data-3-3'),
    'line4' => 'default',
    'line5' => 'default2'
);
 
// save the array to the .txt file:
write_tabbed_file($filepath, $array, true);
function write_tabbed_file($filepath, $array, $save_keys=false){
    $content = '';
 
    reset($array);
    while(list($key, $val) = each($array)){
 
        // replace tabs in keys and values to [space]
        $key = str_replace("\t", " ", $key);
        $val = str_replace("\t", " ", $val);
 
        if ($save_keys){ $content .=  $key."\t"; }
 
        // create line:
        $content .= (is_array($val)) ? implode("\t", $val) : $val;
        $content .= "\n";
    }
 
    if (file_exists($filepath) && !is_writeable($filepath)){ 
        return false;
    }
    if ($fp = fopen($filepath, 'w+')){
        fwrite($fp, $content);
        fclose($fp);
    }
    else { return false; }
    return true;
}
 
 
// load the saved array:
$reloaded_array = load_tabbed_file($filepath, true);
 
print_r($reloaded_array);
// returns the array from above
?>
User avatar
angelicodin
Forum Commoner
Posts: 81
Joined: Fri Nov 13, 2009 3:17 am
Location: Oregon, USA

Re: saving, loading & setup of user data via .txt files

Post by angelicodin »

question, why not use MySQL?
Disloxic
Forum Newbie
Posts: 2
Joined: Tue Nov 17, 2009 1:41 pm

Re: saving, loading & setup of user data via .txt files

Post by Disloxic »

Yeah your right actually, I should use MYSQL. That way i will be able to interogate the data.

Back to the drawing board.

Sorry peeps.

Would still be good to see a solution for this though using .txt files.
User avatar
Weiry
Forum Contributor
Posts: 323
Joined: Wed Sep 09, 2009 5:55 am
Location: Australia

Re: saving, loading & setup of user data via .txt files

Post by Weiry »

Im glad to see you decided to use a MySQL database to do this :)

However it would be entirely possible to do it. (For argument sake here is some example code [never tested, example only])

All you would need to is try to open the user's file, if not, loop through each file in the directory checking the filename of each until you got to a point where the next file didnt exist and then create a default one.

Could possibly look something like the below.

Code: Select all

$dir = "saveDir";
$str1 = "user_id_000001.txt"; 
if(fopen($dir."/".$str1, "r")){
    $str1_handle = fopen($str1, "r");
    // load the file
    $str1_contents = fread($str1_handle, filesize($str1)); 
    fclose($str1_handle); 
    //modify the file and then save it
}else{
    // create a new file
    if (is_dir($dir)) {
        $dir .= "/";
        if ($dh = opendir($dir)) {
            $i = 1;
                while (($file = readdir($dh)) !== false) {
                if($file == "." || $file == ".." || $file == "index.php"){
                    continue;
                }
                if(!$file){
                    // create new user file
                    // user_id_{$i}.txt  -- you would need to format $i in order to set the correct number of 0's
                    break;
                }
                $i++;
            }
            closedir($dh);
        }else{
            print "Error: Could not open directory {$dir}";
        }
    }else{
        print "Error: '{$dir}' is not a directory";
    }
}
Post Reply