Function to create traffic graph in PHP with gd

Just finished a couple of projects in which this code came in useful.

You just pass in an array of traffic date of the format

I am Indian so the data code is in format d/m, but m/d should not matter either if you create the array in proper order. Also if the data is greater than 1024 for any of the array values, the graph switches to GB display.

Here is a sample image generated by this code.

Sample graph

Sample graph

Below is the code, enjoy! Let me know if it helped you.

function generategraph($traffic){
$imagewidth=700; $imageheight=300;
$yaxistextarea=35; 	$lefttextarea=30; $xaxistextarea=30; $bottomtextarea=30;
$topmargin=20; 	$rightmargin=20; $graphtop=10;


//xaxis is one greater because one line the start and end of the graph will not have any bars on them.

if ($barwidth>30) $barwidth=30;
foreach($traffic as $value){
if ($maxvalue<$value&#91;'data'&#93;) $maxvalue=$value&#91;'data'&#93;;

if ($maxvalue>=1024) { $datascale=1024; $dataunit='GBs';}

//The y axis is for the amount of traffic. so we find the minimum of the incoming and the outcoming traffic and
//it will be the lower and upper bounds.

//Since we will have a graph of only 20 lines, we split the difference into 20 and find the linerange

//we now have a neat map of i => in and out
//remember that each linerange is equal to
$im = ImageCreate ($imagewidth,$imageheight);
if (!$im) echo "Error in gd library";

//some of these variables are not used in the current code, but nice to let it remain in case future coding requires additions like borders around bars, lines etc.
$imagebackground=ImageColorAllocate($im, 255,255,255);
$graphbackground=ImageColorAllocate($im, 255,255,255);
$textcolor=ImageColorAllocate($im, 100,100,100);
$datalinecolor=ImageColorAllocate($im, 100, 255,100);
$databarcolor=ImageColorAllocate($im, 233,131,18);
$databarbordercolor=ImageColorAllocate($im, 100, 100,100);
$axiscolor=ImageColorAllocate($im, 50,50,50);
$axislinecolormajor=ImageColorAllocate($im, 186,180,24);
$axislinecolorminor=ImageColorAllocate($im, 255,255,255);

//create some frequently used variables
//these are the min and max values on the graph.
$xmin=$yaxistextarea + $lefttextarea;

//create the graph area
imagefilledrectangle($im, $xmin, $ymin, $xmax, $ymax, $graphbackground);
imagestringup($im, 3, 0+5, $ymin-30 , "Data Transmitted in ".$dataunit, $textcolor);

for ($i=1; $i<=$yaxissplits; $i++){
//each major y axis line locations
$ymajor = $ymin - ($i * ($graphheight/$yaxissplits));
imagestring($im, 2,  $lefttextarea,$ymajor -5, round(($minvalue + $i * $linerange)/$datascale,2), $textcolor);
$yminor = $ymajor + ($graphheight/$yaxissplits)/2;
imageline($im, $xmin, $ymajor, $xmax, $ymajor, $axislinecolormajor);

for ($i=1; $i<$xaxissplits; $i++){
//each major x axis line locations
$xmajor = $xmin + ($i * ($graphwidth/$xaxissplits));
$xminor = $xmajor - ($graphwidth/$xaxissplits)/2;
imageline($im, $xmajor, $ymin, $xmajor, $ymax, $axislinecolormajor);
imagestringup($im, 1,  $xmajor-3, $ymin+$xaxistextarea, $traffic&#91;$i-1&#93;&#91;'date'&#93;, $textcolor);

//plot the actual graph
$plotxold=$xmin; $plotyold=$ymin;
for($key=1; $key<=$xaxissplits-1; $key++){
$plotx=$xmin + ($key) *($graphwidth/$xaxissplits);
$ploty= $ymin - ($value&#91;'data'&#93; - $minvalue) * $graphscale;
if ($plotx>$xmax) $plotx=$xmax; //to avoid bleed due to rounding off of graphscale
if ($ploty<$ymax) $ploty=$ymax; //to avoid bleed due to rounding off of graphscale
$plotxold=$plotx; $plotyold=$ploty;
if ($value&#91;'data'&#93;>0){
imagefilledrectangle($im, $plotx-$barwidth/2, $ymin, $plotx+$barwidth/2, $ploty, $databarcolor);
$plotxold=$xmin; $plotyold=$ymin;
imagestring($im, 2,  $yaxistextarea+$lefttextarea,$imageheight-$bottomtextarea*3/4, "Total Data: " . $totaldata . " ".$dataunit, $textcolor);
imagestring($im, 1,  $lefttextarea,5, "Image generated at " . date('d/m/y  H:i'), $textcolor);
imagerectangle($im, $xmin, $ymin, $xmax, $ymax, $axiscolor);
imagejpeg($im, "graph.jpg");
return "<div><img src='graph.jpg' /></div>";

Python script to get links from yahoo search

This was a quick script I made to pull links from yahoo search using the boss search api, and then list the unique domains.

If you want the entire links, just modify so that the whole links are appended to the list. Yahoo does not allow to get all the results, but only a certain predefined number so this code only extracts about 800 domains. But it is still good enough for a start and for most uses.

I am also working on getting citation values for google scholar for a friend. I will post that soon here. Heres the code for now.

#! /usr/bin/python
import urllib,json
from urlparse import urlparse

#print yahoo_application_id

#print ""+yahoo_application_id+"&format=xml"
	print "trying result from " + str(nextresult)
	f = urllib.urlopen(""+yahoo_application_id+"&format=json&count=100&start="+str(nextresult))
	ssjson= ss.decode(
	print totalhits
	for x in ssjson["ysearchresponse"]["resultset_web"]:
		url= x["url"]
		o = urlparse(url)
		link = o[0]+"://"+o[1]
		if link not in links:
	if (nextresult>10000):
print "Obtained results: " + str(nextresult) + " of which " + str(len(links)) + " were unique."
for x in links:
	print x

Cool huh? If you want any help modifying this, drop me a line.

PHP and XML RPC – Searching for values

Many servers provide xmlrpc interfaces which allow other web applications to call and execute functions. It is actually quite simple once you get the hang of it. The servers also return the response and any variables as xmlrpc response messages which are xml responses basically

There are probably a lot of ways to get this done, but this actually turned out pretty well using a combination of the phpxmlrpc library and the Domdoc class in php.

Let us say that the server url is at port 4567.
In order to make the call you first have to download the phpxmlrpc library from and extract it to a folder in your web directory root.

In the beginning you may want to turn the debugging feature of the rpc client on. To do uncomment the setDebug line in the code.



//ini_set("display_errors", 1);


//You do not need to set the transport as https here.

$xmlrpc_client=new xmlrpc_client('admin/admin', '',4567);


//An xmlrpc call without any parameters is below.

$xmlrpc_msg=new xmlrpcmsg('rpcFunctionName');

//the next one is an xmlrpc call with parameters.

//$xmlrpc_msg=new xmlrpcmsg('rpcFunctionName', array(new xmlrpcval(7, "int"),new xmlrpcval("", "string"),new xmlrpcval(2, "int")));

//Here is where you set the transport as https. Look at the manual for more options

$xmlrpc_resp=$xmlrpc_client->send($xmlrpc_msg, 200, 'https');

if ($xmlrpc_resp==False)


print "No response";

die ('Error');


if (!$xmlrpc_resp->faultCode())


//If you just want the xml, print out the return value from serialize()

//print $xmlrpc_resp->serialize() ;

$dom=new DomDocument();


//examine the xml to find out the path to the actual things you need.

$xpathString = "//methodResponse/params/param/value/struct/member[name='a_value']/value/string";

$xp=new DOMXPath($dom);

$domNodeList = $xp->query($xpathString);

foreach($domNodeList as $domNode){

//You may need to do more xpath queries as $xp->query($anotherXpathstr, $domNode). search will be done under $domNode

$server_name=$domNode->nodeValue ;





print "Error: " . $xmlrpc_resp->faultString();



Also do look up the documentation for xmlrpc_client property return_type.

Printing a sheet to pdf silently in Excel VBA

This piece of code uses Adobe Acrobat to silently print a sheet to the location you specify.
Change PDFPath and strOutFile to modify.

Dim strDefaultPrinter As String, strOutFile As String
Dim lngRegResult As Long, lngResult As Long
Dim dhcHKeyCurrentUser As Long
Dim PDFPath As String
dhcHKeyCurrentUser = &H80000001
strDefaultPrinter = Application.ActivePrinter
PDFPath = ThisWorkbook.Path & Application.PathSeparator ‘The directory in which you want to save the file
strOutFile = PDFPath & “sheet1.pdf” ‘Change the pdf file name if required. This should have the fully qualified path

lngRegResult = RegOpenKeyA(dhcHKeyCurrentUser, “SoftwareAdobeAcrobat DistillerPrinterJobControl”, lngResult)
lngRegResult = RegSetValueEx(lngResult, Application.Path & “excel.exe”, 0&, dhcRegSz, ByVal strOutFile, Len(strOutFile))
lngRegResult = RegCloseKey(lngResult)
ThisWorkbook.ActiveSheet.PrintOut copies:=1, ActivePrinter:=”Adobe PDF”

Solving Error with bzr in debian etch. PathNotChild Stack Trace

I installed bazaar on my debian box in order to host the ‘Leave Status Board’ Project on launch pad. Following the instructions to init, add, commit worked fine. But on trying to push to the launchpad account, (had to add the RSA public key to Launchpad first) I got a whole bunch of python errors, a stack trace.

bzr: ERROR: bzrlib.errors.PathNotChild: Path ‘bzr+ssh://’ is not a child of path ‘bzr+ssh://’

Traceback (most recent call last):
File “/usr/lib/python2.4/site-packages/bzrlib/”, line 611, in run_bzr_catch_errors
return run_bzr(argv)
File “/usr/lib/python2.4/site-packages/bzrlib/”, line 573, in run_bzr
ret = run(*run_argv)
File “/usr/lib/python2.4/site-packages/bzrlib/”, line 282, in run_argv_aliases
File “/usr/lib/python2.4/site-packages/bzrlib/”, line 601, in run
relurl = to_transport.relpath(location_url)
File “/usr/lib/python2.4/site-packages/bzrlib/transport/”, line 375, in relpath
raise errors.PathNotChild(abspath, self.base)
PathNotChild: Path ‘bzr+ssh://’ is not a child of path ‘bzr+ssh://’

bzr 0.11.0 on python (linux2)
arguments: ['/usr/bin/bzr', 'push', 'bzr+ssh://']

** please send this report to

A helpful soul at irc ( mentioned that 0.11-1.1 version of bazaar that I had installed was quite old. Considering that 1.11 is the current version, that was actually quite old.

A quick trip to for the stable version for i386 with a download with wget got me the deb installer.

Uninstall the old version, install the deb file. A minor hiccup was the python-celementtree needed to be installed, which I did. The installer also complained about python 2.5 required, while my system had 2.4. But didn’t stop installing.

Pushing to launchpad works fine for now, so I take it that python 2.4 is quite ok for this version of bzr.

Solving the include_once error in Pear Mail

I have this hosting from and helping on a friend’s community development initiative by setting up his website. It may soon move to

During that, I set up a email form on my system, using PHP’s PEAR mail package to send mail. Though it worked fine on my own system, it didn’t on the hosting server. And no errors either.

First enabled the Error messages by putting this is the first line of the php file.

ini_set('display_errors','1'); ini_set('display_startup_errors','1'); error_reporting (E_ALL);

And then out popped the error.

Warning: Mail_smtp::include_once(Net/SMTP.php) [mail-smtp.include-once]: failed to open stream: No such file or directory in /home/username/php/Mail/smtp.php on line 206

Warning: Mail_smtp::include_once()[function.include]: Failed opening 'Net/SMTP.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/username/php/Mail/smtp.php on line 206

Fatal error: Class 'Net_SMTP' not found in /home/username/php/Mail/smtp.php on line 210

Apparently the basedir is set incorrectly and since I need to ask the hosting person to change the configuration, and to avoid the hassle, the simplest solution was to edit line 206 in /home/username/php/Mail/smtp.php to have

include_once '/home/username/php/Net/SMTP.php';

include_once 'Net/SMTP.php';

Yes, that is the full path.

Once I did that, I also got an error from Net/SMTP.php with it finding difficulty in locating Socket.php.

Same solution again and everything looks hunky dory. Clean up the error reporting and any debugging steps in between.

Oh, by the way, the site is at and will soon be moved to

A c program to add n numbers

OK, I agree it is too simple. But I really need to brush up my programming skill and anyway I enjoy programming. Or used to.
So just thought to brush up my programming skills, and if it weren’t for that error i posted about previously I got only a few logical errors which I was able to resolve immediately. Time taken to write this program – 1/2 hour. Good enough for touching C after over a year.

A C program to add n numbers which are input by the user and the input ends when the user enters a negative integer, ie any number less than 0. I haven’t added any error checking yet. Maybe I will get around to it.
(I really don’t know if I need this header on top but it has my name in it and will increase search engine rankings, so here it does.)

blast it, blogger doesn’t seem to allow the lesser than symbol. OK, here is the link to the page on my website.