Archive for the ‘PHP Code Samples’ Category

Filed Under (LAMP, PHP Code Samples, Technology Junk) by Anoop on July-6-2007
Code (php)

<?
function getLocaltime($GMT,$dst){
        if(preg_match('/-/i',$GMT))
        {
                $sign = "-";
        }
        else
        {
                $sign = "+";
        }

        $h = round((float)$GMT,2);

        $dst = "true";

        if ($dst)
                {
                $daylight_saving = date('I');
                if ($daylight_saving)
                                {
                   if ($sign == "-"){ $h=$h-1}
                   else { $h=$h+1; }
                }
        }

        // FIND DIFFERENCE FROM GMT
        $hm = $h * 60;
        $ms = $hm * 60;

        // SET CURRENT TIME
        if ($sign == "-"){ $timestamp = time()-($ms); }
        else { $timestamp = time()+($ms); }

        // SAMPLE OUTPUT
        $gmdate = gmdate("F d, Y - g:i A", $timestamp);
        return $gmdate;
}

echo ' Server Time: '.date("F d, Y - g:i A",time());;

echo " || GMT Time: " . gmdate("F d Y - g:i A", time());

echo ' ||  Localtime: '.getLocaltime('+5.5',0);

?>
 


Filed Under (PHP Code Samples) by Anoop on June-17-2007
Code (php)

<?php

//This function can be used to validate usernames
//The maximum and minimum length of the username can be set. Also you are allowed to set the allowed characters.

function is_valid_username($username, $valid_chars, $min_length, $max_length)
{
    if(!eregi("^[a-z0-9$valid_chars]{".$min_length.",".$max_length."}$",$username)){
        return false;
    }
    return true;
}

// Usage Example

$username = "DFKGJDF04FL";
$valid_chars = "._+?";
$min_length = 5;
$max_length = 15;
if(is_valid_username($username, $valid_chars, $min_length, $max_length))
{
    echo "$username is valid";
}
else
{
    echo "$username is invalid";
}
?>
 


Filed Under (PHP Code Samples) by Anoop on June-14-2007
Code (php)

<?
function applytext($file,$text,$Position,$fontsize,$font,$newfile,$Margin = 5)
{
        if($newfile == '')
                $newfile = $file;

        $fontangle = 0;

        $Type  = strtolower(strrchr($file,'.'));
        if($Type == '.jpg' || $Type == '.jpeg')
                $simg = @imagecreatefromjpeg( $file );
        if($Type == '.gif')
                $simg = @imagecreatefromgif( $file );
        if($Type == '.png')
                $simg = @imagecreatefrompng( $file );

        if(!$simg)
                        return 0;

        $currwidth = imagesx($simg);
        $currheight = imagesy($simg);

        $im = imagecreatetruecolor($currwidth, $currheight);
        $Imah = imagecopyresampled($im, $simg, 0, 0, 0, 0, $currwidth, $currheight, $currwidth, $currheight);

        // Get exact dimensions of text string
        $box = @imageTTFBbox($fontsize,$fontangle,$font,$text);

        // Get width and height of text from dimensions
        $textwidth = abs($box[4] - $box[0]);
        $textheight = abs($box[5] - $box[1]);

        $FW = $textwidth;
        $FH = $textheight;

        switch($Position)
        {
                case "center" :
                {
                        $xcord = ($currwidth/2)- ($FW/2);
                        $ycord = ($currheight/2)- ($FH/2);
                        break;
                }
                case "top-left" :
                {
                        $xcord = $Margin;
                        $ycord = $FH+$Margin;
                        break;
                }
                case "top-right" :
                {
                        $xcord = ($currwidth- ($FW+$Margin));
                        $ycord = $FH+$Margin;
                        break;
                }
                case "bottom-left" :
                {
                        $xcord = $Margin;
                        $ycord = $currheight - ($FH+$Margin);
                        break;
                }
                case "bottom-right" :
                {
                        $xcord = ($currwidth- ($FW+$Margin));
                        $ycord = ($currheight - ($FH+$Margin));
                        break;
                }
        }

        $color = imagecolorallocate($im, 0, 0, 0);
        imagettftext ( $im, $fontsize, $fontangle, $xcord+2 , $ycord+1  , $fontcolor, $font, $text );
        $color = imagecolorallocate($im, 255, 255, 255);
        imagettftext ( $im, $fontsize, $fontangle, $xcord, $ycord, $color, $font, $text );

        if($Type == '.jpg' || $Type == '.jpeg')
        {
                imagejpeg( $im, "$newfile" );
        }
        if($Type == '.gif')
        {
                imagegif( $im, "$newfile" );
        }
        if($Type == '.png')
        {
                imagepng( $im, "$newfile" );
        }
        imagedestroy($im);
        return 1;
}

