Archive for March, 2009

Create your own log file with php add text to a new line

I created this the other day for one my websites and find it very handy. For instance if you want to creat your very own log file of all your php and mysql errors youll have a nice convenient text file which contains all of your logs.
You can even take it that little bit further and create access logs or logs for particuarly actions etc. Its simple enough to code so just follow the steps below.

  1. Create a file called logfile.txt on your server (make sure you remember the path to that file).
  2. Insert the below functions either directly into your page, or into your functions page.

[sourcecode=php]//File will be rewritten if already exists
function append_file($filename,$newdata) {
$f=fopen($filename,”a”);
fwrite($f,$newdata);
fclose($f);
}
[/sourcecode]

3. Then all thats left is to just call that function like so below, a new line of text will be added to the bottom of the new logfile.txt file.

[sourcecode=php] //add more data ot the existing file
append_file(“../logs/logfile.txt”,”New text addedn”);[/sourcecode]

You can take this further if you wish and add a read file module.

  1. You can simply do that by adding the below function to your page.

[sourcecode=php]
function read_file($filename) {
$f=fopen($filename,”r”);
$data=fread($f,filesize($filename));
fclose($f);
return $data;
}
[/sourcecode]

  1. Once again you can use this function by simply calling in on your page.

[sourcecode=php]
$data=read_file(“test.txt”);
echo “Data in file : <b>$data</b>”;
[/sourcecode]

I hope this might be useful to someone else.

Php random password generator

I developed this the other day and think its a really useful bit of code to use if your looking to make yourself a strong password generator for your users.
[sourcecode language='php']
function generatePassword($length=9, $strength=0) {
$vowels = ‘aeuy’;
$consonants = ‘bdghjmnpqrstvzuacd’;
$consonants .= ‘BDGHJLMNPQRSTVWXZUACD’;
$vowels .= “AEUY”;
$consonants .= ’23456789′;
$consonants .= ‘@#$%!’;

$password = ”;
$alt = time() % 2;
for ($i = 0; $i < $length; $i++) {
if ($alt == 1) {
$password .= $consonants[(rand() % strlen($consonants))];
$alt = 0;
} else {
$password .= $vowels[(rand() % strlen($vowels))];
$alt = 1;
}
}
return $password;
}

[/sourcecode]

The function is called in the normal way something like below:

[sourcecode language='php']
$length=15;
$strength = 8;
$password = generatePassword($length,$strength);
[/sourcecode]

An example result of this password generator is below:

Your password: REWEMYAuHy$e

Enjoy!