04-22-10

Pre-Render Dynamically Resized Images with the PHP-GD Library

If you’ve been frustrated with having to resize images for the sake of continuity or load time and don’t want to develop an entire caching system than this post will be of great value to you.

Today I will discusses the theory and resolve of applying a system to autonomously resize images, with the GD library for PHP, before they get requested by the browser.

This practice presents many benefits to its use.

  1. Save loads of hard drive space
  2. Easy to resize div backgrounds
  3. Faster to call than the use of JavaScript.

Calling the Application With HTML

<img src="image.php?i=image.jpg&s=500" />

Calling the php script is this easy. You can place this tag anywhere on any page and be able to display an image, with exact value constraints, and as many times as you need.

Developing the image.php Application

header("Content-Type: image/jpeg");

header() will make sure that the browser is aware how to handle the applicaton. Here it enables the page to be viewed as a jpeg source.

if (!isset($_GET['s'])) {
    $size = 160;
} else {
    $size = $_GET['s'];
}
$image = $_GET['i'];

list($width, $height) = getimagesize($image);

$ratio = $width/$height;

if ($ratio > 1) {
    $newWidth  = $size;
    $newHeight = $size/$ratio;
} else {
    $newHeight = $size;
    $newWidth  = $size*$ratio;
}
// creates a copy of the loaded image
$create = imagecreatefromjpeg($image);
// creates a blank template to work from
$template = imagecreatetruecolor($newWidth,$newHeight);
// copies the original onto the new template
imagecopyresized($template, $create, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// displays the image
ImageJpeg($template);

Usually I break this larger portion of my post up into smaller pieces so I can reference all the code being used and what it does. But the fundamentals are so well noted and easy to navigate, that I figured even if I left it as so, that you should have no problem implementing this into your own work.

Error catching

If source material is not working properly. Issue the following:

if(!function_exists('imagecreatetruecolor')) {
    exit('Err, function : imagecreatetruecolor does not exist');
}

function_exists() will check the currently active Apache function repository, both internal and user-defined, to see if the listed function matches anything available.

If you’re receiving the error message than the server you’re running this code on does not support the GD library and you must either set it up manually or contact an administrator to do so for you.

Also note that only Jpeg formats are acceptable by this set up. Extending is not a difficult task. I only wanted you to understand the basics and be able to evolve with PHP from my writings.

Summary

Hopefully I’ve left more than enough room for you to adapt this into your own projects. You can add on to this with many of the GD library features documented by the PHP network.

If you develop an extension or even a class, from these tips, please feel free to share by commenting back and letting me know what you’ve done.

04-03-10

Bare-bones way of using Paypal’s Express Checkout NVP API with PHP

I don’t know why Paypal has written its documentation on the subject of, using the Express Checkout name value pair API with PHP, with such an unreadable manner. The classes used with the Paypal API are extremely easy to use. All of this is likely contributing to the confusion about using Express Checkout. But I’m here now, to save your application, and possibly your sanity.

I’m going to explain why the API objects work and what happens when they’re called. There’s a few different ways that you could go about setting up the product and or service details. So I’ll keep this post relative to the main focus points and let you handle the before and after parts on an individual basis.

Referring payment authentication

$paypal = new SetExpressCheckout($totalPrice);

We start out by calling the SetExpressCheckOut() class. It contains the functions you’ll use to redirect the customer to Paypal along with data to differentiate each customer at the completion of the sale. A variable of the total price has to be set to complete the initiation of this class.

$paypal->setNVP("RETURNURL", "http://yourURL.com/confirm.php");
$paypal->setNVP("HDRIMG", "http://yourURL.com/image.jpg");
$paypal->setNVP("EMAIL", "$userEmail"); // customer's email
$paypal->setNVP("AMT", $totalPrice);
$paypal->setNVP("SHIPPINGAMT", "32");
$paypal->setNVP("CUSTOM", "Anything you want to put");
$paypal->setNVP("INVNUM", $uniqueID); // personal invoice number

Before you submit for a transfer to Paypal, know that there are optional values you can send with the setNVP() function, to customize the payment process. All values that can be found, by default, in the etc/NVP/SetExpressCheckout.ini file. I’ve included a list of common practice examples and how to use them in this template.

$paypal->getResponse();

getResponse() sends the user’s browser to Paypal for authentication of credit information. Specifically to a URL that you’ll have to variably set between test mode (sandbox) and live, in the file named etc/NVP/PayPalNVP.ini.

Completing the Sale

$paypal = new GetExpressCheckoutDetails;
$details = $paypal->getResponse();

GetExpressCheckoutDetails() is a class that is most responsible for presenting the custom specifications that you originally sent with SetExpressCheckOut() and SetNVP().

getResponse() will gather all of the available options as an array, labelled $details.

$payment = new DoExpressCheckoutPayment($totalPrice);
$response = $payment->getResponse();

DoExpressCheckoutPayment() will instinctively initiate a communication with Paypal to notify the service that you are ready for the payment to be transferred to your account. The only necessary requisite, of calling this class and it calling to action, is to include the total price in its variable containment field.

getResponse() will gather the resulting responses by DoExpressCheckoutPayment() and include them in an array, labelled $response.

It could be said that you could apply another (final) verification for your customer to submit before the transaction is completed by DoExpressCheckoutPayment(). But not technically necessary.

if ($response['PAYMENTSTATUS'] == 'Completed') {
    //process information
}

One of the returned values in $response will be the PAYMENTSTATUS key. This is a string result that confirms whether or not the money has made been payed to your account. It will definitely be useful when you set up your system to print an invoice on complete, or some insightfully-formatted summary on failure.

Displaying results from getRespnse

echo '<pre>';
print_r($details);
echo '<pre>';
print_r($payment_response);

The above code should print out something similar to the following:

Array
(
    [TOKEN] => EC%2d8DS53628GJ4630109
    [TIMESTAMP] => 2010%2d03%2d31T08%3a25%3a40Z
    [CORRELATIONID] => ce3e460d38d2f
    [ACK] => Success
    [VERSION] => 51%2e0
    [BUILD] => 1247606
    [EMAIL] => test_acct_36654645742_per%40domain%2ecom
    [PAYERID] => W96GXTA5P9BRN
    [PAYERSTATUS] => verified
    [FIRSTNAME] => Test
    [LASTNAME] => User
    [COUNTRYCODE] => US
    [SHIPTONAME] => Test%20User
    [SHIPTOSTREET] => 1%20Main%20St
    [SHIPTOCITY] => San%20Jose
    [SHIPTOSTATE] => CA
    [SHIPTOZIP] => 95131
    [SHIPTOCOUNTRYCODE] => US
    [SHIPTOCOUNTRYNAME] => United%20States
    [ADDRESSSTATUS] => Confirmed
    [CUSTOM] => Anything you want to put
    [INVNUM] => IYUUFEOAS0ME3MTI
)
Array
(
    [TOKEN] => EC%2d8DS53628GJ4630109
    [TIMESTAMP] => 2010%2d03%2d31T08%3a25%3a43Z
    [CORRELATIONID] => b1989df39a0ca
    [ACK] => Success
    [VERSION] => 51%2e0
    [BUILD] => 1247606
    [TRANSACTIONID] => 1PR0061154034542X
    [TRANSACTIONTYPE] => expresscheckout
    [PAYMENTTYPE] => instant
    [ORDERTIME] => 2010%2d03%2d31T08%3a25%3a42Z
    [AMT] => 152%2e00
    [FEEAMT] => 4%2e71
    [TAXAMT] => 0%2e00
    [CURRENCYCODE] => USD
    [PAYMENTSTATUS] => Completed
    [PENDINGREASON] => None
    [REASONCODE] => None
)

Testing

If you don’t have a Paypal developer account, than you should certainly sign up for one to use Paypal’s Sandbox, which makes a mock version of Paypal available for testing. Comes complete with personal and business accounts, each with their own credentials, and unlimited funds.

Summary

Follow the preceding order and you could easily narrow this code down to a a single file, with enough if() constructs, or span it out to many.

You might be left wondering why it seems less daunting than you have expected. That would be because you’re right. These few objects are all that’s needed to handle a shopping cart system on your website.

Maybe Paypal will use this post to refer new users trying to understand how this system works. But I doubt it.

Download now (.zip)