$iscreated = applytext("clippart.jpg",'www.teckjunk.websewak.com','center','15','arial.ttf','new.jpg');

//applytext('[targetimagefile]','[text to apply]','[position]','[font size]','[font]','[saveas]','[margin]');
?>
 


Filed Under (PHP Code Samples) by Srikanta on May-30-2007

This random password generator generates the password upto a desired length and includes the desired set of characters. It ensures that you will get atleast one random character from the character type you have choosen.

Click here to see the demo of the Random Password Generator

Code (php)

<?
$Source[0] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$Source[1] = "0123456789";
$Source[2] = "!@#$%^*_-+=?|:";
if($_POST['submit'] == 1)
{
        if($_POST['alpha'] == '' && $_POST['num'] == '' && $_POST['other'] == '')
        {
                $Error = "Please provide 'Password Type'.";
        }
        else
        {
                if($_POST['alpha'] == '1' )
                {
                        $Use[] = $Source[0];
                }
                if($_POST['num'] == '1' )
                {
                        $Use[] = $Source[1];
                }
                if($_POST['other'] == '1' )
                {
                        $Use[] = $Source[2];
                }
                $Passwordlen = $_POST['passwordlen'] ;
                if($Passwordlen >= count($Use))
                {
                        $Min = 0;
                        while($i < $Passwordlen)
                        {
                                $Max = strlen($Use[$i % count($Use)])-1;
                                $Rand = rand($Min,$Max);
                                $Password .= substr($Use[$i % count($Use)],$Rand,1);
                                $i++;
                        }
                }
                else
                {
                        $Error="Please enter password length  greater than number of 'Password Type' selected.";
                }
        }
}
?>
<html>
<head>
<style>
<!--
.box{
        background-color:#ba0808;
        color:#ffdf9a;
        font-size:20px;
}
.header{
        background:#6f0006;
        color:#ffa200;
}
.password{
        background:#630102;
        color:#ffa200;
}
-->
</style>

</head>
<body>
<CENTER>
<div class="box">
<form method="POST">
<div class="header">
<h1>Password Generator</h1>
</div>
<table class="box">
<?
if($Error != '')
{
?>
<tr>
<td>
                <font color="#ffa200" size="6"><?=$Error;?></font>
        </td>
</tr>

<?
}
?>
<tr>
<td>
                Enter your password length:
<input type="text" name="passwordlen" size="2" maxlength="2" value="<?=$_POST['passwordlen'];?>">
</td>
</tr>
<tr>
<td>
                Please Select Characters to be used in the password:
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="alpha" value="1" <?
if($_POST['alpha']!='')
{
        echo "checked";
}
?>
>Use Alphabets (e.g., QlqzkBKrod )
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="num" value="1" <?
if($_POST['num']!='')
{
echo "checked";
}
?>
>Use Numbers (e.g., 5122401523 )
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="other" value="1" <?
if($_POST['other']!='')
{
echo "checked";
}
?>
>Use Other Characters (e.g., ?=:!?%^-@|  )
</td>
</tr>
<tr>
<td>
<input type="hidden" name="submit" value="1">
<input type="submit" value="Generate">
        </td>
</tr>

