open source code

Recourse

Recourse or circular definition is used a lot in C++. Recourse is process of invoke the function. Function which invoke is called recourse. For example factorial on number:

int fact(int n){
int answer;
if(n==1)
return 1;
answer = n * fact(n-1);
return answer;
}

When the function invoke, the new local variables and parameters locate on steak in memory. The recourse doesn’t make a new copy from the function, just the parameters are new. After every return the variables the old variables are deleted from the steak. The recourse can be vary slowly process. Too much recourse’s invokes on the function can bring to congestion in a steak. Quicksort is algorithm for sorting which works in a principle of recourse.

Posted in |

fre source code of Matrix determinant solver

You can download source code from my program for matrix determinant solver.
download

Posted in |

fre source code of Matrix determinant solver

You can download source code from my program for matrix determinant solver.
download

Posted in |

code to connect MySQL database and PHP

Connecting to MySQL database is very easy and consist of following few instractions.


$host="localhost"; //Mostly its localhost
$dbUser="root";//your mysql username here
$password="passwordhere";// mysql user's password
$dbName="students";//Your MySQL database name
$dbc=@mysql_connect($host,$dbUser,$password) OR die('Couldn\'t connect to MySql:'.mysql_error());//This will make a connection to mysql or will display error if failed
mysql_select_db($dbName, $dbc) OR die('Couldn\'t select DB:'.mysql_error());//This will select the specified database for operations or will display error if failed

?>



Thats it with the above code you are connected to mysql db through php and can perform any mySQL database operation through php script now.

Posted in |

code to delete a cell by its ID

In javascript when some row don't have an id defined for it but the cell have its id we can delete the cell by using its parentNode property with cells object and telling the column number of cell like in following javascript code

document.getElementById(cellID).parentNode.deleteCell(1);

cellID is the variable which contains the id assigned to cell to be deleted and in deleteCell(1) number '1' is the column number of cell. So know if you have the cell ID and you can figure out the column number of cell , you can delete cell by ID.

Your comments will be welcome and if you have any better idea I will be pleased to know.

Posted in |

Php code to make CSV from MySQL query result in PHP

I had to make a csv from the data coming from MySQL database, I came across this very easy method so I am sharing this to you people.


$query="SELECT * FROM tickets";
$Result = mysql_query($query) or die("Error: " . mysql_error());
header("Content-type:text/octect-stream");
header("Content-Disposition:attachment;filename=chargRep.csv");
while($row = mysql_fetch_row($Result))
{
print '"' . stripslashes(implode('","',$row)) . "\"\n";
}
exit;
?>

The verable $query may contain any mySQL query and above code will give you option to save or open the result returned from MySQL as a CSV file.
CSV files may be opened in MS Excel or as simple text files with fields separated by commas.

Posted in |

php code to make csv from two dimentional array

When you fetch any data from mySQL database and make the two dimensional array from that like following

$counter = 0;
while($resRow = mysql_fetch_array($sqlRes))
{
$resArray[$counter]['ticketID'] = $resRow['ticketID'];
$resArray[$counter]['title'] = $resRow['title'];
}

Or any other two dimentional array you have in PHP and you want to generate a csv from that the solution is few easy lines of code as follows


header("Content-type:text/octect-stream");
header("Content-Disposition:attachment;filename=chargRep.csv");
for($i=0;$i<$counter;$i++)
{
print '"'.implode('","',$resArray[$i]) . "\"\n";
}
exit;

In above code the $resArray contains the two dimensional array.

Posted in |

PHP code to Seprate a string into array of strings on base of a character or string in

In case in php you have a string and you want to separate it into array of sub-strings on base of a separated character or string using php solution is simple.

For this we will use php explode function with a seprator and a string. Seprater may be any character of sub string.

array=explode(seprator,string);


See following example

$string1= "this is car and he is boy";
$strAry= explode("and",$string1);

Now after execution created array will be in following state
$strAry[0] => this is car
$strAry[1] => he is boy

Posted in |

Javascript to Seprate a string into array of strings on base of a character or string in

In Javascript you can very easily seprate a string in an array of strings on base of a character or sub-string seprator using split function

array=string.split(seprator);


See following example

var string1= "this is box and who is going and we are one";
strAry= string1.split("and");

Now after execution created array will have following values
strAry[0] => this is car
strAry[1] =>
who is going
strAry[2] =>
we are one

Posted in |

Php code to Get time and date for specific GMT time zone

No matter the server is in which GMT time zone here is extremely easy way to get time and date for any time zone. This is done with time() and gmdate() function. gmdate() funtion normally give us GMT time but by doing a trick with time() function we can get GMT+N or GMT-N means we can get time for any GMT time zone.

For example you have to get time for GMT+5 we will do it like following
$offset=5*60*60; //converting 5 hours to seconds.
$dateFormat="d-m-Y H:i";
$timeNdate=gmdate($dateFormat, time()+$offset);
?>

Now if you have to get the time which is GMT-5 now we will just subtract the offset from the time() instead of adding into time like in following example we are getting time for GMT-4

$offset=4*60*60; //converting 5 hours to seconds.
$dateFormat="d-m-Y H:i";
$timeNdate=gmdate($dateFormat, time()-$offset);
?>


Now finally the $timeNdate variable will be having the date and time in given format, which can be used to display or do anything with it.

Posted in |

PHP code to copy data and structure of one mysql database to other

If you are looking for to develop PHP script which can copy all data and structure of all tables of first database to other database you are on right place. Previously I had posted a script with ability to copy all data of first mysql db to other mysql db with same table structure. But now this script update both data and structure of tables in destination database. Script do not remove or change any additional tables in destination db it just pick all tables of source db to destination db or if they exist in destination db script update their data and structure.

$dbc=@mysql_connect("localhost","dbUser","dbPass") OR die('Couldn\'t connect to MySql:'.mysql_error());


