Archive for php

How to Send Out a Mass Email Using PHP

Posted in php by ShortLikeAFox on September 19th, 2008

So you want to send out a mass email or you want to create a program that can quickly be changed to send out multiple mass emails. PHP makes this easy. In this example I will assume that you have a list of email addresses you want to send a certain email to. I will also assume that you are keeping this list in a database, but this code could easily be adjusted to use either a hardcoded email address list or list from another source.

<?php

 

//First connect to the database that contains the email address information.
$user = "USER";
$host = "HOST";
$password = "PASSWORD";
$database = "DATABASE";

$cxn = mysql_connect($host, $user, $password) or die ("Couldn’t connect to server");
mysql_select_db($database);

//Query the table that contains the email addresses. Fill in your own table name here…
$query = "SELECT * FROM theEmailAddresses ";
$result = mysql_query($query, $cxn) or die (mysql_error($cxn));
$nrows = mysql_num_rows($result);

//Who the sender will be identified as. You can put what you want here, but it really isn’t too ethical to place an email address that you don’t control here.
$from = "From: me@mydomain.com";
//A standard email subject line
$subject = "What’s new at mydomain.com ";
//The message
$message = "Hi valued friend,

We now sell cookies at mydomain.com. Be sure to check it out!
Sincerely,
me"
;

//We’ve already queried all of the email address. Now we just need to send the email
for ($i = 0; $i <$nrows; $i++){

$row = mysql_fetch_assoc($result);
extract($row);
//Replace $email with whatever the column of email addresses is called
$to = "$email";
//Send the email to each email in the database
if(mail($to, $subject, $message, $from)){

//Print the name of emails that were successfully sent. I use this just to make sure that the program hasn’t frozen. In theory their should be a steady stream of names being printed>

echo("$to<br/>");

}

}




?>

This bit of code takes advantage of the php mail() function. This is a very powerful and easy to use function. Remember that with great power comes great responsibility. Try not to use this function for evil.

How to Tell Where Your Visitors are Geographically Using PHP

Posted in PEAR, php by ShortLikeAFox on September 13th, 2008

If you have a website and want to tell where your users are coming from geographically PHP and PEAR make this possible. To turn a guest’s IP into a physical location the first thing you are going to need to do is make sure that you have the Net_Geo PEAR module. If you don’t have the Net_Geo PEAR module, you are going to have to use the PEAR Package Manager to acquire it.

If you don’t think that you have access to PEAR because of your hosting package, check out this explanation on how to install PEAR on an account that doesn’t allow access by default. It is written with GoDaddy shared accounts in mind, but should work for most hosting packages that don’t come with PEAR set up.

After you have Net_Geo package installed, it only takes a few lines of code to acquire geographical data:

<?php

require_once("Net/Geo.php");
$ip = $_SERVER['REMOTE_ADDR'];
//$ip = "64.246.30.37";
$firstNetGeo = new Net_Geo();
$geoData = $firstNetGeo->getRecord($ip);

?>

IP: <?php echo($ip); ?><br/>
Latitude: <?php echo($geoData['LAT']); ?><br/>
Longitude: <?php echo($geoData['LONG']); ?>
<br/>
Country: <?php echo($geoData['COUNTRY']); ?><br/>
State: <?php echo($geoData['STATE']); ?><br/>
City: <?php echo($geoData['CITY']); ?><br/>

 

The Code At Work:

IP: 38.103.63.60

Latitude: 38.98

Longitude: -77.39

Country: US

State: VIRGINIA

City: HERNDON

How to Divide One Image Into Multiple Images Using PHP

Posted in functions, php by ShortLikeAFox on August 26th, 2008

So you want to break one large image into multiple smaller images? No problem. This may seem like an obscure problem, but there are multiple reasons you’d want to do this. Maybe you want to create a visual sliding puzzle. Or maybe you are running a unique WordPress theme. Or maybe you want to create a collage of some kind. It really doesn’t matter why you want to split an image into smaller image, PHP makes this task easy. The example below only deals with jpegs. Changing the function to deal with other types of images wouldn’t be that hard.

 

