Tuesday, September 23, 2008

Write your PHP script file

The PHP scripts will have the logic of rewriting the URL (you can use any other language, Perl for example).What the code will exactly look like is depend upon your requirement. But again, for the sack of completeness I will show you a working example. Note that the same script should work on both Windows and Linux without any modification.

#!/usr/bin/php
mysql_connect("localhost","username","password");
mysql_select_db("Database");

$filename = "log.txt";
if (!$handle = fopen("$filename", "a+")) {
echo "Cannot open file ($filename)";
exit;
}
while( $url = trim(fgets(STDIN)))
{
$sql = "select * from users order by rand() limit 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$name = $row['username'];
$today = date("j-n-Y, G:i:s");
if (fwrite($handle, $today."|".$url."|\r\n") === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
if(fwrite(STDOUT, $name.".html\r\n") === FALSE)
{
fwrite($handle, "CANT WRITE $url\n");
}
}
fclose($handle);
exit;
?>



Statement while( $url = trim(fgets(STDIN))) and fwrite(STDOUT,$name.".html\r\n") are important to note. First, rewriting program must keep iterate continuously, otherwise off course it will terminate, end of story. This is why I have used ‘while’ loop here. Second, there must be some mechanism in the program to take input and give output. For this we have statements fgets(STDIN) and fwrite(STDOUT, $name.".html\r\n"). In case if they dont work use $stdin = fopen('php://stdin', 'r'); $stdout = fopen('php://stdout','w'); and use $stdin in place of STDIN and use $stdout in place of STDOUT respectively. Refer to PHP manual for further help (search ’stdin’ in PHP manual).

Please feel free to add your comment for pointing out any mistake and/or to add any further information.

No comments: