Archive

Archive for the ‘Php’ Category

Simple but good encrypt user password script

October 27th, 2011 No comments

In reference to the latest “Swedish password hacking scandal“:

MD5 hashed password are still widely used for storing passwords in  a database. Here’s Andrew Moore‘s contribution to help prevent this in the future, using Bcrypt. If you don’t have BCrypt installed, use phppass

<?php

class Bcrypt {
private $rounds;
public function __construct($rounds = 12) {
if(CRYPT_BLOWFISH != 1) {
throw new Exception(“bcrypt not supported in this installation. See http://php.net/crypt”);
}

$this->rounds = $rounds;
}

public function hash($input) {
$hash = crypt($input, $this->getSalt());

if(strlen($hash) > 13)
return $hash;

return false;
}

public function verify($input, $existingHash) {
$hash = crypt($input, $existingHash);

return $hash === $existingHash;
}

private function getSalt() {
$salt = sprintf(‘$2a$%02d$’, $this->rounds);

$bytes = $this->getRandomBytes(16);

$salt .= $this->encodeBytes($bytes);

return $salt;
}

private $randomState;
private function getRandomBytes($count) {
$bytes = ”;

if(function_exists(‘openssl_random_pseudo_bytes’) &&
(strtoupper(substr(PHP_OS, 0, 3)) !== ‘WIN’)) { // OpenSSL slow on Win
$bytes = openssl_random_pseudo_bytes($count);
}

if($bytes === ” && is_readable(‘/dev/urandom’) &&
($hRand = @fopen(‘/dev/urandom’, ‘rb’)) !== FALSE) {
$bytes = fread($hRand, $count);
fclose($hRand);
}

if(strlen($bytes) < $count) {
$bytes = ”;

if($this->randomState === null) {
$this->randomState = microtime();
if(function_exists(‘getmypid’)) {
$this->randomState .= getmypid();
}
}

for($i = 0; $i < $count; $i += 16) {
$this->randomState = md5(microtime() . $this->randomState);

if (PHP_VERSION >= ’5′) {
$bytes .= md5($this->randomState, true);
} else {
$bytes .= pack(‘H*’, md5($this->randomState));
}
}

$bytes = substr($bytes, 0, $count);
}

return $bytes;
}

private function encodeBytes($input) {
// The following is code from the PHP Password Hashing Framework
$itoa64 = ‘./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789′;

$output = ”;
$i = 0;
do {
$c1 = ord($input[$i++]);
$output .= $itoa64[$c1 >> 2];
$c1 = ($c1 & 0×03) << 4;
if ($i >= 16) {
$output .= $itoa64[$c1];
break;
}

$c2 = ord($input[$i++]);
$c1 |= $c2 >> 4;
$output .= $itoa64[$c1];
$c1 = ($c2 & 0x0f) << 2;

$c2 = ord($input[$i++]);
$c1 |= $c2 >> 6;
$output .= $itoa64[$c1];
$output .= $itoa64[$c2 & 0x3f];
} while (1);

return $output;
}
}

$bcrypt = new Bcrypt(10);
$password = “agoodpassword”;echo $password;
$hash = $bcrypt->hash($password);echo ” = “.$hash.”<br>”;
$isGood = $bcrypt->verify(‘agoodpassword’, $hash);
if ($isGood) echo “OK<br/><br/>”;
else echo “NOT OK<br/><br/>”;

//Look, same password, different output! Mmmm, salt.

$bcrypt = new Bcrypt(10);
$password = “agoodpassword”;echo $password;
$hash = $bcrypt->hash($password);echo ” = “.$hash.”<br>”;
$isGood = $bcrypt->verify(‘agoodpassword’, $hash);
if ($isGood) echo “OK<br/><br/>”;
else echo “NOT OK<br/><br/>”;

?>

Quick and dirty url shortener

July 6th, 2011 No comments

I neeeded a simple URL shortener for a framed image site (the framing wasn’t my idea). It had to work on non-php pages, so I came up with an iframe solution.

url/index.php (this file looks up the shortened URL and redirects)

<?php
$link = mysql_connect('localhost', 'user', 'password') or die('Could not connect: ' . mysql_error());
mysql_select_db('url') or die('Could not select database');
// Performing SQL query
$query = "SELECT * FROM links WHERE linkin = '".mysql_real_escape_string($_GET['u'])."'";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$line = mysql_fetch_array($result, MYSQL_ASSOC);
header("Location: ".$line['linkout']." ");
?>
url/iframe.php (this file looks up or creates a short url, and gets the url to be processed from the url of the embedded iframe src. And then displays the link so the user can copy it.
<?php
//Check to only allow the URL shortener to work from certain domains
if (strstr($_SERVER["HTTP_REFERER"],"example.com"))
{
$link = mysql_connect('localhost', 'user', 'password') or die('Could not connect: ' . mysql_error());
mysql_select_db('url') or die('Could not select database');
// Performing SQL query
$query = "SELECT * FROM links WHERE linkout = '".mysql_real_escape_string($_GET['url'])."'";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$num_rows = mysql_num_rows($result);
if ($num_rows==0) // if no match, create a new shortened url
{
$id=rand(10000,99999);
$shorturl=base_convert($id,20,36);
$query = "INSERT INTO links (linkout,linkin) VALUES ('".mysql_real_escape_string($_GET['url'])."','".$shorturl."')";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
echo 'Link to this page:<br><a href="http://example.com/url/?u='.$shorturl.'">http://img.example.com/url/?u='.$shorturl.'</a>';
}
else
{
$line = mysql_fetch_array($result, MYSQL_ASSOC);
echo 'Link to this page:<br><a href="http://example.com/url/?u='.$line['linkin'].'">http://img.example.com/url/?u='.$line['linkin'].'</a>';
}
} //End domain check
?>
</body>

contentpage.html (this is the page on which you want to display the shortened link, in my case a framed page)
The trick is getting the page url and passing it to the php iframe as a url parameter.  

<head>
<script type="text/javascript">

function sURL() {
	var href = escape(document.location.href);
	var site = "http://img.example.com/url/iframe.php?url="+href;
	document.getElementById('myIframe').src = site;
}
</script>
</head>
<body onLoad="sURL();">
<iframe id="myIframe" frameborder="0" name="myIframe" src="http://img.example.com/url/load.html" width="200" height="40" scrolling="no"></iframe>
</body>

url/load.html (this file is just a filler, displays a loader. Could also just be an empty file)
Get one at www.ajaxload.info

<html>
<body>
<img src="ajax-loader.gif">
</body>
</html>

If you have any questions, or if it doesn’t work as expected, just post a comment.

Categories: Php, Programming Tags: , , , ,

How to run php script every 15 minutes with launchd

February 25th, 2011 No comments

On Mac OS X 10.6.6 I wanted a php script to be run every fifteen minutes past the hour , to check if something has been scheduled to run. I tried to use Lingon, but it couldn’t do exactly this. So I searched and found out I had to use an array.

The script below will use wget to run a php script at 00, 15, 30 and 45 minutes, every hour. Put it in /Library/LaunchAgents
and call it something like com.example.phpcheck.plist and restart the Mac.

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE plist PUBLIC “-//Apple//DTD PLIST 1.0//EN” “http://www.apple.com/DTDs/PropertyList-1.0.dtd”>
<plist version=”1.0″>
<dict>
<key>Label</key>
<string>no.medieweb.autosend</string>
<key>ProgramArguments</key>
<array>
<string>/opt/local/bin/wget</string>
<string>-q</string>
<string>–delete-after</string>
<string>http://example.com/script.php</string>
</array>
<key>ServiceDescription</key>
<string>Check script every 15 minutes</string>
<key>StartCalendarInterval</key>
<array>
<dict>
<key>Minute</key>
<integer>0</integer>
</dict>
<dict>
<key>Minute</key>
<integer>15</integer>
</dict>
<dict>
<key>Minute</key>
<integer>30</integer>
</dict>
<dict>
<key>Minute</key>
<integer>45</integer>
</dict>

</array>
</dict>
</plist>