sm21guy
sm21guy

Reputation: 626

store data into a text file using php?

i am trying to store data in a text file, something like an array into a text file using php instead of storing into mysql database.

for example here are the data to be stored in a text file

name=>john
age=>25
location=>australia

then after saving it to a text file , how can I get the contents out and parse it with php , for like php can find the name , age and location and echo it out(something like parsing an array)

I need it for storing the data into a text file so it can be easily access from other domains without requiring to be on the same domain , connect to database , get the data from database. I am looking for a speedy solution. :)

I'm not sure which direction should I look into for this kind of functionality , hoping someone can point me out.

Upvotes: 5

Views: 20940

Answers (7)

proseosoc
proseosoc

Reputation: 1354

Functions for some idea, not the best code, but may have fast read/write if thousands of files, not tested:

(Maybe using $GLOBALS is not good here, learn good cooding practices)

<?php

(function () {

    $pre = 'func__storage__';

    $GLOBALS[APP][$pre . 'divide'] = [
        // contains folder paths for which "divide in subfolders" is enabled for performance
        'single' => [
            'car-names/',
            'vid-html-cache/'
        ],
        'json' => [
            'vid-html-cache__info/'
        ],
        'php-array' => [] // Only option to read this format
    ];

    $GLOBALS[APP][$pre . 'getPathParts'] = function ($path) {
        $lastSlashIndex = strrpos($path, '/');
        if ($lastSlashIndex === false) {
            $folderPath = '';
            $fileName = $path;
        } else {
            $folderPath = substr($path, 0, $lastSlashIndex + 1);
            $fileName = substr($path, $lastSlashIndex + 1);
        }
        return [
            'folderPath' => $folderPath,
            'fileName' => $fileName,
        ];
    };

    $GLOBALS[APP][$pre . 'getDividePath'] = function ($fileName) {
        $fileNameLen = strlen($fileName);

        $divisionPath = $fileName[0] . '/';
        if ($fileNameLen > 1) {
            $divisionPath .= $fileName[1] . '/';
            if ($fileNameLen > 2) {
                $divisionPath .= $fileName[2] . '/';
                if ($fileNameLen > 3) $divisionPath .= $fileName[3] . '/';
            }
        }

        return $divisionPath;
    };

    $GLOBALS[APP][$pre . 'get'] = function ($p1) use ($pre) {
        if (
            !is_array($p1) ||
            !isset($p1['path']) ||
            !is_string($p1['path']) ||
            (isset($p1['type']) && ($p1['type'] !== 'json' && $p1['type'] !== 'php-array'))
        ) logNDie('$GLOBALS[APP]["func__storage__get"], $p1 required array keys/vals not set/valid');

        if (!isset($p1['type']) || $p1['type'] === 'single') { //assume its single
            $p1['type'] = 'single';
            $extension = '';
        } elseif ($p1['type'] === 'json') $extension = '';
        elseif ($p1['type'] === 'php-array') $extension = '.php';

        $p1['path'] = $GLOBALS[APP][$pre . 'getPathParts']($p1['path']);

        if (in_array($p1['path']['folderPath'], $GLOBALS[APP][$pre . 'divide'][$p1['type']]))
            $p1['path']['folderPath'] .= $GLOBALS[APP][$pre . 'getDividePath']($p1['path']['fileName']);

        $name = 'storage/' . $p1['type'] . '/' . $p1['path']['folderPath'] . $p1['path']['fileName'] . $extension;
        if ($p1['type'] === 'php-array') $toReturn = @include $name;
        else $toReturn = @file_get_contents($name);

        if ($p1['type'] === 'json') $toReturn = json_decode($toReturn, true);

        return $toReturn;
    };


    $GLOBALS[APP][$pre . 'set'] = function ($p1) use ($pre) { // array:$p1, keys:storageRoot(optional),type(optional),path,data
        if (
            !is_array($p1) ||
            !isset($p1['path']) ||
            !is_string($p1['path']) ||
            !isset($p1['data']) ||
            (isset($p1['type']) && ($p1['type'] !== 'json'))
        ) logNDie('$GLOBALS[APP]["func__storage__set"], $p1 required array keys/vals not set/valid');

        if (!isset($p1['type']) || $p1['type'] === 'single') { //assume its single
            $p1['type'] = 'single';
            if (!is_string($p1['data'])) logNDie('$GLOBALS[APP]["func"]["storage"]["write"], string not given for type "single"');

            $extension = '';
        } elseif ($p1['type'] === 'json') {
            if (!is_array($p1['data'])) logNDie('$GLOBALS[APP]["func"]["storage"]["write"], array not given for type "json"');

            $p1['data'] = json_encode($p1['data']);
            $extension = '';
        }

        $p1['storageRoot'] = $p1['storageRoot'] ?? 'storage/';
        $p1['path'] = $GLOBALS[APP][$pre . 'getPathParts']($p1['path']);

        if (in_array($p1['path']['folderPath'], $GLOBALS[APP][$pre . 'divide'][$p1['type']]))
            $p1['path']['folderPath'] .= $GLOBALS[APP][$pre . 'getDividePath']($p1['path']['fileName']);

        $folderPath = $p1['storageRoot'] . $p1['type'] . '/' . $p1['path']['folderPath'];
        if (!file_exists($folderPath)) mkdir($folderPath, 0775, true);
        return file_put_contents($folderPath . $p1['path']['fileName'] . $extension, $p1['data']);
    };

    $GLOBALS[APP][$pre . 'isPresent'] = function ($p1) use ($pre) {
        if (
            !is_array($p1) ||
            !isset($p1['path']) ||
            !is_string($p1['path']) ||
            (isset($p1['type']) && ($p1['type'] !== 'json' && $p1['type'] !== 'php-array'))
        )  logNDie('$GLOBALS[APP]["func__storage__isPresent"], $p1 required array keys/vals not set/valid');

        if (!isset($p1['type']) || $p1['type'] === 'single') { //assume its single
            $p1['type'] = 'single';
            $extension = '';
        } elseif ($p1['type'] === 'json') $extension = '';
        elseif ($p1['type'] === 'php-array') $extension = '.php';

        $p1['path'] = $GLOBALS[APP][$pre . 'getPathParts']($p1['path']);

        if (in_array($p1['path']['folderPath'], $GLOBALS[APP][$pre . 'divide'][$p1['type']]))
            $p1['path']['folderPath'] .= $GLOBALS[APP][$pre . 'getDividePath']($p1['path']['fileName']);

        return file_exists('storage/' . $p1['type'] . '/' . $p1['path']['folderPath'] . $p1['path']['fileName'] . $extension);
    };
})();

Usage Example:

$GLOBALS[APP]['func__storage__get'](['path' => 'test']);
$GLOBALS[APP]['func__storage__isPresent'](['path' => 'car-names/audi']);

Upvotes: 0

CCjump21
CCjump21

Reputation: 68

You should make a uniqid then they won't be able to access any other txt files in the server.

<?php

    #Get a secure filename
    $username = "myUsername"
    $filename = uniqid($username, true).".txt";

    //Create the array
    $userInfo = ["username" => $username, "points" => 0];

    // Store the data
    file_put_contents($filename, serialize($userInfo));

    // How to get the data
    $userInfo = unserialize(file_get_contents($filename));
    print($userInfo["points"]);
    //or
    print($userInfo["username"]);

?>

Upvotes: 1

undo
undo

Reputation: 277

I made a tiny library (~2 KB; <100 lines) that allows you to do just this: varDx

It has functions to write, read, modify, check and delete data. It implements serialization, and therefore supports all data types.

Here's how you can use it:

<?php
require 'varDx.php';
$dx = new \varDx\cDX; //create an object
$dx->def('file.dat'); //define data file

$val1 = "this is a string";
$dx->write('data1', $val1); //writes key to file
echo $dx->read('data1'); //returns key value from file

Upvotes: -1

And
And

Reputation: 75

//-- short -------------------------------------------

$data = [ "a" => "A",  "b" => "B", "c" => "C" ];
  echo '<br> data - array: ';
  var_dump($data);

file_put_contents('db.php', json_encode($data) );

//get
$g = json_decode(file_get_contents('db.php') , 1);  // 1 Array , 0  Object

  echo '<br><hr>short: var_dump($g): ';
  var_dump($g);    

//-- long -------------------------------------------//

$data = [ "a" => "A",  "b" => "B", "c" => "C" ];
  echo '<br> data - array: ';
  var_dump($data);
  echo '<br> json_encode($data): ';

$jdata = json_encode($data);
  var_dump($jdata); 
  echo'<hr>';
file_put_contents('db.php', $jdata);

//get
$jg = file_get_contents('db.php');
  echo ' $jg = file_get_contents(\'db.php\'); $jg : ';
  var_dump($jg);

  echo '<br> json_decode($jg , 1) //1 Array<br>';
$g = json_decode($jg , 1);  
  var_dump($g);

  echo '<br> json_decode($jg , 0)  //0 Object<br>';
$g = json_decode($jg , 0);
  var_dump($g);

Upvotes: 0

Māris Kiseļovs
Māris Kiseļovs

Reputation: 17305

Storing:
1. Use serialize() to serialize your array into a string
2. Write that string to text file using file_put_contents()

Reading:
1. Use file_get_contents to read text file
2. Use unserialize() to unserialize previously serialized array

serialize()/unserialize() can be replaced by json_encode()/json_decode()

Upvotes: 16

jbrtrnd
jbrtrnd

Reputation: 3843

These functions should do what you want :

function storeInTextFile($array,$path) {
    if(file_exists($path)) {
         $handle = fopen($path,'wb');
         fwrite($handle, arrayToString($array));
         fclose($handle);
    }
}

function arrayToString($array) {
    $string = '';
    foreach($array as $key => $value) {
        $string .= "{$key} => {$value}\n";
    }
    return $string;
}

function stringToArray($string) {
    $explodedString = explode('\n',$string);
    $returnArray = array();
    foreach($explodedString as $arrayValue) {
        list($key,$value) = explode(' => ',$arrayValue);
        $returnArray[$key] = $value;
    }

    return $returnArray;
}

Upvotes: 0

Thorsten Niehues
Thorsten Niehues

Reputation: 14472

You may use

In case you want to convert the array to an XML you might want to read this post: How to convert array to SimpleXML

Upvotes: 0

Related Questions