<?php
//This function will split an image into a number of equally sized columns and rows.
function split_image($number_of_rows, $number_of_cols, $path_to_image, $file_name){

//$number_of_rows = # of rows you want;
//$number_of_cols = # of cols you wnat
//$path_to_image = the path to the folder the image is in, something like: /home/content/username/html/list/uploads/
//$file_name = The filename of the image: archery.jpg, etc.

// parse path for the extension
$info = pathinfo($path_to_image . $file_name);

//make sure we are dealing with a jpeg
if ( (strtolower($info['extension']) == ‘jpg’) || (strtolower($info['extension']) == ‘jpeg’) ){

// load image and get image size
$source = imagecreatefromjpeg( "{$path_to_image}{$file_name}" );
$width = imagesx( $source ); //Find the width
$height = imagesy( $source ); //Find the height
$segment_width = $width/$number_of_cols; //Determine the width of the individual segments
$segment_height = $height/$number_of_rows; //Determine the height of the individual segments

for( $col = 0; $col < $number_of_cols; $col++)
{

for( $row = 0; $row < $number_of_rows; $row++)
{

$fn = sprintf( "img%02d_%02d.jpg", $col, $row );
echo( "$fn" ); //I print the image name here, so that the process shows itself as it runs
$im = @imagecreatetruecolor( $segment_width, $segment_height );
imagecopyresized( $im, $source, 0, 0, $col * $segment_width, $row * $segment_height, $segment_width, $segment_height, $segment_width, $segment_height );
$file = "test.jpg";
//Save the images
if(imagejpeg( $im,"INSERT DESTINATION HERE ", 100 )) //The destination will be something like/home/content/c/h/d/images/$fn

echo("Has been made!<br/>");

}

}

}

}

?>

How to Include Functioning PHP Code in Your WordPress Posts

Posted in WordPress, php by ShortLikeAFox on August 17th, 2008

So you want to be able to use PHP in your WordPress blog posts and pages. That’s no problem. Just using <?php……..?> is going to make WordPress angry unless you install a plugin first. There are a few plugins out there that claim to offer this capability, but the one that I have found works the best is Exec-PHP.To begin using PHP code, follow these steps:

  1. Download Exec-PHP
  2. Install it like you would any plugin (The link above and readme file will walk you through this)
  3. If you are currently using it, you must turn off the WYSIWYG editor. To do this, go to Users -> Your Profile and uncheck the Use the visual editor when writing checkbox
  4. Start writing php code like you normally would: <?php ….code goes here ?>

That’s all there is to it!

How to Create and Use Dynamically Named Variables with PHP

Posted in php by ShortLikeAFox on August 17th, 2008

So you want to use dynamic variable names in your code. No problem. Let’s say you have 100 variables named dog0, dog1, dog2, …., dog98, dog99. Why you would want to use 100 variables like this instead of an array is beyond me, but it doesn’t matter for this example. To set these variables in a quick loop you could use the following:

for ($i = 0; $i < 100; $i ++){

$variableName = "dog$i";
$$variableName = $i; //sets $dog1 to 1, $dog2 to 2, $dog 34 to 34, etc….

}

Now let’s say you wanted to access all of these variables. You could use the following:

for ($i = 0; $i < 100; $i ++){

$variableName = "dog$i";
echo("<br/>");
echo("$variableName: ");
echo($$variableName);

}

This loop prints:

dog0: 0
dog1: 1
dog2: 2
dog3: 3
dog4: 4
dog5: 5
dog6: 6
dog7: 7
dog8: 8

etc… all the way to
dog99: 99

How to Intergrate ISBN Access on Your Webpages Using PHP

Posted in php by ShortLikeAFox on August 12th, 2008

ISBNs or International Standard Book Numbers are useful identifiers that can be used to find information about individual books. If you want to integrate ISBN lookups in your web applications PHP makes it doable.

Step One: ISBNdb.com is a has created an API that allows users from around the web to access their database of ISBN records. Here is their own description of the API:

ISBNdb.com’s remote access application programming interface (API) is designed to allow other websites and standalone applications use the vast collection of data collected by ISBNdb.com since 2003. As of this writing, in July 2005, the data includes nearly 1,800,000 books; almost 3,000,000 million library records; close to a million subjects; hundreds of thousands of author and publisher records parsed out of library data; more than 10,000,000 records of actual and historic prices.

To use this API you must first register. Registration takes literally seconds to complete. After this, you need to set up a key. Keys allow you to directly access the ISBN database from your own code. The ISBNdb.com website makes setting up keys easy.

Step Two: Now you’re start writing code to interact with the database. A request for an ISBN lookup will look something like this:

$isbnData = "http://isbndb.com/api/books.xml?access_key=XXXXXX&index1=isbn&value1=$isbnQuery";

You would insert your access key in the place of XXXXXX. $isbnQuery would be the isbn number you are interested in. $isbnData is an XML file. To access this data you need to let your code know what it is dealing with. Something like this will work:

$xmlData = @simplexml_load_file($isbnData) or die ("no file loaded") ;

Now you can access individual variables with calls similar to this:

$title = $xmData->BookList[0]->BookData[0]->Title ;

Here is a complete working example:

<?php

$searchQuery = "9780684801223"; //The ISBN for Ernest Hemingway’s Old Man and the Sea
$isbnData = "http://isbndb.com/api/books.xml?access_key=XXXXXX&index1=isbn&value1=$searchQuery"; //Remember to replace XXXXXX with your own access key
$xmlData = @simplexml_load_file($isbnData) or die ("no file loaded") ;
$title = $xmlData->BookList[0]->BookData[0]->Title ;
$authors = $xmlData->BookList[0]->BookData[0]->AuthorsText ;
$publisher = $xmlData->BookList[0]->BookData[0]->PublisherText ;

echo("$title<br/>");
echo("$authors<br/>");
echo("$publisher<br/>");

//This example prints:
//The old man and the sea
//Ernest Hemingway
//New York : Scribner Paperback Fiction, 1995.

?>

How to Confirm an Email Address Using PHP

Posted in php by ShortLikeAFox on August 5th, 2008

So you need confirmation of a user’s email address? No problem. There are a lot of reasons to require email confirmation, and PHP makes it simple.

Email confirmation can be completed is these steps:

  1. Prompt the user for whatever information you need from them (including their email address)
  2. Input this data in a database
  3. Send the user an email with a special confirmation key
  4. "Unlock" the data in the database once the confirmation key is entered.

How to do it:

<?php

//First, let’s connect to the database

$user_name = "dbUserName ";
$host = "dbHost";
$my_password = "dbPassword";
$db_name = "dbName";

//Connect to server and select database.
mysql_connect("$host", "$user_name", "$my_password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");

//The following line basically asks if the user needs to have the form displayed. Read down a little if you want to see where the variables come from

if(!(@$_GET['first'] == "no") && !(@$_GET['confirm'] == "yes"){
//Since this is the page’s first display and no confirmation code is included we should display the form for the user to fill out
//This form only takes one argument (the user’s email address).

?>

<form name="emailConfirmation" method="post" action="index.php?first=no">

<table align="center">
<tr>
<td>
Email: <input name="email" type="text" id="email" size="30" />
</td>
</tr>
<tr>
<td align="center">
<input type="submit" name="Submit" value="Submit"/>
</td>
</tr>
</table>
</form>

 

<?php

}

//if the form has been filled out, we need to generate a confirmation code, insert the confirmation code and user email into a database, and send an email to the email address.
elseif (@$_GET['first'] == "no"){ //if the form has been filled out…

//is_valid_email_address is NOT a valid php function. Insert your own email address checking function here…
if (!is_valid_email_address($_POST['email']))

echo("Sorry! The email address you entered is not valid.");

//If the email address appears valid and safe…
else{

$email = ($_POST['email']);
//Generate a confirmation code here. This is the way I choose to do it, but there are innumerable ways that will work.
$confirmation_code=md5(uniqid(rand()));
//Everything is more or less OK to enter into the database and then send an email to the user
$query = "INSERT INTO emailConfirmationTable(user_email, con_code) VALUES(’$email’, ‘$confirmation_code’)";
$result = mysql_query($query) or die ("Config Error 2223 ");
//Send the email
$to=$email;
$subject="Your shortlikeafox example confirmation";// From
$header="from: shortlikeafox <info@shortlikeafox.com>";
// Your message
$message="Your Comfirmation link! \r\n";
$message.="Click on this link to activate your account \r\n";
$message.="This link with expire whenever I feel like cleaning out the unconfirmed emails (every week or so) \r\n";
$message.="http://www.shortlikeafox.com/simple-email-confirmation-example/index.php?confirm=yes&confirmCode=$confirmation_code \r\n";
$sentmail = mail($to,$subject,$message,$header);

echo("Your Confirmation Email Has Been Sent!");

}

}
//If the user found this script from a link in his email, confirm it….
elseif(@$_GET['confirm'] == "yes"){
//Make the confirmCode relatively safe to use

$confirmCode = mysql_real_escape_string(@$_GET['confirmCode']);

$query = "SELECT * FROM emailConfirmationTable WHERE con_code = ‘$confirmCode’ AND is_confirmed = ‘0′";
$result = mysql_query($query) or die ("Error 234234");
$nrows = mysql_num_rows($result);
if ($nrows==1){
$query = "UPDATE emailConfirmationTable SET is_confirmed = ‘1′ WHERE con_code = ‘$confirmCode’ ";
$result = mysql_query($query) or die ("Config Error 222231231233 ");
if ($result)
echo("EMAIL CONFIRMED!!!");

}
else

echo("Could not confirm Email");

}

 

?>

It is very important to remember to validate the information that the user inserts in any form. I didn’t include a function for email address validation above, but a good place to start is Cal Henderson’s email validation function found here.

If you want to see this script in action, you can do so here.

How to Manually Insert a Group of Users Into an SMF Forum Using PHP

Posted in SMF (Simple Machine Forum), php by ShortLikeAFox on July 30th, 2008

This Tutorial assumes you are familiar with my post: How to Manually Insert a User Into an SMF Forum Using PHP.

I recently faced the challenge of moving 800 or so bands from a database into an SMF forum. I faced a couple of problems when making the move that I didn’t cover in the first post:

  1. The band names weren’t guaranteed to be safe for a character by character move into the SMF database. So some kind of name modifying function had to be employed.
  2. The bands don’t have passwords. So some type of password generation needs to be employed.

The steps I went about to register all of the bands in the forum went a little like this:

Open the Band Database

for each (Band){

Generate Password

Rename Band with "safe" name

Grab and generate information needed to insert the user

Insert Band into smf_members

Send Band an email with the password

}

Information I had available from the band database that was useful included: bandName, bandEmail, and bandWebsite

Here is the password generation function I used (blatently taken from totallyphp.co.uk):

function createRandomPassword() {

$chars = "abcdefghijkmnopqrstuvwxyz023456789";

srand((double)microtime()*1000000);

$i = 0;

$pass = ” ;

 

while ($i <= 7) {

$num = rand() % 33;

$tmp = substr($chars, $num, 1);

$pass = $pass . $tmp;

$i++;

}

return $pass;

}

The password created here is relatively weak, but it was good enough for my purposes. Any password generation function would work fine here. I chose this one because it would be easy for members to remember if they chose not to change it.

How to Do It:

//First connect to the band database
$username = "bandUsername ";
$host = "bandHost";
$mypassword = "bandPassword";
$db_name = "bandDatabase";

mysql_connect("$host", "$username", "$mypassword")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");

//Now grab all of the bands from the database
$query = "SELECT * FROM allBands ";
$bands = mysql_query($query) or die ("Config Error 2222b");
$userRows = mysql_num_rows($bands);

//Now lets connect to the smf db
$host="smfhost"; // Host name
$username="smfuser; // Mysql username
$mypassword="smfpassword"; // Mysql password
$db_name="smfdatabase"; // Database name

mysql_connect("$host", "$username", "$mypassword")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");

//$vaild_chars is going to be the array of allowed characters for usernames. I decided to only allow letters and numbers. There are other characters that could be used that wouldn’t cause a problem, but for style reasons I decided to go with only letters and numbers
$valid_chars = "a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9";
$valid_chars = explode(" ",$valid_chars);

//Now we need to loop through each band

for ($i = 0; $i < $userRows; $i++){

if ($row = mysql_fetch_assoc($bands)){

//Extract the band information
extract
($row);
//Create a password for the band
$realPassword = createRandomPassword();
//I choose to echo the bandname and password as part of my debugging and so I can see the function as it works
echo("<br/>$bandName - $realPassword");
$newBand = "";
//For each letter in the band name we are going to look to see if it matches a valid character from $valid_chars. It it does not we are going to get rid of it and truncate the band name
for ($j = 0; $j < strlen($bandName); $j++){

$temp = str_replace($valid_chars, "X", strtolower($band[$j]));
if ($temp == "X")

$newBand = $newBand.$band[$j];

}
//I echo the new name for the same reason I echo the old name and password
echo(" - $newBand");
//We have the new Band name…. now let’s start buliding the info we need to insert in the db…
$memberName = $newBand;
$realName = $newBand; //I set the real name and member name the same. The bands can change it if they want
$emailAddress = $bandEmail;
$websiteUrl = $bandWebsite; //Since I have the bands’ websites might as well enter them
$websiteTitle = $newBand;
$is_activated = 1;
$ID_POST_GROUP = 4;
$password = sha1(strtolower($memberName).$realPassword); //Password must be encrypted

//Make sure their isn’t a member with the same name in the SMF database. We don’t want to accidentally enter anyone twice
$query = "SELECT * FROM smf_members WHERE memberName = ‘$memberName’";
$result = mysql_query($query) or die ("Config Error 2222343242b");
$nrows = mysql_num_rows($result);

//If the member name is found do nothing
if ($nrows>0){}

else {

//If the user isn’t already signed up for the forums, do so and send an email….
$query = "INSERT INTO smf_members(memberName, realName, emailAddress, is_activated, ID_POST_GROUP, passwd, websiteUrl, websiteTitle ) VALUES(’$memberName’, ‘$realName’, ‘$emailAddress’, ‘$is_activated’, ‘$ID_POST_GROUP’, ‘$password’, ‘$websiteUrl’, ‘$websiteTitle’)";

$result = mysql_query($query) or die ("Config Error 2232 ");

//Now we need to send the band an email
$to=$emailAddress;
$subject="Your forum username and password ";

// From
$header="from: Me <me@mysite.com>";

// Your message
$message.="Your login and password are listed below. You can change either at anytime. If you don’t want to participate in our forums, that’s no problem. Just never log in and it will be like nothing ever happened.\r\n";
$message.="Username: $memberName Password: $realPassword \r\n";

// send email
$sentmail = mail($to,$subject,$message,$header);
if ($sentmail)

echo("- YES!");
//This is the last part of our echo. The " -YES!" will only be printed if an email is sent. So a full printout line will look something like this:
//Adam Strife - 4s6vsxag - AdamStrife - YES!

}

}
}

How to Manually Insert a User Into an SMF Forum Using PHP

Posted in SMF (Simple Machine Forum), php by ShortLikeAFox on July 28th, 2008

This specific example is for SMF 1.1.5. I can’t guarantee it will work with any other version.

So you run Simple Machine Forum Software and want to manually enter a user? No problem. I know this problem seems very specific, but the ideas explained here can be adapted to other types of forums and other database driven software packages such as Wordpress. Before we get into exactly how to do this, let’s take a look at how Simple Machine Forums keeps track of users. In the SMF database there is a table called smf_members. The smf_members structure looks like this:

Field Type Null

Key Default Extra
ID_MEMBER mediumint(8) unsigned NO PRI NULL auto_increment
memberName varchar(80) NO MUL    
dateRegistered int(10) unsigned NO MUL 0  
posts mediumint(8) unsigned NO MUL 0  
ID_GROUP smallint(5) unsigned NO MUL 0  
lngfile tinytext NO MUL    
lastLogin int(10) unsigned NO MUL 0  
realName tinytext NO      
instantMessages smallint(5) NO   0  
unreadMessages smallint(5) NO   0  
buddy_list text NO      
pm_ignore_list text NO      
messageLabels text NO      
passwd varchar(64) NO      
emailAddress tinytext NO      
personalText tinytext NO      
gender tinyint(4) unsigned NO   0  
birthdate date NO MUL 0001-01-01  
websiteTitle tinytext NO      
websiteUrl tinytext NO      
location tinytext NO      
ICQ tinytext NO      
AIM varchar(16) NO      
YIM varchar(32) NO      
MSN tinytext NO      
hideEmail tinyint(4) NO   0  
showOnline tinyint(4) NO   1  
timeFormat varchar(80) NO      
signature text NO      
timeOffset float NO   0  
avatar tinytext NO      
pm_email_notify tinyint(4) NO   0  
karmaBad smallint(5) unsigned NO   0  
karmaGood smallint(5) unsigned NO   0  
usertitle tinytext NO      
notifyAnnouncements tinyint(4) NO   1  
notifyOnce tinyint(4) NO   1  
notifySendBody tinyint(4) NO   0  
notifyTypes tinyint(4) NO   2  
memberIP tinytext NO      
memberIP2 tinytext NO      
secretQuestion tinytext NO      
secretAnswer varchar(64) NO      
ID_THEME tinyint(4) unsigned NO   0  
is_activated tinyint(3) unsigned NO   1  
validation_code varchar(10) NO      
ID_MSG_LAST_VISIT int(10) unsigned NO   0  
additionalGroups tinytext NO      
smileySet varchar(48) NO      
ID_POST_GROUP smallint(5) unsigned NO MUL 0  
totalTimeLoggedIn int(10) unsigned NO   0  
passwordSalt varchar(5) NO      

Fields we need to pay attention to:

  • memberName - Self Explanitory.
  • dateRegistered - Isn’t neccessary, but if not filled out the date registered displays as December 31st 1969. The date is saved as an epoch timestamp. Don’t know how to calculate timestamps in your head? No problem. I use the free generator found here.
  • realName - Should be inserted. When I’m not sure I just repeat memberName here.
  • emailAddress - Self Explanitory.
  • is_activated - Must be set to 1 since we are manually activating a member.
  • ID_POST_GROUP - I won’t lie. I’m not sure what this is, but it always seems to be set to 4. So…. I always set it to 4. Not the best way to program, but what can you do?
  • passwd - The password you want to give the new user. It is impossible to figure out how to enter without looking at the SMF documentation. The proper code to encrypt a SMF password for the database looks like this:

$passwd = sha1(strtolower($memberName).$password)

In the above line of code, $password is the user’s actual password.

How to Do It:

//First, connect to the SMF database

$host="hostname"; // Host name
$username="username"; // Mysql username
$mypassword="password"; // Mysql password
$db_name="username"; // Database name

mysql_connect("$host", "$username", "$mypassword")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");

$memberName = "ironMan";
$realName = "Tony Stark";
$emailAddress = "ironMan@ironMan.com";
$is_activated = 1;
$ID_POST_GROUP = 4;

$password = “Tony1234″;

$password = sha1(strtolower($memberName).$password);

$dateRegistered = 1216951200; // 7-25-2008 2 AM

$query = "INSERT INTO smf_members(memberName, realName, emailAddress, is_activated, ID_POST_GROUP, passwd, dateRegistered) VALUES(’$memberName’, ‘$realName’, ‘$emailAddress’, ‘$is_activated’, ‘$ID_POST_GROUP’, ‘$password’, ‘$dateRegistered’)";
$result = mysql_query($query) or die ("SMF Error 101.234 ");

That’s all there is to it!

How to Make Thumbnail Images Using PHP

Posted in functions, php by ShortLikeAFox on July 22nd, 2008

So you want to create a thumbnail from a given image… PHP makes this task easy. I first wrote the function below to deal with images uploaded by users at a site I help administer. Uploaded images to this site can be jpegs, pngs, or gifs, so I had to write a function to deal with all three. This code is originally based off of a function found at webcheatsheet.com

How to Do It:

function createThumbs( $pathToImages, $fname, $pathToThumbs, $thumbWidth )
{

// parse path for the extension

$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( (strtolower($info['extension']) == ‘jpg’) || (strtolower($info['extension']) == ‘jpeg’) )
{

// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );

// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );

// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );

// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );

}

if ( strtolower($info['extension']) == ‘gif’ )
{

// load image and get image size
$img = imagecreatefromgif( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );

// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );

// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );

// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

// save thumbnail into a file
imagegif( $tmp_img, "{$pathToThumbs}{$fname}" );

}

if ( strtolower($info['extension']) == ‘png’ )
{

// load image and get image size
$img = imagecreatefrompng( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );

// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );

// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );

// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

// save thumbnail into a file
imagepng( $tmp_img, "{$pathToThumbs}{$fname}" );

}

}

How This Works

The function createThumbs takes four arguments.

  • $pathToImages -> The path to the folder the image file is in. It might look something like this: /home/content/username/html/list/uploads/
  • $fname -> The filename: pic1.gif, johnny.jpg, etc…
  • $pathToThumbs -> The path to the folder you want the thumbnail image to be in. You DO NOT want this to be the same path as $pathToImages, because the thumbnail image will have the same name as the original image.
  • $thumbWidth -> The width that you want the thumbnail to be in pixels.

An important note that I should make here is that this function has nothing in place, other than the file extension check, to make sure that the image files contain nothing malicious. Since the files createThumbs() works with have already been uploaded it is assumed that the files have been properly scrutinized.

The first thing createThumbs() does is call pathinfo(). pathinfo() breaks the parts of a path into an array. This is useful to us, because we need the file extension to properly create the thumbnail. Next createThumbs() checks to see if we are dealing with a jpeg. If the original file is a jpeg createThumbs creates a new image based on the original image with imagecreatefromjpeg(). The next step is to get the width and height of this image (imagesx(), imagesy()). Using $thumbWidth and the ratio of the original width and height createThumbs() sets the new width and height of the thumbnail. Using these new ratios createThumbs() creates a "blank" image that will be the same width and height of the thumbnail with imagecreatetruecolor(). imagecopyresized() is used to resize the image and save it in the "blank" just created. imagecopyresized() might seem like it takes a lot of parameters, but if you take a look at the documentation it really isn’t that complicated. Now that the thumbnail exists as a true color image all createThumbs needs to do is convert the file into a jpeg. To do this imagejpeg() is called.

That’s how the function works for jpegs. There are minimal differences for .pngs and .gifs.


« Previous entries