Code
PHP, Tip & Tricks - Friday, May 30, 2008 3:20 - 0 Comments
Reuse Excel business logic with PHPExcel
Reuse Excel business logic with PHPExcel
n many companies, business logic resides in Excel. This business logic is sometimes created by business analysts and sometimes by business users who want to automate parts of their everyday job using Excel. This same Excel-based business logic is often copied into an application (i.e. a website) and is maintained on 2 places: if the Excel logic changes, the application should also be modified. Did you know you can use PHPExcel to take advantage of the Excel-based business logic without having to worry about duplicate business logic?
Here’s a scenario: You are working in a company which sells “dream cars”. For every model, the company has created an Excel spreadsheet which is used to calculate the car’s price based on customer preferences. These spreadsheets are updated frequently in order to reflect the car manufacturer’s pricing schemes.
Your manager asks you to create a small website which accepts some input fields (Does the customer want automatic transmission? What colour should the car be painted? Does the customer want leather seats? Does the customer want sports suspension?). Based on these questions, the car’s price should be calculated. Make sure all prices on the website are in sync with this Excel sheet!
Download example source code
View live example
1. Create the Excel sheet containing business logic
First of all, we’ll create an Excel sheet containing business logic. If you’re lazy, download my example here. To make things easy for yourself when scripting, make sure you add some defined names on each field you want to use as input/output. Of course it’s possible to work with the sheet’s cell references later on, but if you want to be able to change the location of cells within the worksheet later, these defined names are much easier!
2. Download the latest PHPExcel version
You can find PHPExcel on www.phpexcel.net. If you want a stable version, download an official release. The source code tab on CodePlex reveals the latest Subversion source code if you want to use it.
3. Create the web based front-end
Next thing we’ll do is creating a simple webpage containing an HTML form which corresponds woth the parameters you want to pass to the Excel sheet.
4. Let’s do some PHP coding!
Since you came here for the good stuff, here it is! What we’ll do is load the Excel sheet, pass in the parameters and use some calculated values on our resultign page. First things first: include the necessary class references:
/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . ‘./PHPExcel/Classes/’);
/** Class requirements */
require_once(’PHPExcel.php’);
require_once(’PHPExcel/Reader/Excel2007.php’);
PHPExcel is the base library which represents an in-memory spreadsheet. Since we need to interface with an Excel2007 file, we also include the required reader class.
Now load the Excel sheet into a PHPExcel object:
// Load price calculation spreadsheet
$objReader = new PHPExcel_Reader_Excel2007();
$objPHPExcel = $objReader->load(”price_calculation.xlsx”);
All data from the web form is passed in via the $_REQUEST array. Let’s pass these to the Excel sheet. I named all form fields equal to my defined names in Excel which makes coincidence of all array keys and cell names being the same intentional.
// Set active sheet
$objPHPExcel->setActiveSheetIndex(0);
// Assign data
$objPHPExcel->getActiveSheet()->setCellValue(’automaticTransmission’, $_REQUEST[’automaticTransmission’]);
$objPHPExcel->getActiveSheet()->setCellValue(’carColor’, $_REQUEST[’carColor’]);
$objPHPExcel->getActiveSheet()->setCellValue(’leatherSeats’, $_REQUEST[’leatherSeats’]);
$objPHPExcel->getActiveSheet()->setCellValue(’sportsSeats’, $_REQUEST[’sportsSeats’]);
This is actually about it. The only thing left is to fetch the formula’s calculated values and we’re done!
// Perform calculations
$_VIEWDATA[’totalPrice’] = $objPHPExcel->getActiveSheet()->getCell(’totalPrice’)->getCalculatedValue();
$_VIEWDATA[’discount’] = $objPHPExcel->getActiveSheet()->getCell(’discount’)->getCalculatedValue();
$_VIEWDATA[’grandTotal’] = $objPHPExcel->getActiveSheet()->getCell(’grandTotal’)->getCalculatedValue();
You can use these values to print the result on your web page:
Based on your chosen preferences, your car will cost <?php echo number_format($_VIEWDATA[’grandTotal’], 2); ?> EUR.
5. Summary
Embedding business logic in Excel and re-using it in PHP is not that hard. The PHPExcel library helps you simplify development: your application logic and business logic is separated. Business logic can be maintained by a business expert or key user in Excel. As an application developer, you can easily pass data in the sheet and make use of PHPExcel’s calculation engine.
A Guide to Cryptography in PHP
A Guide to Cryptography in PHP
In an ideal world, words like cryptography and security wouldn’t even exist, but the real world is far from perfect, so software developers have to spend a good deal of time building security into applications. Cryptography is just one piece of the security puzzle, along with SSL/TLS, certificates, digital signatures, and so on. This article explains how to use PHP to implement the most common cryptographic algorithms. In addition to describing PHP’s default encryption functions, you’ll see how to use a wide variety of cryptographic libraries and packages.
The code examples in this article use the contents of a short text file, textfile.txt, which contains the following plain-text content:
For every difficult and complicated question there is an answer that is simple, easily understood, and wrong. H.L. MenckenDefault PHP Encryption Functions
PHP ships with three built-in encryption functions: md5(), crypt(), and sha1(). The md5() function prototype is:string md5(string $str [, bool $raw_output ])The function calculates the MD5 hash of a supplied string using the MD5 Message-Digest algorithm. The $str argument represents the string to be encrypted. If you pass FALSE in the $raw_output argument (the default), the function returns the hash as a 32-character hexadecimal number. If you pass TRUE then the function returns a 16-byte raw binary value.
The PHP crypt() function is a one-way encryption function that lets you confirm that an entered password matches a stored encrypted one—without having to decrypt anything. The crypt() function prototype is:
string crypt (string $str [, string $salt ])It returns an encrypted string using the standard Unix DES-based encryption algorithm (or alternative algorithms that may be available on the system). The $str argument is the string to be encrypted and the optional $salt argument is a string on which to base the encryption. If you don’t provide the salt string, PHP will randomly generate one each time you call this function.
The PHP sha1() function calculates the SHA-1 hash of a string. The sha1() function prototype is:
string sha1 (string $str [, bool $raw_output ])
Figure 1. Encrypted File: The encrypted.txt file contains a password encrypted with md5, crypt, and sha1 PHP default functions. The function returns the SHA-1 hash as a string. Again, the $str argument represents the input string. If you set the optional $raw_output argument to TRUE, the function returns the sha1 hash in raw binary format with a length of 20 characters; if you set it to FALSE, it returns a 40-character hexadecimal number.
As an example, the following code shows how to use the PHP default encryption functions to encrypt the contents of texfile.txt file and write the encrypted result in the file encrypted.txt (see Figure 1):
<?php $file = 'textfile.txt'; $initial_contents = file_get_contents($file); if($initial_contents){ $password = 'OctaviaAnghel'; //Calculates the md5 hash $md5_data = md5($password); //This function encrypts data $crypt = crypt($password); //Calculate the sha1 hash $sha1 = sha1($password); $encrypted_file = @fopen('encrypted.txt','w'); $ok_encrypt = @fwrite($encrypted_file,'md5: '. $md5_data."\r\n".'crypt: '.$crypt."\r\n".'sha1: '.$sha1); if($ok_encrypt){ echo 'The encrypted code was succesfully created'. ' in encrypted_file.txt!!!'.' '; } else{ echo ("The write of this file failed!"); } @fclose($encrypted_file); } ?>In addition to the built-in functions, PHP supports encryption via external libraries and packages. Table 1 shows the libraries and packages described in the rest of this article.
Table 1. Cryptography in PHP: The table contains a list of packages and libraries described in this article that work with PHP to perform various types of encryption and decryption.Package/Library Description MCrypt Use MCrypt to encrypt large files or data streams using any of a wide range of encryption functions. You can find more information at http://mcrypt.sourceforge.net/. MHash Use the MHash library to obtain hashes. MHash supports the most popular algorithms and implementations, such as SHA, MD5, and CRC. You can use these algorithms to compute checksums, message digests, and create other signatures. MHash is often used to obtain password hashes for passwords entered into HTML password fields. You can find more information at http://mhash.sourceforge.net/. Crypt_Blowfish Use Crypt_Blowfish for quick two-way encryption both with or without a secret key. You don’t need the MCrypt PHP extension to use Crypt_Blowfish; however, the package can use MCrypt if it’s installed. More details at: http://pear.php.net/package/Crypt_Blowfish. Crypt_RSA Crypt_RSA provides RSA-like key generation, encryption/decryption, signing and signature checking. More details here: http://pear.php.net/package/Crypt_RSA. Crypt_ HMAC This class calculates RFC 2104-compliant hashes. You’ll find complete information at: http://pear.php.net/package/Crypt_HMAC. Crypt_DiffieHellman This package is a PHP5 implementation of the Diffie-Hellman Key Exchange cryptographic protocol. You can find more information at http://pear.php.net/package/Crypt_DiffieHellman. Encrypting Large Data with MCrypt
MCrypt allows developers to encrypt files or data streams using any of a large number of encryption functions without having to be cryptographers. MCrypt supports a wide variety of block algorithms such as Blowfish, DES, TripleDES, SAFER-SK128, TWOFISH, TEA, RC2, 3-WAY, SAFER-SK64, and several “modes of operation.” Normally a block chipper such as MCrypt operates on data blocks of fixed length, often 64 or 128 bits. But because messages may be of any length, and because encrypting the same plaintext using the same key always produces the same output, several solutions have been invented that allow block ciphers to provide confidentiality for messages of arbitrary length. These solutions are known as modes of operation. The modes supported by MCrypt include: CBC, CFB, CTR, ECB, OFB, and NCFB.The companion library for MCrypt is Libmcrypt, which contains the actual encryption functions themselves. Windows users can download it here, while Linux users can get it here.
Author’s Note: If you are using PHP 5.0.0 you will also need libmcrypt Version 2.5.6 or greater. Installing Libmcrypt:
- Download libmcrypt.dll.
- Copy the libmcrypt.dll file to {php_home}/ext and {Windows_home}/System32.
- In php.ini activate the extension=php_mcrypt.dll line by deleting the comment mark (“;”).
- Save the updated php.ini file.
Author’s Note: For Linux, you have to download the libmcrypt-x.x.tar.gz file and follow the included installation instructions. MCrypt can operate with the four cipher modes CBC, OFB, CFB, and ECB. If you are using a libmcrypt-2.4.x version or higher, then MCrypt functions also operate with the nOFB and STREAM cipher modes. Table 2 shows the most commonly-used encryption modes, along with a short description of when to use each.
Table 2. Commonly-Used MCrypt Modes: These cipher modes all operate with MCrypt, and are useful in different situations.Encryption Mode Description MCRYPT_MODE_ECB Use with random data. You can use this mode to encrypt different keys. MCRYPT_MODE_CBC Used for encrypting files. MCRYPT_MODE_CFB Recommended for encrypting byte streams. MCRYPT_MODE_OFB Used specifically in applications where error propagation is not accepted. MCRYPT_MODE_NOFB Comparable with OFB, but more secure. MCRYPT_MODE_STREAM Use when you need stream algorithms such as WAKE or RC4. In addition to the modes listed in Table 2, MCrypt also currently supports these ciphers:
- MCRYPT_3DES
- MCRYPT_ARCFOUR
- MCRYPT_BLOWFISH
- MCRYPT_ENIGMA
- MCRYPT_GOST
- MCRYPT_IDEA (non-free)
- MCRYPT_LOKI97
- MCRYPT_MARS
- MCRYPT_PANAMA
- MCRYPT_RIJNDAEL_128
Author’s Note: Because the list of supported ciphers can change over time, you should periodically check this list of the currently supported ciphers . MCrypt Example
Here’s an example that shows how to encrypt and decrypt the contents of a text file using MCrypt. Again, the example encrypts the contents of textfile.txt and stores the encrypted result in the file encrypted.txt. However, this example also decrypts that file and stores the unencrypted text in the file newfile.txt:// Listing file_encrypt.php <?php $file = 'textfile.txt'; $initial_contents = file_get_contents($file); if($initial_contents){ //This function opens the module of the algorithm and the mode to be used $td = mcrypt_module_open('tripledes', '', 'ecb', ''); //Create an initialization vector (IV) from a random source $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND); //This function initializes all buffers needed for encryption mcrypt_generic_init($td, $initial_contents, $iv); //This function encrypts data $encrypted_data = mcrypt_generic($td, $initial_contents); $encrypted_file = @fopen('encrypted.txt','w'); $ok_encrypt = @fwrite($encrypted_file,$encrypted_data); if($ok_encrypt){ echo 'The encrypted code was succesfully created '. 'in encrypted_file.txt!!!'.'<br />'; } else{ echo ("The write of this file failed!"); } @fclose($encrypted_file); mcrypt_generic_init($td, $initial_contents, $iv); //This function decrypts data $p_t = mdecrypt_generic($td, $encrypted_data); $newfile = @fopen('newfile.txt','w'); $ok_decrypt = @fwrite($newfile,$p_t); if($ok_decrypt){ echo 'The decrypted code was succesfully created '. 'in newfile.txt!!!'.'<br />'; } else{ echo ("The write of this file failed!"); } @fclose($newfile); //This function deinitializes an encryption module mcrypt_generic_deinit($td); //Close the mcrypt module mcrypt_module_close($td); } ?>Building Hashes with MHash
MHash is a free library that lets developers choose from a large number of hash algorithms. These algorithms can be used to compute checksums, message digests, and create other signatures.Installing Libmhash
- Download libmhash.dll.
- Copy the libmhash.dll file to {php_home}/ext and to {Windows_home}/System32.
- In php.ini, activate the extension=php_mhash.dll line by deleting the comment mark (”;”).
- Save the updated php.ini file.
Supported Hashes
The hashes currently supported by MHash are:- MHASH_ADLER32
- MHASH_CRC32
- MHASH_CRC32B
- MHASH_GOST
- MHASH_HAVAL128
- MHASH_HAVAL160
- MHASH_HAVAL192
- MHASH_HAVAL256
- MHASH_MD4
- MHASH_MD5
- MHASH_RIPEMD160
- MHASH_SHA1
- MHASH_SHA256
- MHASH_TIGER
- MHASH_TIGER128
- MHASH_TIGER160
The following example uses MHash to encrypt the contents of texfile.txt and write the encrypted result to encrypted.txt:
<?php $file = 'textfile.txt'; $initial_contents = file_get_contents($file); if($initial_contents){ //mhash() applies a hash function specified by MHASH_MD5 //to the $initial_contents $encrypted = mhash(MHASH_MD5, $initial_contents); // get current Unix timestamp $current = time(); $salt = $current; $password = "Octavia"; //mhash_keygen_s2k generates a key according to the hash function //given and the password provided by the user. $hash = mhash_keygen_s2k(MHASH_GOST, $password, $salt, 20); //concatenate the $salt with the $hash $key = $salt . "|" . bin2hex($hash); $encrypted_file = @fopen('encrypted.txt','w'); $ok_encrypt = @fwrite($encrypted_file, 'mhash: '.bin2hex($encrypted).' mhash_keygen_s2k: '.$key); if($ok_encrypt){ echo 'The encrypted code was succesfully created '. 'in encrypted_file.txt !!!'.'<br />'; } else{ echo ("The write of this file failed!"); } @fclose($encrypted_file); } ?>Secret Keys and Crypt_Blowfish
Secret-key cryptography uses a single key for both encryption and decryption—also called a symmetric key. For example, the commonly-used DES algorithm is a secret key algorithm. The Crypt_Blowfish PEAR package is based on the Blowfish block cipher and supports two-way encryption, either with or without a secret key. The package doesn’t require MCrypt, but Crypt_Blowfish can use MCrypt if it’s installed. The latest released version is 1.0.1 (stable), and you install it like any other PEAR package:> pear install pear_package_nameThis package uses two classes defined in the Blowfish.php file, which you must include in all scripts that use the Crypt_Blowfish package:
require_once 'Crypt/Blowfish.php';Here’s the code for the by-now-familiar encryption example program using Crypt_Blowfish:
<?php require_once 'Crypt/Blowfish.php'; $file = 'textfile.txt'; $initial_contents = file_get_contents($file); if($initial_contents){ $bf = new Crypt_Blowfish('some secret key!'); // Encrypts a string $encrypted = $bf->encrypt($initial_contents); $encrypted_file = @fopen('encrypted.txt','w'); $ok_encrypt = @fwrite($encrypted_file,$encrypted); if($ok_encrypt){ echo 'The encrypted code was succesfully created '. 'in encrypted_file.txt!!!'.'<br />'; } else{ echo ("The write of this file failed!"); } @fclose($encrypted_file); // Decrypts an encrypted string $plaintext = $bf->decrypt($encrypted); $newfile = @fopen('newfile.txt','w'); $ok_decrypt = @fwrite($newfile,$plaintext); if($ok_decrypt){ echo 'The decrypted code was succesfully created '. 'in newfile.txt!!!'.'<br />'; } else{ echo ("The write of this file failed!"); } @fclose($newfile); } ?>Encrypt Data Using an Arbitrary Key Length with the Crypt_RSA PEAR Package
This package supports two-way encryption; it’s based on the RSA block cipher. Crypt_RSA supports encryption and decryption using an arbitrary key length. You can download the latest version (1.0.0, stable) and install it like any other PEAR package:> pear install pear_package_nameCrypt_RSA performs intensive math calculations, for which it uses one of the following extensions:
- PECL big_int extension—(requires a version greater than or equal to 1.0.3)
- PHP GMP extension
- PHP BCMath extension for PHP4/PHP5. Required because libbcmath was bundled with PHP 4.0.4.
Here’s an example of using this package:
<?php require_once 'Crypt/RSA.php'; //Generates the pair keys function generate_key_pair() { global $public_key,$private_key; $key_pair = new Crypt_RSA_KeyPair(32); //Returns public key from the pair $public_key = $key_pair->getPublicKey(); //Returns private key from the pair $private_key = $key_pair->getPrivateKey(); } //Check runtime errors function check_error(&$obj) { if ($obj->isError()){ $error = $obj->getLastError(); switch ($error->getCode()) { case CRYPT_RSA_ERROR_WRONG_TAIL : // nothing to do break; default: // echo error message and exit echo 'error: ', $error->getMessage(); exit; } } } $file = 'textfile.txt'; generate_key_pair(); $plain_text = file_get_contents($file); //get string represenation of the public key $key = Crypt_RSA_Key::fromString($public_key->toString()); $rsa_obj = new Crypt_RSA; check_error($rsa_obj); //Ecnrypts $plain_text by the key $key. $encrypted = $rsa_obj->encrypt($plain_text, $key); $encrypted_file = @fopen('encrypted.txt','w'); $ok_encrypt = fwrite($encrypted_file,$encrypted); if($ok_encrypt){ echo 'The encrypted code was succesfully created '. 'in encrypted_file.txt!!!'.'<br />'; } else{ echo ("The write of this file failed!"); } @fclose($encrypted_file); $enc_text = $encrypted; //Get string represenation of the private key $key2 = Crypt_RSA_Key::fromString($private_key->toString()); check_error($key2); //Check encrypting/decrypting function's behaviour $rsa_obj->setParams(array('dec_key' => $key2)); check_error($rsa_obj); //Decrypts $enc_text $decrypted = $rsa_obj->decrypt($enc_text); $newfile = @fopen('newfile.txt','w'); $ok_decrypt = @fwrite($newfile,$decrypted); if($ok_decrypt){ echo 'The decrypted code was succesfully created '. 'in newfile.txt!!!'.'<br />'; } else{ echo ("The write of this file failed!"); } @fclose($newfile); ?>Generating Hashes with Crypt_HMAC
The Crypt_HMAC PEAR package contains a class you can use to calculate RFC 2104-compliant hashes. Crypt_HMAC is easy to use; you need only provide your secret key, the hash method you want to use, and the plaintext string. Crypt_HMAC supports both MD5 and SHA-1 algorithms. The latest stable released version is 1.0.0. You install it just like any other PEAR package:> pear install pear_package_nameAnd here’s a simple example that creates a hash using Crypt_HMAC:
<?php require_once 'Crypt/HMAC.php'; //Creating a key by repeating the "0x0b" character for 20 times $key = str_repeat(chr(0x0b), 20); //Creating an instance of the Crypt_HMAC class //$crypt = new Crypt_HMAC($key, 'md5'); $crypt = new Crypt_HMAC($key, 'md5'); //Hashing function echo $crypt->hash('Hello')."<br />"; $key = str_repeat(chr(0xaa), 10); $data = str_repeat(chr(0xdd), 50); //Sets key to use with hash $crypt->setKey($key); echo $crypt->hash($data)."\n"; ?>Generating Secret Keys with the Crypt_DiffieHellman PEAR Package
This PEAR package implements the Diffie-Hellman Key Exchange cryptographic protocol in PHP5. You can use the protocol to generate a secret key for two foreign parties, who can then use the generated key for communications even on insecure channels. You can download the latest release, version 0.2.1 (beta) and then install it the same way as any other PEAR package.> pear install pear_package_nameThe following two code examples show two applications for generating a secret key between two parties: subject_1 and subject_2. The first example shows you the simplest way to obtain a secure key based on Diffie Hellman algorithm:
<?php //include Diffie Hellman functions require_once 'Crypt/DiffieHellman.php'; //set the required options for two subjects $subject_1 = array('prime'=>'123', 'generator'=>'7', 'private'=>'3'); $subject_2 = array('prime'=>'123', 'generator'=>'7', 'private'=>'34'); //apply Diffie Hellman algorithm $subject_1_GK = new Crypt_DiffieHellman( $subject_1['prime'], $subject_1['generator'], $subject_1['private']); $subject_2_GK = new Crypt_DiffieHellman( $subject_2['prime'], $subject_2['generator'], $subject_2['private']); //generate keys $subject_1_GK->generateKeys(); $subject_2_GK->generateKeys(); //compute the secret keys $subject_1_SK = $subject_1_GK->computeSecretKey( $subject_2_GK->getPublicKey())->getSharedSecretKey(); $subject_2_SK = $subject_2_GK->computeSecretKey( $subject_1_GK->getPublicKey())->getSharedSecretKey(); //displaying the secret keys echo('Subject_1_SK:'.$subject_1_SK.'<br />'); echo('Subject_2_SK:'.$subject_2_SK); ?>The second example shows you how to generate a secret key using the Diffie Hellman BINARY mode:
<?php //include Diffie Hellman functions require_once 'Crypt/DiffieHellman.php'; //set the required options for two subjects $subject_1 = array('prime' => '9568094558049898340935098349053', 'generator'=>'2', 'private' => '2232370277237628823279273723742872289398723'); $subject_2 = array('prime' => '9568094558049898340935098349053', 'generator'=>'2', 'private' => '0389237288721323987429834389298232433363463'); //apply Diffie Hellman algorithm $subject_1_GK = new Crypt_DiffieHellman( $subject_1['prime'], $subject_1['generator'], $subject_1['private']); $subject_2_GK = new Crypt_DiffieHellman( $subject_2['prime'], $subject_2['generator'], $subject_2['private']); //generate keys $subject_1_GK->generateKeys(); $subject_2_GK->generateKeys(); //compute the secret keys using BINARY mode $subject_1_SK = $subject_1_GK->computeSecretKey( $subject_2_GK->getPublicKey(Crypt_DiffieHellman::BINARY), Crypt_DiffieHellman::BINARY)-> getSharedSecretKey(Crypt_DiffieHellman::BINARY); $subject_2_SK = $subject_2_GK->computeSecretKey( $subject_1_GK->getPublicKey(Crypt_DiffieHellman::BINARY), Crypt_DiffieHellman::BINARY)-> getSharedSecretKey(Crypt_DiffieHellman::BINARY); //display the secret keys echo('subject_1_SK:'.$subject_1_SK.'<br />'); echo('subject_2_SK:'.$subject_2_SK.'<br />'); ?>With the wide variety of cryptographic options you’ve seen here, you should be able to achieve nearly anything you want. Cryptography is a delicate security problem—and as you can see there are many solutions and implementations. The information in this article can help you get started, but beyond that, only experience and hard work with secure systems will help you to choose the cryptographic implementation that represents the perfect compromise between security, speed, and implementation time.
Octavia Andreea Anghel is a senior PHP developer currently working as a primary trainer for programming teams that participate at national and international software-development contests. She consults on developing educational projects at a national level. She is a coauthor of the book “XML technologies—XML in Java” (Albastra, ISBN 978-973-650-210-1), for which she wrote the XML portions. In addition to PHP and XML, she’s interested in software architecture, web services, UML, and high-performance unit tests.8 Best Open Source Shopping Carts
8 Best Open Source Shopping CartsHey Everyone, On Sunday I was contacted by a client and they said the needed a shopping cart up by Monday. Since they needed this cart up so fast I went to the easiest solution I knew, Open Source Shopping Carts. I browsed through tons of shopping carts and put together a list of only the best carts. The list is below. Continue…
Computer Random vs. True Random
Computer Random vs. True Random
See the difference in how random numbers are generated. Thank you Random.org!
Note: I am doing more research comparisons and will have more data and analysis up very soon.
I’ve always been into scripting things using random numbers based on random functions, like PHP’s “rand()” function… but I’ve never compared these types of functions to true random number generators. Then one day, I stumbled upon Random.org, which is a true random number generating service.
Make fancy buttons using CSS sliding doors technique
Make fancy buttons using CSS sliding doors technique
This article will show you how to create fancy buttons using CSS sliding doors technique. It is much better to use this technique than to use image buttons because you can apply the style to any link and at the same time you don’t have to create an image for each button. I posted this one on Morning Break weblog but due to its popularity I decided to publish it here. Continue…
Make fancy buttons using CSS sliding doors technique
Make fancy buttons using CSS sliding doors technique
This article will show you how to create fancy buttons using CSS sliding doors technique. It is much better to use this technique than to use image buttons because you can apply the style to any link and at the same time you don’t have to create an image for each button. I posted this one on Morning Break weblog but due to its popularity I decided to publish it here.
What is sliding doors technique?
The technique is very simple. If we want to have a dynamic-width button, we have to find a way to stretch it horizontally. We will accomplish this if we create two background images that will define the button: one for the left side and one for the right side - like in the example below.
LEFT RIGHT

Smaller, right image will slide on the top of the larger, left image (that why it is called sliding doors). The more right image slides to the left, the narrower button will be and vice versa. The image below shows the technique.

Styling the button
First, let’s take a look at the HTML elements that will simulate button. We have <span> element within the <a> element. Span element contains left, wider image and text. The width of the text will determine the size of the button.
<a class=”button” href=”#”><span>Submit</span></a>
Now let’s take a look at the CSS code. We have a .button class that will be applied to <a> element and .button span class that will be applied to <span> element within <a> element. We also have .button:hover span that will change the font style within <span> element. And that’s all. Simple, eh? The comments in the code below describes each element.
a.button { /* Sliding right image */ background: transparent url(’button_right.png’) no-repeat scroll top right; display: block; float: left; height: 32px; /* CHANGE THIS VALUE ACCORDING TO IMAGE HEIGHT */ margin-right: 6px; padding-right: 20px; /* CHENGE THIS VALUE ACCORDING TO RIGHT IMAGE WIDTH */ /* FONT PROPERTIES */ text-decoration: none; color: #000000; font-family: Arial, Helvetica, sans-serif; font-size:12px; font-weight:bold; } a.button span { /* Background left image */ background: transparent url(’button_left.png’) no-repeat; display: block; line-height: 22px; /* CHANGE THIS VALUE ACCORDING TO BUTTONG HEIGHT */ padding: 7px 0 5px 18px; } a.button:hover span{ text-decoration:underline; }
The result will look like the examples below.

Fetching a Web Page From Your PHP Code
To fetch a web page from your PHP application, you could use curl functions or simply open the page with fopen(). But these have some limitations. Your server needs to have PHP with curl enabled, or the PHP configuration should allow scripts to open an URL with fopen().If that is not the case, you can still fetch a web page by opening a socket connection to the remote host and make HTTP request.
Damn Small Rich Text Editor
This piece of code creates a Rich Text Editor (”RTE”) from an IFRAME element. …Flexigrid for jQuery (beta)
by Paulo P. Marinas
Lightweight but rich data grid with resizable columns and a scrolling data to match the headers, plus an ability to connect to an xml based data source using Ajax to load the content. Continue…How To Detect Internet Explorer Version With PHP
Awhile ago I needed to detect the Internet Explorer version of the visitor from inside of my PHP script. Being lazy I just tried to Google for some existing code, but to my surprise there was none available! Well, I think it’s time to rectify that problem by publishing the code I ended up creating. The ieversion() function looks at the HTTP_USER_AGENT header sent by the browser to determine if the visitor is using Internet Explorer. If not, then the script will return -1. If yes, then the script will extract the version number and return that.
Most Popular Content
- Kopete, The KDE Instant Messenger
- Warning Signs You Can’t Ignore
- Robotic Jellyfish Swim and Fly at Hannover Fair
- The Real Indiana Jones
- Popular Wealth - Free Photoshop Brushes To Download
- 5 Ways To Combat Aging
- Inflatable robots could explore Mars
- Thinking the Way Animals Do
- Top 10 things to do in a blackout
- The most natural drug
- 30 Websites to follow if you’re into Web Development
- Please,I want you to help me with some of your books that will enable me to keep...
- You should also mention Ubercart (http://www.ubercart.org) a very powerful Drupa...
- Hello i am interessted on this script please can you contact me!?...
- Excellent article and oh so true.
Thanks...
- Well done.
If you use Ubuntu for, say, half a hour, you'll never go back to W...
- I own a "Super Battery" chinesse mobile phone, Chivak78, and I can assure you th...
- Thank You Very MUCH!!!
I had a working key, but the last time I reinstalled, it...
- Is this big deal end yet ?...