</TABLE>
</form>
<div class="password">
<?
if($Password != '')
{
?>
<h2>Generated Password: <?=$Password;?></h2>

<?
}
else if($Error != '')
{
?>
<h2>Error : <?=$Error?></h2>

<?
}
else
{
?>
<h3>Password Generater</h3>

<?
}
?>
</div>
</div>

</CENTER>
</body>
</html>
 



Filed Under (Articles, PHP Code Samples) by Virender on May-29-2007

Cookies and Sessions both fulfill the purpose of storing data across the pages of a website. Both have their own advantages.

Cookies are stored on the client side and can be set to a long lifespan, which means that data stored in a cookie can be stored for months if not years. Cookies work fine with a web application installed on a cluster of web server, whereas sessions are stored on the server, means if one web server is handling the request, the other web server on the cluster will not have access to the information stored.

As Sessions are stored on web server, this gives extra security and freedom. We do not transmit session data with each page, just an ID and the data is loaded from the local file stored on the server. Clients do not know about the information we store about them, which is not the case with Cookies.

Many browsers have a limit for the Cookies as to stop the wastage of bandwidth that is caused by meaningless Cookies, but that is not the case with Sessions. They are stored on the server, hence they can be of any size. One can use them as per requirement. If he wants to store information until visitor comes back next day then Cookies are the way to go. If some part of cookie data is crucial then we can store it in database and just store an ID in the Cookie to reference the data. If not, then use Sessions, as they are little easier to use and do not require their entire data to be sent with each page. Sessions get cleaned as soon as visitor closes the web browser.

Let’s see how to use Cookies in a web page

The following script will store a Cookie labeled test on the client side with a value as “IsOn”. Please make sure that you set cookie values before sending any output to browser.

Code (php)

<?php
        setcookie("test", "IsOn", time() + (60 * 60));// variable name = test, value = "IsOn" and cookie life is one minute from current time. If you don't set cookie life, it will be expired after browser is closed.
?>
 

Now that our Cookie is set up, we can use it on every page of the site.

Code (php)

<?php
   echo $_COOKIE['test']; //displays "IsOn"
?>
 

If the above code shows nothing in output, then consider it as cookies being disabled or cookies improperly set. As you can see, we access information stored in cookies by using $_COOKIE[] array.

To destroy Cookies forcefully, we can use the following script:

Code (php)

<?php
        setcookie("test", "IsOn", time() - (60 * 60)); // setting a cookie life to a time that is past will actually expire the cookie instantly
?>
 

Now, let’s see how to use Sessions in a web page:

Code (php)

<?php
    session_start(); // this needs to be declared on the top of every page, specially before sending any output to the browser.
    $_SESSION['Check'] = 'test';
    echo $_SESSION['Check'];// displays "test" on any page of that web site
?>
 

We can use sessions on same page. Since sessions are server-side and the users have access to only the Session Identifier.

To destroy the Sessions for the current site, we can use the following script.

Code (php)

<?php
        session_destroy();
?>
 


Filed Under (PHP Code Samples) by Anoop on May-26-2007
Code (php)

<?
function makeClickableLinks($text)
{

        $text = html_entity_decode($text);
        $text = " ".$text;
        $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
                '<a href="\\1" target=_blank>\\1</a>', $text);
        $text = eregi_replace('(((f|ht){1}tps://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
                '<a href="\\1" target=_blank>\\1</a>', $text);
        $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
        '\\1<a href="http://\\2" target=_blank>\\2</a>', $text);
        $text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})',
        '<a href="mailto:\\1" target=_blank>\\1</a>', $text);
        return $text;
}

// Example Usage
echo makeClickableLinks("This is a test clickable link: http://www.websewak.com  You can also try using an email address like test@websewak.com");
?>
 


Filed Under (PHP Code Samples) by Anoop on May-22-2007
Code (php)

<?php
$URL = 'www.yah.in';
$ip = gethostbyname($URL); // Get IP address from a URL
$out = "The following URLs are equivalent (for dedicated IP addresses only): ";
$out .= $URL.', http://' . $ip . '/ http://' . sprintf("%u", ip2long($ip)) . "";
echo $out;
echo "Your IP address: ".$_SERVER['REMOTE_ADDR'];
?>
 

