Archive

Archive for February, 2009

Concept unit converter

February 12th, 2009

Introduction

This is my fourth guide and is, like my prime generator, just some code I did for fun, while I was bored in front of my computer:)
So what are we going to do today? Well, we’re going to program a unit converter “Google-style”. What I wanted to do was to get a user to input a unit. For instance “4 pounds” and then the script would output how much this was in several other units. And because units like “pounds” can be addresses in many ways (like “lb”, “lbs”, “pound”, and so on) I wanted to make the script understand every single of them and use them as if the user had used the input “pounds”.

The code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Concept unit converter
echo "You can use this script to convert from/to any of the most common units in mass, distance and speed<br/>Just enter, for instance: 13 km, and then the system will calculate how long 13 km is in other units.";
echo '<form action="test.php" method="get"><input type="text" name="q" size="15"/><input type="submit" value="submit"/></form>';
$input = strtolower($_GET['q']);
$number = floatval($input);
list( , $unit) = preg_split("/[\s,.1234567890]+/", $input);
$original_unit = $unit;
//Mass
$allowed["mass"] = array("kilogram" => "kg", "kilograms" => "kg", "kgs" => "kg", "grams" => "g", "gram" => "g", "lb" => "lbs", "pounds" => "lbs", "pound" => "lbs", "ounces" => "ounce", "stones" => "stone");
$conv["mass"] = array("kg" => 1, "lbs" => 2.204623, "g" => 1000, "stone" => 0.157473, "ounce" => 35.27);
 
// Distance
$allowed["distance"] = array("meter" => "m", "meters" => "m", "kilometer" => "km", "kilometers" => "km", "inch" => "in", "inches" => "in", "mile" => "mi", "miles" => "mi", "yard" => "yd", "yards" => "yd");
$conv["distance"] = array("m" => 1, "km" => 0.001, "in" => 39.37007874, "mi" => 0.0006213712, "yd" => 1.093613);
 
// Speed / velocity
$allowed["speed"] = array("kmh" => "km/h", "mps" => "m/s", "kms" => "km/s");
$conv["speed"] = array("km/h" => 1, "mph" => 0.6213712, "m/s" => 0.2777778, "km/s" => 0.0002777778);
 
$types = array("mass", "distance", "speed");
 
foreach($types as $type){
	if(array_key_exists($unit,$allowed[$type]) || array_key_exists($unit,$conv[$type])){
		if(array_key_exists($unit,$allowed[$type]))
			$unit = $allowed[$type][$unit];
		echo "<table><tr><td style=\"text-align:right;\">";
		echo "<b>" . number_format($number,2,"."," ") . "</b></td><td><b> " . $original_unit . "</b></td></tr>";
		$number = $number/$conv[$type][$unit];
		foreach($conv[$type] as $unit_conv => $conv_ratio){
			if($unit != $unit_conv)
				echo "<tr><td style=\"text-align:right;\">" . number_format($number*$conv_ratio,2,"."," ") . "</td> <td>$unit_conv</td></tr>";
		}
		echo "</table>";
	}
}

It is clear from the code that the array $allowed[] specifies what terms are allowed in the script and it’s a translation table to the correct unit (”the correct unit” is specified by you). The array $conv[] contains the conversion ratio. As you see from the code the conversion ratio is always relative to the first unit in $conv[].

Good luck converting:D

Important note: This script can only be used for units with a specific ratios between them. This means that it for instance cannot be used for converting Celsius to Fahrenheit and vice versa.

Ricehigh Micro guides , ,

Cookie security

February 2nd, 2009

Introduction

When using cookies for login systems it’s very common to store the username and a hashed password. This method is nothing near ideal, since cookie theft is a very common phenomenon, whereby a potential hacker will be able to brute force your user’s password. What you want to do instead is creating a cookie containing 3 values: The username, a long random string and an expirery date. By putting the cookie information in a database as well, we can determine the cookies validity.

How to do it

NOTE: This guide presumes that you’ve already got a login system and the variables $username and $id is respectively the username and user id in your userdatabase

First you need to create a MySQL database table with the following data:

  • id, int(11), unsigned, auto_increment, primary key
  • user, varchar(50)
  • random, varchar(64)
  • expire, varchar(40)
  • uid, int(11)

When you have authorized the user’s login data, you will generate the cookie information somewhat like this:

