Archive for the 'PHP' Category
Sub archives: Images Mapping DateTime
The following is a simple method to set your timezone within PHP. You need to do this at the start of each of your pages. If your using OOP (Object-Oriented Programming) in PHP then put this in one of your main objects. Otherwise just include the line at the start of each file. If thats not possible, just include it at the top of any file that uses the built in date or time functions.
<?php
echo "Original Time: ". date("h:i:s") ."n";
date_default_timezone_set("Europe/London");
echo "New Time: ". date("h:i:s") ."n";
?>
As you can see, you need to use the
date_default_timezone_set() function along with a timezone identified.
You can find a list of valid timezones at
http://uk2.php.net/manual/en/timezones.php
Posted by epic at 16:03pm Permalink
Sending HTML emails with PHP is actually alot easier than many would want you to believe.
First off, lets define the to, from and subject fields.
$to = 'joe123@hotmail.com'; //The email address you wish to send to//
$from = 'joe123@hotmail.com'; //The email address you wish the message to come from//
$subject = 'An HTML Email';
Next, define the email headers.
$headers = "From: $from\r\n"; //Defines the from address
$headers .= "Content-type: text/html\r\n"; //Sets the content type to text/html
Next, write the content of the message. Here we assign this to the variable $message.
//begin message
$message = <<<EOF
<html>
<body bgcolor="#E9F0FA">
<p>
<strong>This is an HTML Email message</strong><br />
<br />
<a href="http://www.epicarena.com/">epicarena.com</a>
</p>
<p>
You can now send HTML emails.</p>
</body>
</html>
EOF;
//end of message
Finally, send the message using the standard mail function.
//Send the email
mail($to, $subject, $message, $headers);
Simple
$to = 'joe123@hotmail.com'; //The email address you wish to send to//
$from = 'joe123@hotmail.com'; //The email address you wish the message to come from//
$subject = 'An HTML Email';
$headers = "From: $from\r\n"; //Defines the from address
$headers .= "Content-type: text/html\r\n"; //Sets the content type to text/html
//begin message
$message = <<<EOF
<html>
<body bgcolor="#E9F0FA">
<p>
<strong>This is an HTML Email message</strong><br />
<br />
<a href="http://www.epicarena.com/">epicarena.com</a>
</p>
<p>
You can now send HTML emails.</p>
</body>
</html>
EOF;
//end of message
//Send the email
mail($to, $subject, $message, $headers);
Posted by OLLIE at 23:02pm Permalink
Once you start building any complex site and needs to log a users IP address you will need this neat little piece of code. Its easy to remember and easy to use. Great for logging visitor events (for example posts to a message board!).
If register globals is on$ip=@$REMOTE_ADDR;
The above will save your ip address to a variable called $ip. Simple eh?
If register globals is off$ip=$_SERVER['REMOTE_ADDR'];
SIMPLE!
Posted by OLLIE at 20:36pm Permalink
When programming PHP you may find the need to use random numbers. You may see this in use on websites that provide changing log-in messages, or random quotes. The random function can be very powerful but is in fact, simple to use.
There are two random functions in php:
int
rand ( [int min, int max] )
int
mt_rand ( [int min, int max] )
The first function, rand(), returns a pseudo-random integer between min and max.
If you wanted to return a number between say, 5 and 10, you would write
echo rand(5, 10);
If you wanted to return a number between 0 and 10, you would write
echo rand(0, 10);
Finally, using rand on its own will return a random number
echo rand(); //When tested returned: 18639
The second function, mt_rand (Mersenne Twister) takes the same arguments but is far more complex, and will return numbers which appear more random than those returned by rand. That said, even though the numbers appear more random, the execution time is much faster than rand (upto four times faster).
echo mt_rand(5, 10); //7
echo mt_rand(0, 10); //3
echo mt_rand(); //177136487
Ok, so the random functions in PHP are pretty straight forward. But to demonstrate a use of rand i have provided the following code...
switch(rand(1,5))
{
case 1:
$welcomeMessage = 'Welcome to my site'; break;
case 2:
$welcomeMessage = 'Thank you for visiting'; break;
case 3:
$welcomeMessage = 'Hello Visitor'; break;
case 4:
$welcomeMessage = 'Please leave your comments'; break;
case 5:
$welcomeMessage = 'Ah! Welcome my good friend'; break;
}
print $welcomeMessage;
Goodluck
Posted by OLLIE at 14:32pm Permalink
Ok, well ive been playing with file uploads recently and have come across the need to create filenames on the fly. Following is a random filename generator. Its actually pretty simple when you look at it...
/** Function: generate_rand_filename
* Param1: $1 - Generates a random string thats as long as param $l given.
**/
function generate_rand_filename($l)
{
//Allowed characters//
$c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
//Seed the random number generator//
srand((double)microtime()*1000000);
//Loop upto $l times and add a character to the string each time//
for($i=0; $i<$l; $i++)
$rand.= $c[rand()%strlen($c)];
//Return your new string//
return $rand;
}
Thats the basis of the function. But thats not all. You will also need to add an extension to the filename, and may also want to have a prefix. If you do, just use the following code:
$type = '.jpg';
$prefix = 'upload-';
$filename = $prefix;
$filename .= generate_rand(10);
$filename .= $type;
Good luck...
Posted by OLLIE at 13:01pm Permalink
Okies, ive managed to create a better image resize function. The one i found before was pretty poor if not kinda similar. Anyways, hope this helps.
To call the function you need some basic details.
You need the files temporary name (from $_FILES), an upload directory, a filename (i suggest randomly creating them, ill post an article soon on that), and your desired width and heights (ive used 250).
NOTE: Height may vary slightly to ensure resizing is to scale.
$filetmpname = $_FILES['file']['tmp_name'];
$uploaddir = './images/';
$filename = 'yourfilename.jpg';
$width = 250;
$height = 250;
$resize = resizePic($filetmpname, $width, $height, $filename, $uploaddir);
The function looks like this:
function resizePic($filetmpname, $allowedwidth, $allowedheight, $filename, $uploaddir)
{
// Create an image for us to resize
$src = imagecreatefromjpeg($filetmpname);
//If image creation fails, return failse//
//This step is not actually really necessary, but I do it for//
//error provention//
if (!$src)
return false;
// Get dimensions of origional image
list($width,$height)=getimagesize($filetmpname);
//Maintains size ratio. Does not squash or squeeze image.//
$newwidth=$allowedwidth;
$newheight=($height/$width)*$allowedheight;
$tmp=imagecreatetruecolor($newwidth,$newheight);
//now, actually resize image using dimensions just worked out//
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
//generate filename using given values. Write image to disk from tmp location//
$filename = $uploaddir.$filename;
imagejpeg($tmp,$filename,100);
imagedestroy($src);
imagedestroy($tmp);
}
Hope this helps. Any improvements to it, let me know.
Posted by OLLIE at 12:52pm Permalink
Okies, for anyone that has not coded in PHP before...
Its HELLO WORLD for PHP.
Simple and easy...
<?php
echo 'Hello World!';
?>
Check it out soon for some Object Orientated PHP demos...
Posted by OLLIE at 07:19am Permalink
So, heres a function to count the days between two dates. Its pretty easy to understand and very easy to use.
Ive added a few comments but its important to know, the strtotime function
only works on american dates, eg: MM/DD/YY and NOT DD/MM/YY like us English use...
function count_days($a, $b)
{
//Convert times to string format//
$datea = strtotime($a);
$dateb = strtotime($b);
//Use getdate on the strings (explodes them into array form//
//See manual for specific array column names//
$a_dt = getdate($datea);
$b_dt = getdate($dateb);
//Uses maketime to generate a numeric value for the date//
//Ive used 12, 0, 0 to specify midday every day (Using a constant time value)//
$a_new = mktime(12,0 ,0, $a_dt['mon'], $a_dt['mday'], $a_dt['year']);
$b_new = mktime(12,0 ,0, $b_dt['mon'], $b_dt['mday'], $b_dt['year']);
//Returns a rounded value devided by number of seconds in the day//
return round(($a_new - $b_new) / 86400);
}
Hope its of some use to someone.
Regards
Ollie
Posted by OLLIE at 18:39pm Permalink
Well, this is a pretty awsome function. It takes two points of reference, using Longitude and Latitude and returns the distance between them.
I use this for compairing distances between zip codes and displaying results based on the values returned. Its pretty sleak if you ask me...
Good luck...
<?php
/**
* Function: distance
* Param1: lat1 - Latitude of point 1.
* Param2: lon1 - Longitude of point 1.
* Param3: lat2 - Latitude of point 2.
* Param4: lon2 - Longitude of point 2.
* Param4: unit - M(Miles) K(Kilometers) N(Nautical Miles)
*
* Takes the longitude and latitude of two locations along with a unit type.
* Calculates the distance between the two and returns a result.
*/
function distance($lat1, $long1, $lat2, $long2, $unit) {
$theta = $long1- $long2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == "K")
return ($miles * 1.609344);
else if ($unit == "N")
return ($miles * 0.8684);
else
return $miles;
}
//Following values used for testing purposes.//
//Chandler, Arizona -> Las Vegas Nevada//
echo distance(33.239097, -111.86355, 36.233655, -115.06881, "M") . " Miles
";
echo distance(33.239097, -111.86355, 36.233655, -115.06881, "K") . " Kilometers
";
echo distance(33.239097, -111.86355, 36.233655, -115.06881, "N") . " Nautical Miles
";
?>
Posted by OLLIE at 22:46pm Permalink
So, today I realized i needed to create some thumbnails using PHP. For a long time ive just been resizing the same image which is highly inefficient and a waste of bandwidth. So, instead i came across the following code:
<?php
function thumbnail($image_path,$thumb_path,$image_name,$thumb_width)
{
$src_img = imagecreatefromjpeg("$image_path/$image_name");
$origw=imagesx($src_img);
$origh=imagesy($src_img);
$new_w = $thumb_width;
$diff=$origw/$new_w;
$new_h=$new_w;
$dst_img = imagecreate($new_w,$new_h);
imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, $new_w, $new_h, imagesx($src_img), imagesy($src_img));
imagejpeg($dst_img, "$thumb_path/$image_name");
return true;
}
?>
Just make sure the output directory is writable...
UPDATE: So, i tested it out. Im not too happy with the results. It decreased the quality a little too much and made the images look like a two year old had drawn over them with a oversized paintbrush... if that helps at all... seriously though, im going to try fixing it to keep the quality or look elsewhere for another function. Keep your eyes peeled for an update...
Posted by OLLIE at 21:57pm Permalink