You can also use long2ip() function to get ip address back from a long code.



Filed Under (PHP Code Samples) by Srikanta on May-21-2007

PHP’s mktime() function doesn’t work before 1970, so here is the alternate function. Hope this helps somebody.

Code (php)

<?php
//Function to make timestamp for dates after year 1801
function timestamp($mm,$dd,$yyyy)
{
        if ($mm > 12 || $dd > 31 || $yyyy < 1800)
                return -1;
        $ysec=((($yyyy-1801)*365*24*3600)+(floor($yyyy-1801)/4)*24*3600);
        if(((($yyyy%4)==0&&($yyyy%100)!=0))||($yyyy%400==0))
        {
                $fsec = 29;
        }
        else
        {
                $fsec = 28;
        }
        if ($mm == 2 AND $dd > $fsec)
                return -1;
        switch($mm)
        {
                case 1  : $msec=0; break;
                case 2  : $msec=(31*24*3600); break;
                case 3  : $msec=(31+$fsec)*24*3600; break;
                case 4  : $msec=((31+31+$fsec)*24*3600); break;
                case 5  : $msec=((31+31+30+$fsec)*24*3600); break;
                case 6  : $msec=((31+31+30+31+$fsec)*24*3600); break;
                case 7  : $msec=((31+31+30+31+30+$fsec)*24*3600)break;
                case 8  : $msec=((31+31+30+31+30+31+$fsec)*24*3600); break;
                case 9  : $msec=((31+31+30+31+30+31+31+$fsec)*24*3600); break;
                case 10 : $msec=((31+31+30+31+30+31+31+30+$fsec)*24*3600); break;
                case 11 : $msec=((31+31+30+31+30+31+31+30+31+$fsec)*24*3600); break;
                case 12 : $msec=((31+31+30+31+30+31+31+30+31+30+$fsec)*24*3600); break;
        }
        $dsec=(($dd)*24*3600);
        return $ysec+$msec+$dsec;
}

//Example to use

$month=1;
$day=1;
$year=1914;

$time = timestamp($month,$day,$year);
if ($time != -1)
{
echo $time;// Displays 3566095200
}
else
{
echo "Invalid Date!";
}
?>
 


Filed Under (PHP Code Samples) by Srikanta on May-17-2007
Code (php)

<?php
// Function to convert Minutes to Hours : Minutes format
function to_hour_string($MM)
{
        $Hour=floor($MM/60);
        $Min=($MM%60);
        If($Hour>0)
        {
                $str = $Hour."hr";
                if ($Hour > 1)
                        $str .= "s";
                if ($Min > 0)
                        $str .= " ".$Min."min";
                if ($Min > 1)
                        $str .= "s";
        }
        else if ($Min > 0)
        {
                $str = " ".$Min."min";
                if ($Min > 1)
                        $str .= "s";
        }
        else
        {
                $str = "-";
        }
        return $str;
}

//Example
$MM=98; //$MM is Minutes

echo to_hour_string($MM); //displays 1hr 38mins

?>
 


Filed Under (PHP Code Samples) by AJ on May-15-2007
Code (php)

<?php
function check_email($email) //Function to check email validity
{
// First, we check that there's one @ symbol, and that the lengths are right
if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email))
{
// Email invalid because wrong number of
//characters in one section, or wrong number of @ symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("@", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++)
{
if (!ereg(
"^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
$local_array[$i]))
{
        return false;
}
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1]))
{ // Check if domain is IP. If not, it should be valid domain name
        $domain_array = explode(".", $email_array[1]);
        if (sizeof($domain_array) < 2)
                {
                        return false; // Not enough parts to domain
                }
        for ($i = 0; $i < sizeof($domain_array); $i++)
                {
                if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$",
 $domain_array[$i]))
                        {
                        return false;
                        }
                }
}
return true;
}
// Example Usage

$good_email = "sd@example.com";
$bad_email = "al.c";

$a = check_email($good_email);// returns true
$b = check_email(