$result = mysql_list_tables ("database1name");
$i = 0;
while ($i < mysql_num_rows ($result))
{
$table[$i] = mysql_tablename ($result,$i);
$i++;
}


$j=count($table);
for($i=0;$i<$j;$i++)
{

$qry="drop table if exists database2name.".$table[$i];
mysql_query($qry)or die("Failed to delete:".mysql_error());

$query="CREATE TABLE database2name.".$table[$i]." SELECT * FROM database1name.".$table[$i];
mysql_query($query)or die("Table copy failed:".mysql_error());
echo "$table[$i] copy done...";
}
?>


So script actually works in a way that it picks list of tables in first db the delete those tables from second db then recreate them in second db. Thats it.

If you change or optimize the code to use I will be happy to see an update from you through comment.

Posted in |

PHP script to copy all data of one mysql database to other mysql database on same server

The PHP script I am going to provide you will update all the data in second database from first database. In both databases table structure should be exactly same.
The strategy we will use is we will make an array of table names data from which have to be transfered to tables in other db. Here we are assuming database name is different but table names are same in both databases. So here we go.


$dbc=@mysql_connect("localhost","dbUser","dbPass") OR die('Couldn\'t connect to MySql:'.mysql_error());
$table=array("tableonename","tabletwoname");
$j=count($table);
for($i=0;$i<$j;$i++)
{
$query="replace INTO database2name.".$table[$i]." SELECT * FROM database1name.".$table[$i];
mysql_query($query)or die("Table copy failed:".mysql_error());
echo "

$table[$i] copy done...";

}
?>

This script will copy all the data of tables specified in array of first database to the same tables in database two provided that the db user you are connected with should have access to both the databases. This script will replace the data of db1 to db2 means will delete older data in db2 if any. If you want to just copy the data from db1 to db2 without deleting the old data in db2 use keyword "insert" instead of "replace" in the query.

If you use some changes to script and use it then It will be good for me to see those optimizations so you can post back modified code through comment feature.

Posted in |

code to copy all tables of one mysql db to other with structure, keys and data

In my two old posts I had posted about firstly how to copy all data of one database tables to the same structured tables of second database. Then my second post had the method to copy all tables data and structure to a second database. That script was copying the data and the structure of all pages but that was not copying the keys (indexes) of first table to the second table. Here comes the modified code which now copy all tables structure, Keys and data from one table to another mysql table.




$dbc=@mysql_connect("localhost","dbUser","dbPass") OR die('Couldn\'t connect to MySql:'.mysql_error());


