PHP
Running php scripts using cron
Lots of programmers like PHP for its ability to code and develop web applications fast. Code-debugging is a lot easier than with PERL or C. However, there is one thing a lot of developers are puzzled about, “How to run PHP Scripts with crontab?”
Cron is normally available on all Unix and Linux distributions; if you cannot access it, contact your root or server administrator. It is a daemon which allows you to schedule a program or script for a specific time of execution. If you want to learn more about cron, click here or type “man crontab” at your command prompt.
I have found myself in the need to run PHP scripts at specific times. For example, to update the content of a website, to remove expired articles, to send out e-mails on a given date and a lot more. While some may think that this is were PHP is doomed, I will show you how it’s done.
A Manual crontab?
The first solution that came to my mind was to run the script directly from my browser (e.g. http://www.mydomain.com/script.php). Since I need to run my script on a regular basis, I squashed that idea. My goodness, all the extra hassle is ridiculous.
An include?
Another possible solution is to include the script in one of the pages of the site, for example the very first: “index.php”. (<? include “cron.php”; ?>)
The drawbacks to this solution are, that it works but when someone accesses the “index.php”. This could cause a lot of extra overhead produced by the script. If you get a lot of traffic, the script is executed 1000 times a day and adds a lot of usage on the database and the server.
On the other hand, if you do not get a lot of traffic, or people tend to access your site over another file, this will not work out as well. If you need to run the script on a regular intervals, this is not a solution.
Crontab!
Let’s suppose you either know what cron is or have read about it using the link above. We want to run our script once a minute. So where do we go from here? Here is how you can accomplish this task.
Your PHP setup
You will need to find out the answer to the following question, “Is my PHP installed as CGI or as an Apache module?”. To find out do the following: Create a new file, name it info.php (just an example), and put in the following code, “<? phpinfo(); ?>”. Upload to your webserver and go to it with your browser.
Now check for Server API (4th item from the top), if it says “CGI”, you have PHP compiled as CGI, if it reads “Apache”, you have it running as an Apache module.
Compiled CGI
If the answer to the question above is “CGI” then you need to add a line to your PHP script. It has to be the first line of your script and must contain your server’s PHP executable location:
#!/usr/local/bin/php -q
That looks a lot like PERL now, doesn’t it? After that let’s add the necessary command to our crontab. Edit /etc/crontab and add the following line:
* * * * * php /path/to/your/cron.php
Execute the following from the command line:
Shell> crontab crontab
Be sure your “script.php” has the necessary permissions to be executable (“chmod 755 script.php”).
Now you are all set!
Apache module
If your PHP is installed using the Apache module, the approach is a little different. First, you need access to Lynx (Lynx Browser for more information). Lynx is a small web browser, generally available on Unix and Linux.
Running your PHP script will not require you to add any additional lines. You simply have to edit your /etc/crontab file and add the following line:
* * * * * lynx -dump http://www.somedomain.com/cron.php
Please note that in general, you have to specify the entire URL (with “http://” and so on). But depending on your Lynx’s configuration, the URL might be relative; I suggest always using the absolute reference as in my example above – it always works.
Again execute the following from the command line:
Shell> crontab crontab
That all it takes to get a cron job setup using PHP. Hope you have learned something new and will use it to save overhead time on the server and on the developer.
Alexa ranking using php script
if you want to check the your website ranking as per alexa so you can use the following code in your php projects.
http://data.alexa.com/data?cli=10&dat=s&url=how2dev.com
“http://data.alexa.com/data” this file will return the xml format output. Using the XML output or reading xml file we can easily fetch the our or any website ranking.
Use the following function for getting the alexa website ranking.
<?php function AlexaRank( $url ) { preg_match( '#<POPULARITY URL="(.*?)" TEXT="([0-9]+){1,}"/>#si', file_get_contents('http://data.alexa.com/data?cli=10&dat=s&url=' . $url), $p ); return ( $p[2] ) ? number_format( intval($p[2]) ):0; } echo "wordpressapi.com Rank as per alexa.com: "; echo AlexaRank('how2dev.com'); ?> if you want to check the multiple website ranking in one shot than use the following PHP code. <?php $domains = array( 'google.com', 'ask.com', 'yahoo.com', 'bing.com' ); foreach ( $domains as $domain ) echo $domain, ' - ', AlexaRank( $domain ), '<br />', PHP_EOL; ?>
Dynamic Navigation Menus
Next code demonstrates how to build a simple menu function with the current page high-lighted.
Code:
<?php require_once('menu.php'); $page = isset($_GET['page']) ? $_GET['page'] : 'home'; ?> <html> <head> <title>Page - <?=$page?> <style type="text/css"> .inactive, .active { padding:2px 2px 2px 20px; } .inactive { background:#ddd; } .active { background:black; font-weight:bold; } .inactive a { text-decoration:none; } .active a { text-decoration:none; color:white; } </style> </title> </head> <body> <table> <tr> <td width="200" valign="top"> <?php page_menu($page); ?> </td> <td width="600" valign="top"> Page: <?=$page?> </td> </tr> </table> </body> </html>
Save this code as index.php
<?php function menu_item($id, $title, $current) { $class = ($current == $id) ? "active" : "inactive"; ?> <tr><td class=<?=$class?>> <a href="index.php?page=<?=$id?>"><?=$title?></a> </td></tr> <?php } function page_menu($page) { ?> <table width="100%"> <?php menu_item('home', 'Home', $page); ?> <?php menu_item('about', 'About', $page); ?> <?php menu_item('browse', 'Browse', $page); ?> <?php menu_item('download', 'Download', $page); ?> </table> <?php } ?>
Save this code as menu.php
Drop-Down Stickies
Attaching a drop-down sticky to a word or phrase in your document is an easy way to add valuable information close to the word, without obscuring it.
Code:
<?php
function start_link($text, $nextid)
{
$idtext = $nextid;
?>
<a href="javascript:void drop('<?=$idtext?>');">
<span id="a_<?=$idtext?>"><?=$text?></span>
</a>
<div id="<?=$idtext?>" class="drop" style="display:none">
<table cellspacing="0" cellpadding="0" width="170">
<tr>
<td valign="top" width="20">
<a href="javascript:void close(<?=$idtext?>)">
<img src="close.gif" border="0" />
</a>
</td>
<td valign="top" width="150">
<?php
}
//--------------------
function end_link()
{
?>
</td>
</tr>
</table>
</div>
<?php
}
//-----------------
function link_header()
{
?>
<style type="text/css">
.drop
{
padding:5px;
font-size:small;
background:#eeeeee;
border:1px solid black;
position:absolute;
}
</style>
<script type="text/javascript">
function drop(sid)
{
aobj = document.getElementById("a_" + sid);
divobj = document.getElementById(sid);
divobj.style.top = (aobj.offsetBottom + 10) + "px";
divobj.style.left = (aobj.offsetLeft + 10) + "px";
divobj.style.display = "block";
}
function close(sid)
{
divobj = document.getElementById(sid);
divobj.style.display = "none";
}
</script>
<?php
}
?>
<html>
<head>
<?php link_header(); ?>
</head>
<body>
Hello <?php start_link("my friend", 1); ?>
Jimmy <?php end_link(); ?> .How are you?
</body> </html>
Save this code as drop-down.php
Section Content with Spinners
This code shows how to create sections on your page with spinners that open and show section of the content interactively.
Code:
<?php
function start_section($id, $title)
{
?>
<table cellspacing="0" cellpadding="0">
<tr>
<td width="30" valign="top">
<a href="javascript:void twist('<?=$id?>');">
<img src="up.gif" border="0" id="img-<?=$id?>" />
</a>
</td>
<td width="90%">
<h1><?=$title?></h1>
<div style="display:none;position:absolute" id="<?=$id?>" class="content">
<?php
}
function end_section()
{
?>
</div>
</td>
</tr>
</table>
<?php
}
?>
<html>
<head>
<style type="text/css">
body{font-family:Verdana;}
h1{font-size:medium;border-bottom:1px solid black;}
.content{font-size:small; margin-left:10px; padding:10px;}
</style>
<script type="text/javascript">
function twist(sid)
{
imgobj = document.getElementById("img-" + sid);
divobj = document.getElementById(sid);
if(imgobj.src.match("up.gif"))
{
imgobj.src = "down.gif";
divobj.style.position = "relative";
divobj.style.display = "block";
}
else
{
imgobj.src = "up.gif";
divobj.style.display = "none";
divobj.style.position = "absolute";
}
}
</script>
</head>
<body>
<?php start_section("first", "section one"); ?>
first part first part first part first part first part.
first part first part first part first part first part.
<?php end_section(); ?>
<?php start_section("sec", "section two"); ?>
section two section two section two section two section two.
section two section two section two section two section two.
<?php end_section(); ?>
</body>
</html>
Save the as spinners.php
Caching Output
High-traffic sites can often benefit from caching of pages, to save processing of the same data over and over again.
Put the first function cache_start in the beginning of php script and the second cache_end in the end of script.
Code:
function cache_start($_time, $dir)
{
$cachefile = $dir.'/'.sha1($_SERVER['REQUEST_URI']).'.html';
$cachetime = $_time;
ob_start();
if(file_exists($cachefile) && (time( )-$cachetime < filemtime($cachefile)))
{
include($cachefile);
ob_end_flush();
exit;
}
}
//——————————————–
function cache_end($dir)
{
$cachefile = $dir.'/'.sha1($_SERVER['REQUEST_URI']).'.html';
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
}
//————————————–
$_time : cache time
$dir : directory to cache files
Catching Keywords from Search Engines
With this class we try to catch some keywords from google, yahoo and bing search engines.
Code:
<?php class keywords { private $referer; private $_e; public $keywords; public function __construct() { if($_SERVER['HTTP_REFERER']) { if(preg_match("#\.google|search\.yahoo|\.bing#", $_SERVER['HTTP_REFERER'])) { $this->referer = urldecode($_SERVER['HTTP_REFERER']); } else { return; } } else { return; } } private function getSeparators() { $this->_e = (preg_match("#\?q=|\?p=#", $this->referer)) ? "\?" : "&"; } public function getKeywords() { if(!empty($this->referer)) { $this->getSeparators(); //google if(preg_match("#\.google#", $this->referer)) { $m_ = preg_match("#{$this->_e}q=(.+?)&#si", $this->referer, $this->keywords); if($m_ == 0) { return false; } } //yahoo elseif(preg_match("#search\.yahoo#", $this->referer)) { $m_ = preg_match("#{$this->_e}p=(.+?)\&#si", $this->referer, $this->keywords); if($m_ == 0) { return false; } } //bing elseif(preg_match("#\.bing#", $this->referer)) { $m_ = preg_match("#{$this->_e}q=(.+?)\&#si", $this->referer, $this->keywords); if($m_ == 0) { return false; } } else { return false; } return $this->keywords[1]; } else { return false; } } } ?>
Save this script as keywords_class.php
Now let’s try to print these keywords.
Code:
<?php require_once('keywords_class.php'); $keywordsObj = new keywords(); $keys = $keywordsObj->getKeywords(); if($keys) { print $keys; } else { print "ooops"; } ?>
Save this code as index.php
Drag - Drop Lists
This code uses an open source drag - drop library from Tool-Man to create drag-drop lists. Download and unpack the drag-drop libraries onto your server.
Code:
<html>
<head>
<title>Drag - Drop Lists</title>
<style>
#cities li {margin:0px;}
ul.box li {margin:3px;}
ul.sortable li {position:relative;}
ul.box
{
list-style-type:none;
padding:0px;
margin:2px;
width:20em;
font-size:13px;
font-family:"Times New Roman", Times, serif;
}
ul.box li
{
cursor:move;
padding:2px 2px;
border:1px solid #cccccc;
background:#eee;
}
.clickable a
{
display:block;
text-decoration:none;
cursor:pointer;
cursor:hand;
}
clickable li:hover
{
background:#f6f6f6;
}
</style>
<script type="text/javascript" src="source/org/tool-man/core.js"></script>
<script type="text/javascript" src="source/org/tool-man/events.js"></script>
<script type="text/javascript" src="source/org/tool-man/css.js"></script>
<script type="text/javascript" src="source/org/tool-man/drag.js"></script>
<script type="text/javascript" src="source/org/tool-man/coordinates.js"></script>
<script type="text/javascript" src="source/org/tool-man/dragsort.js"></script>
<script type="text/javascript" src="source/org/tool-man/cookies.js"></script>
<script type="text/javascript">
<!--
var dragsort = ToolMan.dragsort();
var junkdrawer = ToolMan.junkdrawer();
window.onLoad = function()
{
dragsort.makeListSortable(document.getElementById("cities"), verticalOnly, saveOrder);
}
function verticalOnly(item)
{
item.toolManDragGroup.verticalOnly();
}
function saveOrder(item) { }
function prepFields()
{
document.getElementById("cities_txt").value = junkdrawer.
serializeList(document.getElementById("cities"));
return true;
}
//-->
</script>
</head>
<body>
<ul id="cities" class="box">
<li>Paris</li>
<li>Rome</li>
<li>Athens</li>
</ul>
<form method="post" action="display.php">
<input type="hidden" name="cities" value="" id="cities_txt" />
<input type="submit" onclick="prepFields();" />
</form>
</body>
</html>
Save the code as dragdrop.html
The simple code below used to print out values from the list.
Code:
<html> <body> You chose: <?=$_POST['states']?> </body> </html>
Save the code as display.php.
Magnet Link
This PHP function return the urn (Uniform Resource Name) formed from the content hash of a particular torrent file. The urn refering to the Base32 encoded hash of the file.
Code:
function base32_encode ($hash)
{
$outString = '';
$compBits = '';
$BASE32_TABLE = array(
'00000' => 0x61,
'00001' => 0x62,
'00010' => 0x63,
'00011' => 0x64,
'00100' => 0x65,
'00101' => 0x66,
'00110' => 0x67,
'00111' => 0x68,
'01000' => 0x69,
'01001' => 0x6a,
'01010' => 0x6b,
'01011' => 0x6c,
'01100' => 0x6d,
'01101' => 0x6e,
'01110' => 0x6f,
'01111' => 0x70,
'10000' => 0x71,
'10001' => 0x72,
'10010' => 0x73,
'10011' => 0x74,
'10100' => 0x75,
'10101' => 0x76,
'10110' => 0x77,
'10111' => 0x78,
'11000' => 0x79,
'11001' => 0x7a,
'11010' => 0x32,
'11011' => 0x33,
'11100' => 0x34,
'11101' => 0x35,
'11110' => 0x36,
'11111' => 0x37,
);
/* Turn the compressed string into a string that represents the bits as 0 and 1. */
for ($i = 0; $i < strlen($hash); $i++) {
$compBits .= str_pad(decbin(ord(substr($hash,$i,1))), 8, '0', STR_PAD_LEFT);
}
/* Pad the value with enough 0's to make it a multiple of 5 */
if((strlen($compBits) % 5) != 0) {
$compBits = str_pad($compBits, strlen($compBits)+(5-(strlen($compBits)%5)), '0', STR_PAD_RIGHT);
}
/* Create an array by chunking it every 5 chars */
$fiveBitsArray = split("\n",rtrim(chunk_split($compBits, 5, "\n")));
/* Look-up each chunk and add it to $outstring */
foreach($fiveBitsArray as $fiveBitsString) {
$outString .= chr($BASE32_TABLE[$fiveBitsString]);
}
return $outString;
}
Parametres:
dn - Filename
xl - Size in bytes
xt - urn containing file hash
as - Web link to the file online
xs - P2P link
kt - Key words for search
mt - link to the metafile that contains a list of magneto
xt is the most important part of magnet links.
Sites that use this kind of magnet links: btscene.com , mininova.org
Pop-Up Hints
Download the overLIB javascript library.
Code:
<?php
function popup($txt, $popup)
{
?>
<a href="javascript:void(0);"
onmouseover="return overlib('<?=$popup?>');"
onmouseout="return nd();">
<?=$txt?>
</a>
<?php } ?> <html> <head> <title>Popup hints</title> <script type="text/javascript" src="overlib.js"></script> </head> <body> <div id="over" style="position:absolute;visibility:hidden;z-index:1000;"> </div> Greece is a small
<?php popup( 'country ', 'Small but very beautiful<br /> with many islands' ); ?> in southeast Europe. </body> </html>
Save the code as index.php
Unpack the overLIB library into your web server’s documents directory, add in the index.php file and surf to it on your browser. This popup can be used with images, tables, fonts, styles and whatever you want.
