I'm very new to php, I'm trying to create a simple function that will write the name of the person on people.txt file.
I started with the code below.
<?php
session_start();
$counter_name = "people.txt";
if (!file_exists($counter_name)) {
$f = fopen($counter_name, "w");
fwrite($f,"0");
fclose($f);
}
$f = fopen($counter_name,"r");
$person = fread($f, filesize($counter_name));
fclose($f);
$f = fopen($counter_name, "w");
fwrite($f, $person);
fclose($f);
Basically I to give user the website like this: www.mywebsite.com/person.php+personName
In the results, this person name will be added to people.txt file. If a new person will access this page, then the name of the new person will be added to the next line. Something like this:
person1;
person2;
person3;
...
Please some help to figure out the rest of this function.
function appendToFile($stringOrArray, $fileName, $eol = true)
$fp = fopen('people.txt', 'a');
$e = $eol ? PHP_EOL : '';
if(is_string($stringOrArray)){
fwrite($fp, $stringOrArray.$e); fclose($fp);
return true;
}
elseif(is_array($stringOrArray)){
foreach($stringOrArray as $v){
fwrite($fp, $v.$e);
}
fclose($fp);
return true
}
else{
die('$stringOrArray must be a String or Array');
}
return false;
}
appendToFile('Single String', 'people.txt');
appendToFile('Another Line', 'people.txt');
appendToFile(array('First Array Element' 'Second Array Element'), 'people.txt');
Note that you don't have to see if the file exists, since it will be created anyways. Also, I would create a class, more like:
class FileHandler{
private $fn, $fp, $md;
public function __construct($fileName){
$this->fn = $fileName;
}
public function getFileName(){
return $thsi->fn;
}
public function setMode($mode){
$this->md = $mode; $this->fp = fopen($this->fn, $mode);
return $this;
}
public function getFilePointer(){
return $this->fp;
}
public function getMode(){
return $this->md;
}
private function fc(){
fclose($this->fp);
}
public function exec($maybe, $eol = true){
$fp = $this->fp;
$e = $eol ? PHP_EOL : '';
switch($this->md){
case 'r':
break;
case 'r+':
break;
case 'w':
break;
case 'w+':
break;
case 'a':
if(is_string($maybe)){
fwrite($fp, $maybe.$e); $this->fc();
return true;
}
elseif(is_array($maybe)){
foreach($maybe as $v){
fwrite($fp, $v.$e);
}
$this->fc();
return true;
}
else{
die('$maybe must be a String or Array with mode \'a\'');
}
break;
case 'a+':
break;
case 'x':
break;
case 'x+':
break;
case 'c':
break;
case 'c+':
break;
default:
// maybe you want a mode if none is selected
break;
}
return false;
}
}
$fh = new FileHandler('people.txt');
$fh->setMode('a')->exec(array('value 0', 'value 1', 'value 2'));
Of course, you have to add to the modes and write a bunch of other code. Have fun!