$result = mysql_list_tables ("database1name");
$i = 0;
while ($i <>$j=count($table);
for($i=0;$i<$j;$i++)
{

$qry="drop table if exists database2name.".$table[$i];
mysql_query($qry)or die("Failed to delete:".mysql_error());

$query0= "create table database2name.".$table[$i]." LIKE database1name.".$table[$i];

$query="Insert INTO database2name.".$table[$i]." SELECT * FROM database1name.".$table[$i];
mysql_query($query)or die("Table copy failed:".mysql_error());
echo "$table[$i] copy done...";
}
?>


So in this modified PHP script we are actually using two statements to copy a table. After deleteing the table if exists we create a table using the "LIKE" statement in the create query which actually copies the table to second database with the same structure of first table. Then after that we are coping the data from the table in first db to the table in second db.

Just pick the code and play it and if you discover or implement something new feel free to post here in comments.

Posted in |

PHP code get date and time in mysql datetime format


$dateFormat = 'Y-m-d H:i:s';
$timeStamp = time();
$dateTime= date($dateFormat,$timeStamp);
echo $dateTime;
?>

Posted in |

PHP code to disable caching of a page

While development some times our pages don't refresh automatically after we delete some record and come back. They actually show the page from cache and we need to manually refresh the page. Here is simple short PHP code to stop a page from being saved into the cache.


header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 12 Jul 1996 04:11:00 GMT'); //Any date passed.
header('Pragma: no-cache');
?>

Posted in |

PHP code to rescale image and show an image thumb

During development mostly we need to show images from data base or so by rescaling them but rescaling them in a way that they don't loose the original length to width ratio.
e.g. you have an area of 500*500 pixels to show the image in following code while calling the function you will specify the target as 500 rest of things will be well taken care of by the function. It will rescale image to fit in that 500 pixel sqare area and fit your image in a way that it dont loose the original length to width ratio. Also this function will link image to its own so that you can click image to see it in full size in new browser tab/window. And this thing obviously can be changed into function code if you don't need the link on image.


function showimgthumb($imgpath,$target)
{
list($width, $height, $type, $attr) = getimagesize($imgpath);
if ($width > $height)
{
$percentage = ($target / $width);
}
else
{
$percentage = ($target / $height);
}
$width = round($width * $percentage);
$height = round($height * $percentage);
$hiwi="width=\"$width\" height1=\"$height\"";
echo " echo $hiwi;
echo " />
";

}//end of function Show image thumbnails
?>

And you will call this function like following.


$target=45; // For 45*45 pixels target area
$imgpath="images/myphoto.jpg"; //This is path of image form page where the function is being called
showimgthumb($imgpath,$target);
?>

Posted in |

PHP code to Get refferer website, visitor's IP and browser

There are few very simple PHP predefined variable which give you the information about referer URL , visitors IP and visitors browser.

- Get Referer URL(The page from where user came to your site)

$referer = $_SERVER['HTTP_REFERER'];
?>

- Get visitor's IP

$visitorsIP= $_SERVER['REMOTE_ADDR'];
?&gt;

- Get visitor's web Browser Name and version

$browser=$_SERVER['HTTP_USER_AGENT'];
?>

Posted in |

code to Copy html color code of any color on screen by single click, great tool

While web development often we need color code of different colors. So to get the color code usually we have to first may be take a screen shot and then copy image to a photo editor and get the html color for it.

But the tool I am going to tell today just simply copies the color code of color being displayed on screen just by a single click.

Its instant eyedropper. Just click the instant eyedropper icon on to the system tray and drag it to any color on screen. The html color code for that color will be instantly copied to the clipboard so you can paste it anywhere and use it. It also displays color code on screen, refer to the attached image.

Instant-Eyedropper website: http://instant-eyedropper.com
Direct Download Link: http://instant-eyedropper.com/download/InstantEyedropper.exe

Posted in |

PHP code to $_server variables list with details

Here are some more php $_SERVER variables which will give lots of useful information as mentioned below

$_SERVER['PHP_SELF']
This will give the file name of current script being executed, even if its included file it will give its file name.


$_SERVER['GATEWAY_INTERFACE']
Used to get the
revision of the CGI specification being used on the serveri.e. 'CGI/1.1'.


$_SERVER['
SERVER_ADDR']
Get the IP address of the server on which script is being execute.


$_SERVER['SERVER_NAME']
Get the Host name of server under which script is being executed.

$_SERVER['REMOTE_HOST']
Get the Host name of the visitor.

$_SERVER['REMOTE_PORT']
Get the communication port of the visitor
for current communication.

$_SERVER['SERVER_PORT']
Get the communication port of the server for current communication.


$_SERVER['REQUEST_URI']
Get the URI which was entered to access current page (e.g. /contact.php)

Posted in |

Appending data into a MySQL field, additionally with a "NULL" check

Some times we need to append data into a mysql field. So here is solution. Also the query below checks if the value is NULL then if first enters the empty data to the table field.

UPDATE employee SET notes=CONCAT(COALESCE(notes, ''), 'NewDataHere') where employeeID=13;


In the above query concat('','') is to append the new data to the existing data of the field notes. Other function COALESCE(",") checks for NULL, if the field have NULL value then it will enter an empty '' value to field. Other wise in case of NULL value concat() function will end up with a MySQL error.

Hope this will be helpful, comments, suggestions and other coding tricks are most welcome.

Posted in |

PHP code to send email with an attachment

Assume that we are getting message and file attachment from a html form. So the php code for processing that form and sending email with file attachment will be following.


//Getting Data submitted through form.
$otherData= $_POST['message']; //The text message
$afile = $_FILES['myFile'];

//Getting info about above taken file
$fileatttype = $afile['type'];
$fileattname = $afile['name'];

// Setting basic headers info
$headers = "From: info@website.com";

//Opeing the submitted file to read all data in it
$file = fopen($afile['tmp_name'],'rb');
$data = fread($file,$afile['size']);
fclose( $file );

//Making a random number to use afterwards with help of current time
$semi_rand = md5( time() );

//Defining the type of email as Mime email
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

//Appending to headers, telling that its multipart message with text and attachment
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";

//The text part of message in variable $otherData with other details
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$otherData . "\n\n";


//Encoding all the data read from file to "base64" the standard for email attachments

$data = chunk_split(base64_encode($data));

//Appending the file data to the email including the file name etc
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";

//other details like the email subject and recipient's email address
$subject="New submission";
$to="email@anysite.com";

//Instruction to send email
mail($to, $subject, $message, $headers);
?>
Enjoy!, comment, suggetions, improvements and other coding tricks are most welcome.

Posted in |

PHP code to Save a file to local domain by just using its URL

If you have been given a URL of a document like following

http://www.anydomain.com/anyfolder/thefile.doc


then by using a PHP script saving this to your own domain will be very easy and here goes the code to do that


// Download the given file to local inside the domain

$remoteFileContents=file_get_contents("http://www.anydomain.com/anyfolder/thefile.doc");
// Variable $localFilePath should contain path where u want to save file without slash at end.
// Variable $
localFileName should contain the local file name to be given
$newFileHandle = fopen($localFilePath."/".$localFileName, "w");
fwrite($newFileHandle, $remoteFileContents);
fclose($newFileHandle);
?>

Posted in |

MySQL code to sort by specific value in combination of another field

While development/querying we lots of times need the records to be sorted in a way that records with specific value of specific field come on top and then all other records sorted by another field ascending or descending.
So following example all records with user name 'Adam' will be on top and then all other users' records sorted ascending based on userID field.

SELECT * FROM users ORDER BY FIND_IN_SET('Adam',userName) DESC, userID ASC

Now as used DESC with find_in_set so all user with name Adam will come on top of the list if you use ASC they all will go on bottom of results array. Also you can think of using Find_in_set statment more than once in a quer, in that case in results sql will sort in a way that it will preffer the find_in_ set statements by their order. Following is another example.

SELECT * FROM users ORDER BY FIND_IN_SET('Adam',userName) DESC, FIND_IN_SET('active',userStatus) DESC, userID ASC

Posted in |

PHP Code to send HTML Email or Newsletter of mail

Lots of time we need to send the newsletter or HTML email to the visitors of our website. Following is the simple PHP code to send HTML newsletter.


//Variables from the HTML form
$message=stripslashes($_POST['newsmsg']);
$subject=$_POST['newssub'];

//headers variable being set
headers="From: sender@site.com\nReply-To: sender@site.com\nContent-Type: text/html";

//Getting all recipient email addresses from db in my case
$subRes=getSubscribe();

//Sending HTML email to each recipient
while($subAry=mysql_fetch_array($subRes))
{
mail($subAry['email'], $subject, $message, "From: $from\nReply-To: $from\nContent-Type: text/html");
}
echo "sucess";

?>

Posted in |

How to Prevent webpage items from being printed

As for as web pages are concerned we just have to put some extra items into pages like ads etc. But if some one tries to print out web page it will be good idea to remove the ads and some extra items like menus etc from the printed version.

In this regard css gives us facility to code in a way that some items display on our web page but when some one prints the page through printer those items will not be printed in page on useful content will be printed.

See following css code.

@media print
{

#np{ display:none;}
#contentArea{ width:100%;}
}

@media print tells the browser that you have to consider this in case page is being printed or print preview is being viewed. Styles inside brackets of @media print will now be applied to normal page. Now lets see how to implement.

First step is to paste the code above to your css file or between the css script tags in header section of your webpage.

Now all the items you dont want to print put a div tag around them and put the id="np" inside opening tags. This will apply the np style given above to item and it will not be printed. In case of table or paragraph p tag you can simply put the id="np" attribute to opening tag like

This will prevent that paragraph or table from printing.

Now if you have choosed to not to print a side menu while printing the space will be left blank which will not look very nice. What you can do is put a div tag around useful content to be printed and assign it an id #contentArea and according to above defined style of content area the content of content area will be printed on the full widht with no extra space leaving which will make layout bit nice.

This wonderful thing may please your visitors by not printing extra ads and menus while they are printing your webpage for some reason.

Posted in |

PHP code to get list of all mysql databases on a shared server

Script to get mysql database names on a shared hosting server.


$path="/var/lib/mysql";
$dary=array();
$dary=scandir($path);
$fh=fopen('dbList.txt','w') or die("can't open file");
$num=count($dary);
$i=0;
while($i<$num)
{
$Dposs=strpos($dary[$i],".");
if($Dposs===false)
{
$Uposs=strpos($dary[$i],"_");
if($Uposs===false)
{
//do nothing :-)
}
else
{
$var=$dary[$i]."\n";
fwrite($fh,$var);
}

}
$i++;
}
fclose($fh);
echo "done";

?>

put this script to /root folder of shared server in a folder lets say with file name scri.php. Through shell go to folder and execute as usr/bin/php -q scri.php usr/bin/php shows the installation folder of php. This script will make a file 'dbList.txt' imidiately in the same folder in which script exists. Download this file and this will be list of all mysql dbs on a shared server. DBs from the all acounts.

Posted in |

MySQL Fetch only the distinct values

Last day while I was coding a web based interface and related sql quries and stuff. A situation came where I had to fetch the data in a way that every value for a field even it exists many time against that field I had to fetch it only once. I mean if a field named car name have values "honda","suzuki","honda" while fetching the query must fetch honda only once making the output as "honda","suzuki". This kind of situations come when you have to populate a dropdown list from a data table and you want every value of that data table field must be existing in the dropdown once.

So after doing some research I came to know new keyword which done the whole trick. Which is keyword "DISTINCT".

So final query will be as follows.

"SELECT DISTINCT carName from cars"

This will fetch every value of field "carName" once even it exists many times in table cars.

Posted in |

Very useful text and code editor - Crimson Editor

While we are developing any webpage or coding into some web or normal computer language working into the normal text editor link note pad etc looks much boring. Not only it looks boring it makes the task of coding boring by all time offering that black and white interface. When ever I code some thing I like to use light weight but a bit of an advance text editor. Which at least have features of syntax highlighting, mass searching files without opening them in milliseconds and macros etc.



Crimson editor is the one same kind of useful editor which first of all have the syntax highlighting with the support of more than a hundred of modern and old computer language. Syntax highlighting works in a way that it gives different colors to different elements of code. E.g. comments are colored green, functions are colored red and rest elements colored in different other colors. This not only make code for seeing some one working can quickly differentiate the elements and with increased readability he/she can code more efficiently. And if you are Miss-spelling any function, it will not turn to red, the function color, this way immediately you will know function is Miss-spelled.
Mass searching and quick searching are other good features offered by this editor with the mass searching option if you have 1000 files and you want to know in which file the function is defined just use CTRL+SHIFT+F and specify the containing all the files and editor will it self search the original file containing a string and enlist all occurrences in a clickable list immediately.

Another good feature is macros. You may have used macros in a word processor like MS Word. Same good feature is given into the crimson editor. Brief description is that if you have to do same type of job a number of times you can define a macro instead of doing it again and again. e.g. you have to page a string after each three lines of code, one way is to repeatedly go to lines and paste other easier way is to define a macro which goes down three lines then reaches to location in target lines and pastes and then replay it many times quickly and conveniently.

There is an unending list of good features offered by this editor just yourself download it and use it. Its 100% free without any ads of anything else.

Here is official website of crimson editor where you can download it and learn more about it Official Website: http://www.crimsoneditor.com/

Posted in |

Java Script to generate list of hosting accouts with soho launch installed on a hosting server

Recently I had done a task in which I had to create a list of hosting accounts on a shared only hosting accounts with soho launch installed. Soho Launch, which is also called pro edition. Now not only the accounts but the user names and passwords had also to be collected. The script makes a comma seprated CSV file of useraccounts, soho username and soho password fields.

As the databases created by Soho Launch are always named as sope1. And for each data base on a shared hosting server always a directory is created by the same name of database in the mysql directory located at "/var/lib/mysql". Now the databases on shared hosting servers are always created with names having two words seprated by an underscore( _ ) character. The word before '_' is shared hosting account name and word afterwards is the origional db name.

Now what my script do is read the directory "/var/lib/mysql" for subdirectories having database name part as "_sope1". Then extracted the account name from db name.
e.g. db name is kkpcouk_sope1, the account name will be kkpcouk

Then in same loop for every account I had to get its cpanel user name and password which are always placed in login table of _sope1 db of every account in fields "Username" and "Password" as a single record. So for this at start of script I made the mysql connection with server's root user. And in each loop itration a query fetches out the soho username and password. This all infor then in same itration is written to the file seprated by commas.


S0 following is the PHP script to make csv of hosting accounts with soho launch(pro edition) installed along with soho username and password.


$dbc=@mysql_connect("localhost","root","sqlrootpassword") OR die('Couldn\'t connect to MySql:'.mysql_error());
$path="/var/lib/mysql";
$dary=array();
$dary=scandir($path);
$fh=fopen('sohoDbList.csv','w') or die("can't open file");
$num=count($dary);
$i=0;
$v1=array();
while($i<$num)
{
$Dposs=strpos($dary[$i],".");
if($Dposs===false)
{

$Uposs=strpos($dary[$i],"_");
if($Uposs===false)
{}
else
{
$SLposs=strpos($dary[$i],"sope1");
if($SLposs===false)
{}
else
{
$var=$dary[$i];
$v1=explode("_",$var);
$sopedb=$v1[0]."_sope1";
mysql_select_db($sopedb, $dbc);
$qry="select * from login";
$res=mysql_query($qry);
$resAry=mysql_fetch_array($res);
$username=$resAry['Username'];
$password=$resAry['Password'];
$var=$v1[0].",".$username.",".$password."\n";
fwrite($fh,$var);
}
}

}
$i++;
}
fclose($fh);
echo "\n\ndone\n\n";
?>

Save this script in a php file. Then save it to the server's root folder. And run through shell run it through php 5. e.g. php5 -q filename.php. It will echo done on sucess.

It will make csv file in same directory with name 'sohoDbList.csv'

Posted in |

PHP code of setting and reading cookies of different kinds

SETTING COOKIES

In PHP we can set different kind of cookies lets see how.

1. A simple cookie which only have a name and a value

setcookie("CookieNameHere",$value);

Variable $value here may contain any string value


2. A cookie with a name, a value and expire time

setcookie("CookieNameHere",$value,time()+3600);
This cookie is the same like first one but the difference is it will expire after given time. Here time() shows current time(In seconds from 1970) and 3600 are seconds which added to current time so cookie will expire in next hour. You can give give a time in way that cookie expire in next three days but always it must be current time using time() plus number of seconds.

I have given time()+3600 for hour as it has 3600 seconds I can also give it like time()+60*60 or for three days it will be time()+60*60*24*3. Here 60*60*24*3 is the equivalent of three days in seconds.
After cookie is expired you can't read its value anymore.


3. A cookie with a name, value, expire time and path

setcookie("CookieNameHere",$value,time()+3600,"/");
Here fourth argument to cookie which is '/' is path and will set the cookie which will be valid for whole site. As '/' denotes the root directory so any file at site can access it.

If I don't give a path cookie will only be set for all files in current or its sub directories so files in other directories can't read it.

Also path Can be specified like "../folder1/subfolder" so only files in "../folder1/subfolder" will be able to read it.

READING COOKIES
It is very simple.
for printing it.

for assigning its value to other variable.

Posted in |

PHP code of check if given variable is an array PHP

In php you can check if variable which you are going to use is as array or not. Its done using is_array() function. Which returns TRUE or FALSE

Here are some implementation examples.

' : 'no its not an array' ?>

OR

$res=is_array($variable);
if($res)
{
echo "its an array";
//Some other code
}
else
{
echo "its not an array ";
//some other code
}
?>

Posted in |

PHP code of Object Oriented Programing, Classes and Objects in PHP

Concept of using classes is very easy and the handy one. As it addresses lots of issues, you can define classes for different modules in site.

E.G. In an online community forum you may have two classes "manageThreads" class which will be responsible for all functions like insertion/creation of thread, replies to thread and show threads and other one "manageUsers" class which will contain all functions related to the users' management.

One big advantage of using Object Orientation is re-usability of code and this is equally valid in PHP web programming. If we consider above example of manageThreads class we can simply include class file on any page, define its object and use any of its function on that page, have not to recode any of funtion or stuff for different pages.


Now lets move to code details how Classes and objects work in PHP.

The Class File Defination:-
You Can name a class file some thing like manageThreads.class.php, the class word in between will help us differentiating it from normal pages.

The code in Class file (A class):-

class manageUsers()
{
function createUser($userName, $password)
{
$query="insert into users SET userName='".$userName."', password='".$password."'";
$mysql_query($query) or die(mysql_error());
}

function deleteUser($userID)
{
// Body of function here
}

}
?>

Usage of a PHP class in a page or php file:-


//mysql connection details here
//Inclusion of class file:-
include "classes/managerUsers.class.php"; //If class is in folder classes
//Defination of class object:-
$aManageUsers=new manageUsers();
//Call of a class function with class object
$aManageClass->createUser($userName,$password);//assuming $username and $password are set above in this files

?>

Now this one object $aManageClass can be used with all functions of manageUsers class in usage file. Similarly many classes can be included in a file and their objects can be defined to use their functions.

Hope it helps, give feedback as comments.

Posted in |

Free Java script functions for setting, reading and removing cookies

Create Cookie

function createCookie(name, value, hours)

{
if (hours) {
var date = new Date();
date.setTime(date.getTime()+(hours*60*60));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

Above function can be used to set cookie. It takes name, value of cookie and hours after which cookie will expire. You can modify function to give time in days or minutes. Just ultimate goal is to convert the time given into seconds and provide it to origional cookie setting instruction.

Read Cookie
If you provide the name of already set cookie to following function it will read the cookie value for you.

function readCookie(name)
{
var ca = document.cookie.split(';');
var nameEQ = name + "=";
for(var i=0; i <>
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}

delete Cookie
This simple function deletes cookie of given name using above create cookie function.

function deleteCookie(name)
{
createCookie(name, "", -1);
}

Posted in |

Free PHP code of login script using sessions - Secure and easy

PHP login script is the thing about which you find lots of people searching it. Specially the people who are new to the PHP language it is very important for them to learn user authentication stuff. So I am gonna take this initiative to post a secure php login script and explain it.
For your information we will be using sessions for login. I will mostly emphasize on PHP coding but will give specifications about the html login form. So first things first, make a login form with two fields and one login button. First field must be named "username" and second must be named "password". Post form using method="POST" and action must be another page lets say called doLogin.php which will actually contain the login PHP code.


Now before going further into the PHP lets see out MySQL tables' details which we will be using for login purpose. We will be using two table, one for actual user listing and second will contain the user types available with their IDs, those IDs from second table will be used in first one to specify each user's type or privileges level.


Table One Details:-
Table Name: user
Table fields are as follows:-
userID INT Auto-Increment
userName Varchar(100) Must be unique, used for login
password Varchar(100) Must contain MD5 encrypted password
userStatusID INT(3) The user type ID coming from "userstatus" table and will be used to assign previllages.
email Varchar(100)
userActive TINYINT(2) An optional field but if you choose to use it you can disable users from being login.
Name Varchar(45) User's Actual First and Second Name
Country Varchar(45)
Gender Char(1) 'M' for Male and 'F' for Female

Table Two Details:-
Table Name: userstatus
Table fields are as follows:-
userStatusID INT(3) Auto-Increment
userStatus Varchar(40)

Sample data for table two aka userstatus
1 Admin
2 Operator
3 Visitor

Before jumping on to the PHP actual authentication script next step for us to populate the tables. For data insertion into login table you will yourself design the form and PHP script I will just guide you with some most important things.

As I have given sample data for table two you will have to similarly do some brainstorming for identify how many user types you are gonna support in your login script and will have to just put in to "userstatus" table as given in above sample. After you are done with it now its time to make a form and php script to populate table one called "user".

While entering data into table one "user" choose user type of user by entering the "userStatusID" from userstatus table to "userStatus" field of "user" table. I mean if you are gonna enter a user who is "operator" so according to my sample data you will set the "userstatus" field of "user" table to '2'.

'userActive' field must be set '1' for an active user and '0' for disabled user, which you don't want this time to be able to get login.

Data in password field must be encrypted with 'MD5' encryption before entering it to the table. This can be easily done by a 'md5()' php function which will give you an encrypted string.
e.g see following how data is being encrypted while getting from user insertion form.

$password=md5($_POST['password']);

Now data in this $password variable will be entered in 'user' table's 'password' field. As the 'MD5' encryption is the one way encryption which can't be decrypted so even some one looking into db can't retrieve the password of the user. While user will get login you will again decrypt the password entered by user with md5 and compare it to md5 decrypted string coming from database to verify the correctness of password.


Now after making login form exactly according to specifications given above, lemme mention them again here, which are as follows.

Make a login form with two fields and one login button. First field must be named "username" and second must be named "password". Post form using method="POST" and action must be another page lets say called doLogin.php which will actually contain the login PHP code.
Its time to write the code in doLogin.php which will be as follows.


session_start();
// Following Include File called "config.inc.php" contains DB connection code so make such and include it here
include_once("inc/config.inc.php");

$userName = $_POST["username"];
$password = $_POST["password"];
$errMsg="";
if($userName != "" && $password != "")
{
$encryptPassword = md5($password);
$authSql = "SELECT userID,userStatusID FROM user
WHERE userName = '".$userName."'
AND password = '".$encryptPassword."'
AND userActive = 1";

$authResult = mysql_query($authSql)OR die('Couldn\'t Authenticate Visitor:'.mysql_error());
$authRow = mysql_fetch_array($authResult);
$userID= $authRow['userID'];
$userStatus= $authRow['userStatusID'];

if ($userID > 0)//If user with this username and password actually fetched from db
{
$_SESSION['USER_ID'] = $userID;
$_SESSION['USR_LOGIN'] = $userName;
$_SESSION['USR_STATUS'] = $userStatus;
//Redirect user after being login to a page where you want.
header("Location: mainPage.html");
}
else //User have entered either password or username wrong or he is disabled or does not exist.
{
header("Location: login.html?msg=invalid");
}
}
else
{
// The value of user name or password not entered
header ("Location: login.html?msg=missing");
}
?>

Up-till now we have complete the initial login process but one small but extremely important thing still remains is to check on every page that if user came here after getting login or just putted in the address. If he/she didn't came through the login then he/she must be redirected to the login page. So include following small piece of code in beginning for every page before every thing else and it will do it for us.


session_start();
if (isset($_SESSION['USR_LOGIN'])=="")
{
header("Location:login.html?msg=Login_Required");
}
?>

Now this will redirect user to login page if he/she didn't came after login.

While login process we had set another session variable called $_SESSION['USR_STATUS'] this will actually help us to enforce privileges after login.

For example a piece of content of page is if only for admin and as admin's user status ID is '1' we will put a simple check.



session_start();
if (isset($_SESSION['USR_STATUS'])==1)
{
//display admin content here
}
?>

Or for an operator


session_start();
if (isset($_SESSION['USR_STATUS'])==2)
{
//display Operator content here
}
?>

Now finally for logout make a page named logout.php and put a link to it on any page. When some one will click that link he will go to logout page and will automatically logout and will be redirected to another page. Content of "logout.php" will be as follows.


session_start();
$_SESSION = array();
session_destroy();
// Redirect to following page after logout
header("Location: index.html");//Change the page according to requirement
?>


Now go and implement this all stuff and enjoy new knowledge of being login and logout. So start playing with it.

Posted in |

PHP code to accept and decode incoming email message, pipe to script made easy

We are already reached a point where we are using web 2.0 which is much more dynamic and user interactive. Also journey towards web 2.5 or 3.0 is already started. Now a days on daily basis in many systems we need email processing, i.e. data from incoming email message should automatically be inserted into database.

Lets see how incoming emails can be processed by custom scripts.

This is process of just two steps.

1. Write your own email processing script which decodes the incoming email messages and inserts data to db or a file

2. Set a forwarder in cpanel which redirects the incoming email to your personal email processing script

We will see and understand the both steps so the readers of this post can fully get able to process incoming email message.

STEP 1. Write Incoming Email processing script:-


Before moving to the actual script let me clear that your script must not output a single character on screen in order to work, as this script will run on backend when each email will be redirected to it through cpanel forwarder to script.

First line of the script will be out of PHP starting tag and it is the instruction which tells server the path of php which will be used to run this script. Please remember there must be nothing before this line in file, even not a space or any other character. Extension of file must always be .php

Lets move to script now each part is coming up with proper comments for making the process easier for you

#!/usr/bin/php -q

$htmlFound=0; // Database connection, in case you have to add data to db mysql_connect('localhost','username','password') or die('db error 1'); mysql_select_db('dbname') or die('db error 2');
//Stdin catches the whole text of incoming email puts it into $fd variable
$fd = fopen("php://stdin", "r"); // Read the first two MB of incoming email, (As in text and HTML mails message always resides in first two MB of data)
$fllg=0; $email = ""; $contents = "";
while (!feof($fd))
{
$contents .= fread($fd, 204800);
if($fllg==0)

{
$email=$contents; $fllg=1;
}
} fclose($fd);
//Add Slashes
$email=addslashes($email);
// Empty variables to avoid errors later on
$from = ""; $replyto = ""; $subject = ""; $headers = ""; $message = ""; $split = true;
// Break the e-mail into a line by line array to be put together again later on.
$lines = explode("\n", $email);


//Start splitting the headers and message from extracted email part.

for ($i=0; $i if ($split) {
// this is a header
$headers.= $lines[$i]."\n";
// look out for special headers
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches))
{
$subject = $matches[1];
}
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {

$from = $matches[1];
}

if (preg_match("/^Reply-To: (.*)/", $lines[$i], $matches))
{

$replyto = $matches[1];
}
}
else
{
$htmo=strpos($lines[$i],"Content-Type: text/html;");
if($htmo===false) //Plain text part is still being processed
{}
else

{
$htmlFound=1;
}//If in multipart messege Html part is started then set the varable to 1

$su=$subject[0];
$su.=$subject[1];
$su.=$subject[2];
$currLine=$lines[$i];
if($su=="RE:"||$su=="Re:")//check for replys -- dont show origional messages in replys.
{
//Same $htmlFound variable here is used to stop fetching the origional message from a reply
if($currLine[0]==">")
{
$htmlFound=1;
}
if($currLine=="---- Original Message -----\n")
{
$htmlFound=1;
}

if($currLine=="---- Original Message -----")
{
$htmlFound=1;
}

}

if($htmlFound==0)
{ // not a header, but message
$message.=$lines[$i]."\n";

}
} if (trim($lines[$i])=="") { // empty line, header section has ended $split = false; } }

// Get the current time to keep the database on a standard time listing
$time = time();

//Pick out the sender's email without any extra characters just simple email which can be reused to put in db or send a reply etc
if(strpos($from, "<"))
{
$from_email = substr($from, strpos($from, "<")+1, strpos($from, ">")-strpos($from, "<")-1);
}
else if(strpos($from, "[mailto:"))
{
$from_email = substr($from, strpos($from, "[mailto:")+8, strpos($from, "]")-strpos($from, "[")-8);
}
else if(strpos($from, "[Mailto:"))
{
$from_email = substr($from, strpos($from, "[Mailto:")+8, strpos($from, "]")-strpos($from, "[")-8);
}
else if(strpos($from, "["))
{
$one=strpos($from, "[")+1;
$two=strpos($from, "]")-strpos($from, "[")-1;
$from_email = substr($from,$one, $two);
}
else if(($from[0]=="[")&&($from[1]=="m") && ($from[2]=="a") && ($from[3]=="i") && ($from[4]=="l") && ($from[5]=="t") && ($from[6]=="o") && ($from[7]==":"))
{
$one=strpos($from, "[mailto")+8;
$two=strpos($from, "]")-strpos($from, "[mailto")-8;
$from_email = substr($from,$one, $two);
}
else if(($from[0]=="[") && ($from[1]=="M") && ($from[2]=="a") && ($from[3]=="i") && ($from[4]=="l") && ($from[5]=="t") && ($from[6]=="o") && ($from[7]==":"))
{
$one=strpos($from, "[Mailto")+8;
$two=strpos($from, "]")-strpos($from, "[Mailto")-8;
$from_email = substr($from,$one, $two);
}

else if($from[0]=="[")
{
$one=strpos($from, "[")+1;
$two=strpos($from, "]")-strpos($from, "[")-1;
$from_email = substr($from,$one, $two);
}
else if($from[0]=="<")
{
$one=strpos($from, "<")+1;
$two=strpos($from, ">")-strpos($from, "<")-1;
$from_email = substr($from,$one, $two);
}
else
{
$from_email=trim($from);
}


//You are now done with email accepting script, following variables contain following data
//$from_email contains senders email neat and clean without extra characters
//$from contains sender's email full line with extra characters, use of variable $from_email is recommended over this
//$replyto contains email which can be used to reply sender, still use of $from_email is recomended
//$subject contains subject of incoming email
//$headers contain full header text
//$message contains the email message
//$time contains the current date/time info, which can be saved in your favorite/desired format.

//Now as I have specified all the extracted data variables, you can do anything with them, i.e. save email as a record in a db or save it in a text file. How you use these variables is fully up to you.

?>

So uptill now our email accepting script is complete. Save it in a file with extention as .php for example "handleMailz.php" and upload it inside an hosting account e.g. inside public_html folder.

STEP 2. Setup email forwarder to deliver emails to this newly developed script:-
Now next step is to set up a forwarder in cpanel which will redirect all incoming email messages to this script.

Lets see how to do this, considering the name of script file is "handleMailz.php" and it is uploaded in your hosting account's public_html folder.

- Login to your cpanel
- Under mail category click forwarders
- Click add forwarder button
- Now on target screen fill the add new forwarder form accordingly, in "address to forward" put in email address from which you want all email to be sent to the script.
Also under destination heading select third option pipe to program and add the destination of your script, path muct be relative to your home directory. e.g "public_html/handleMailz.php" in our case. Also see added cpanel image.
Now this script can be used in anysupport system to automatically accept incoming emails, parse required information and insert it into database.

Now its time to play with the script and if you find any difficulty in setting up the script feel free to contact me at "khurram1284pk [@]yahoo.com". I have customised and setup this script many times, so if you need my help in settingup this kind of forwarding, or integrating this into a web system effectively, I will be more than happy to help you. Just contact me using above email address.

Just Enjoy.

Posted in |

PHP code to Remove White Spaces from beginning, end or both sides of string

There are three PHP trim functions which are used to remove the white spaces from start, end or both sides of a string.
White Spaces include

  • " " (Normal Space Characters)
  • "\t" (Tabs)
  • "\r" (Return Characters)
  • "x0B" (Vertical Tab Characters)
  • "\0" (NULL Bytes)
Following are functions to remove above White Spaces from a string

Function to Remove White Spaces From Beginning of String:-
ltrim();

Can be Used As


$string = ltrim($string);
?>

Function to Remove White Spaces From End of String:-
rtrim();

Can be Used As


$string = rtrim($string);
?>

Function to Remove White Spaces From Beginning and end of String:-
trim();

Can be Used As


$string = trim($string);
?>

So start using it :-)

Posted in |

PHP Code to convert text in array of lines and use specific line

While parsing with PHP some times we need to parse the whole text to find and use only a specific line. In this senario converting the whole text in array of lines will be a really handy task. And easily we can reach that specific line.

Now text my be of two types, one coming from a text file etc or coming from html file following are two methods may be used to make array of lines from the given text.


// Consider variable $text contains some text ( one or more paragraphs )
//Normal text / Text coming from text file'

$textAry = explode("\n", $text);
?>

//HTML Text ( remeber in it new line comes with a
)



$textAry = explode("
", $text);

?>

Now array of lines will reside in an array variable $textAry

And if you have to use the fifth line from array you will use it like:
echo $textAry[4]; //indexing starts from 0 :-)

Also you can use this array according to your requirements, I mean you can search in array or use any other way you want and do wonders. :-)

Posted in |

Web Template DesignWeb Template Modification, Photo editing only go for Paint shop prorfes

JASC Paint Shop Pro is a software for web interface design and image processing task. I love it and always preffered in compare to Adobe products. The reason is it provides the same functionality but is very easy to use. You don't need any skills, use this 2 to 3 times and look into different available options you will get used to it very soon.

Posted in |

free Web Template Design

JASC Paint Shop Pro is a software for web interface design and image processing task. I love it and always preffered in compare to Adobe products. The reason is it provides the same functionality but is very easy to use. You don't need any skills, use this 2 to 3 times and look into different available options you will get used to it very soon.


Good thing is it provides all advanced features like croping, slicing, image enhancement and many more. Perfect for designing the webtemplates you don't need to go anywhere else if you are using this. Give it a try, the basic is Paint Shop Pro 7, I am now using the Paint Shop Pro 9. Lots of advanced version are already in the market.

Just give it a try and give feedback.

You can find it on jasc.com Just visited the latest one is the best.
It is a product of corel.

Posted in |

PHP code to read a text file

Sunday, January 25, 2009

PHP file functions - Read, Write, Append

I have posted about four times on this blog to cover the file functions, to read, write append data to files. This post gives links to each post so that if you are up to learn file reading and writing you can find whole stuff on single place. So here we go.

- PHP code to read text from a file
- PHP code to read single line or read text line by line from text file
- PHP code to create/open file for writing
- PHP Code to append data to a file(write data at end of file)

If you have any more questions about file handling in PHP just direct them to me via comments.


PHP append text to a file

Following php script opens an existing file and appends the text to it. In other words it add the text at the end of file without removing the old data. If in case it don't find file with specified name in current directory, it creates the file with that name in current directory.

If your file is in another directory specify full path on place of file name.




$fh = fopen('fileName.txt', 'a') or die("can't open file"); //open file for appending data
$text = "this is text to be written to file, so hello how are you\n";
fwrite($fh, $text); //write text on the end of file.
fclose($fh);
?>


PHP Create or open a file and write text into it

Following code will help us in creating a file a write text into it, if file with specified name already exists if will overwrite the file data.


$fh = fopen('fileName.txt', 'w') or die("can't open file");
$text = "this is line one\n";
fwrite($fh, $text); //write first time to file
$text = "this is line 2\n";
fwrite($fh, $text);//write second time to file
fclose($fh);
?>

Variable $text may contain many lines.
Remember if file already exists this will remove all old data, to add data to file without removing old data see append data to a file



PHP code to read single line and read line by line text file

fgets is the function which reads single line in a file, and with a loop with this function how this reads single line, it reads the line where currently pointer is.

Read single line on pointer location

$filename="FileNameHere.txt";
$fh=fopen($filename,'r'); //r means we are opening file only for reading
$textLine = fgets($fh); // reading the line where the pointer currently is
fclose($fh); //script closes file
echo $textLine; //displaying text line which is just read from file
?>

Read Whole file line by line and display


$fh = @fopen('fileName.txt', 'r');
if ($fh) {
while (!feof($fh)) { //loop for pointer to go to each line
$buffer = fgets($fh);//reading line
echo $buffer; //displaying line
$buffer1.=$buffer; //storing whole text of file in $buffer1 for any future use
}
fclose($fh);
}
?>


Saturday, January 24, 2009

PHP Script to read a text file

Mostly while working with web some times we need our page to read text from a text file so following is code to read text from a text file.


$filename="FileNameHere.txt";
$fh=fopen($filename,'r'); //r means we are opening file only for reading
$textinfile = fread($fh, filesize($filename)); //fread which takes file handle and file size, reading the file data
fclose($fh); //script closes file
echo $textinfile; //dispalying text which is just read from file
?>

Now variable $textinfile contains whole text/data of file, this can be displayed or used anyway you want.

Posted in |