1
2
3
4
5
6
7
8
$random = hash(sha256,(uniqid(rand(), true)) . (uniqid(rand(), true)));
$expire = time() + 60*60*24*30; // current time + expirery time (here: 30 days)
$name   = "login"; // Name of the cookie
$value  = "$username\n$random\n$expire"; // Value of the cookie
$query = "INSERT INTO `cookie_user_db` (`id`,`user`,`random`,`expire`,`uid`) VALUES (NULL, '$username', '$random', '$expire', '$id_db')";
mysql_query($query);
$path   = "/"; // The cookie will work in all folders on present domain.
setcookie($name, $value, $expire, $path);

In the code above it’s presumed that the $username string has already been properly evaluated, to prevent from mysql-injection attacks. See more here.

Now we have a cookie with our wanted data, and a copy of those data in our database.

When a user, who is not logged in, comes to your site, who has a cookie, we want to determine wether the given data is valid:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
if($_COOKIE['login']){
	$info = explode('\n',$_COOKIE['login']); // Devides the cookie in it's seperable values: 1) Username, 2) A unique random number and 3) the expirery date for the cookie.
	$username = mysql_escape_string($info[0]); // mysql_escape_string is used to prevent mysql injection attacks.
	$random = mysql_escape_string($info[1]);
	$expire = mysql_escape_string($info[2]);
 
	if($username && ($username == htmlentities($username)) && $random && $expire){ // Checks if a username is present and wether the username holds special characters.
		$query = "SELECT * FROM `cookie_user_db` WHERE `user` = '$username' AND `random` = '$random' AND `expire` = '$expire'";
		$result = mysql_query($query);
		if(mysql_num_rows($result) >= 1){
			while($r=mysql_fetch_array($result)){
				$username_db= mb_strtolower($r["user"]);
				$random_db=$r["random"];
				$expire_db = $r["expire"];
				$uid_db = $r["uid"];
				}
 
			//checks wether the supplied user exists in the user database
			$result = mysql_query("SELECT * FROM `$user_db` WHERE `user` = '$username' AND `id` = '$uid_db'");
			if(mysql_num_rows($result) >= 1){
				// At the basis the user isn't allowed to login:
				$login = false;
				if (($expire_db == $expire) && $expire > time()){ // Checks wether 1) the expirery date of the database matches the one supplied in the cookie and 2) wether the expirery date is still valid.
					// Gives $login a true value
					$login = true;
				}
 
				// Checks wether $login is true
				if ($login == true) {
					// Session variable "access" is given a true value.
					$_SESSION['access'] = true;
 
					// The user is sent to the administration page.
					header("Location: admin_website.php");
					exit;
				}
				//If $login is not true, the user is sent back to the login page.
				else {
					include("login.php");
					exit;
				}
			}
		}
	}
}
// If no cookie is found, the user is sent back to the login page
include("login.php");
exit;

Ricehigh Security , , ,

How to generate primes

February 2nd, 2009

Introduction

Here’s a micro guide on how to generate prime numbers in a given interval with PHP.

A prime number is a natural number (a positive integer) which has exactly two distinct natural number divisors (1 and the number itself).

The Code

What we want to do is to create a function that takes a minimum and a maximum value of primes values we want to find. Then we try to divide the number by every number bigger than 1 and smaller than itself and determine if it has a remainder on any of the calculation. If it has on every caltulation we’ve got a prime, if not, we don’t.
I’ve made the script to only use odd numbers, because 2 is the only non-odd prime.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php
function prime_generator($from,$to,$return=false){
	if(!($from%2))
		$from++;
	if($from <= 2){
		$from = 3;
		if($return)
			$primes .= "2, ";
		else
			echo "2, ";
	}
 
	for($x=$from; $x <= $to; $x+=2){
		$prime=true;
		for($y=$x-1;$y>1;$y--){
			if(!($x%$y)){
				$prime=false;
				}
		}
		if($prime){
			if($return)
				$primes .= $x . ", ";
			else
				echo $x . ", ";
		}
	}
	if($return)
		return $primes;
}
$primes = prime_generator(0,100, true);
echo $primes;
?>

You can use the function either with or without the $return parameter set. If it’s set to true it will return all primes in the given interval, if not, it gives the output right away.

Ricehigh Micro guides , , ,