Edmonds Commerce Logo
  • home
    • blog
  • ecommerce
    • product catalogue
    • order processing
    • customer services
    • stock control
    • human resources
    • management information
  • development
    • oscommerce
    • php
    • mysql
    • open source
    • performance tuning
  • design
  • marketing
  • contact us
    • pricing

Edmonds Commerce Blog

Freelance PHP Ecommerce and SEO Developer in the UK

Latest Posts

Zend_Dojo Dijits and Numeric ID’s
Happy New Year from Edmonds Commerce
Easy Security for PHP Scripts
Secure and Insecure Contents in HTTPS

Most Popular Posts

PHP Email Attachment Function Freelance osCommerce UK Ultimate osCommerce Checkout - Fast and Friendly PHP : Dead Easy Excel Export

Archive for the 'php' Category

Next Entries »

PHP Save Images Using cURL

Tuesday, March 18th, 2008

Some hosts disabled the ini setting allow_url_fopen. This also means that the ability to easily grab images by calling imagecreatefromjpeg($img) where $img is a url for an external image does not work.

This is a shame as this technique is pretty easy..

PLAIN TEXT
PHP:
  1. $remote_img = 'http://www.somwhere.com/images/image.jpg';
  2. $img = imagecreatefromjpeg($remote_img);
  3. $path = 'images/';
  4. imagejpeg($img, $path);

However I was tearing my hair out trying to get a product feed integration system to work on a host that has disabled the allow_url_fopen mechanism which meant the above wouldnt work.

Thankfully cURL was still working. So here is the function I made for grabbing and saving an image using cURL instead:

PLAIN TEXT
PHP:
  1. //Alternative Image Saving Using cURL seeing as allow_url_fopen is disabled - bummer
  2. function save_image($img,$fullpath){
  3.     $ch = curl_init ($img);
  4.     curl_setopt($ch, CURLOPT_HEADER, 0);
  5.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  6.     curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
  7.     $rawdata=curl_exec($ch);
  8.     curl_close ($ch);
  9.     if(file_exists($fullpath)){
  10.         unlink($fullpath);
  11.     }
  12.     $fp = fopen($fullpath,'x');
  13.     fwrite($fp, $rawdata);
  14.     fclose($fp);
  15. }

Another Problem Solved :-)

Posted in curl, php | 6 Comments »

Debugging PHP Scripts

Monday, March 17th, 2008

When coding PHP, or more frequently when trying to customise or fix someone elses code, it can sometimes be tricky to figure out exactly what is going wrong.

In this kind of situation, it is often neccessary to go through the flow of the script and view the contents of the various strings and arrays at that stage of the script.

I have written this small function to help in this process:

PLAIN TEXT
PHP:
  1. function dbug($item){
  2.     echo '<hr><h3>Debug Info</h3><pre>' . (var_export($item, true)) . '</pre><hr>'; 
  3. }

This script will take any item and print out detailed information for you in a nicely formatted and easy to read way.

For an example when you might decide to use this functionality, you could check the contents of your $_POST

PLAIN TEXT
PHP:
  1. <?php
  2. /*very top of script */
  3. dbug($_POST);

Posted in debugging, php | No Comments »

MySQL Add Column if Not Exists - PHP Function

Thursday, March 13th, 2008

This is a nice little function which I struggled to find elsewhere on the web.

As discussed elsewhere this is not the kind of thing that should be included in a public facing script, but for administration tools etc its pretty handy:

PLAIN TEXT
PHP:
  1. function add_column_if_not_exist($db, $column, $column_attr = "VARCHAR( 255 ) NULL" ){
  2.     $exists = false;
  3.     $columns = mysql_query("show columns from $db");
  4.     while($c = mysql_fetch_assoc($columns)){
  5.         if($c['Field'] == $column){
  6.             $exists = true
  7.             break;
  8.         }
  9.     }      
  10.     if(!$exists){
  11.         mysql_query("ALTER TABLE `$db` ADD `$column`  $column_attr");
  12.     }
  13. }

This function grabs the column information for the table, then it loops through the info looking for the column. If it finds the column then it acknowledges that it exists and ceases the loop.

After this stage, the function checks to see if exists is true or not, and if it is not true then it adds the column with the attributes defined when calling the function.

The default attributes are for a VARCHAR field up to 255 characters in length and NULL enabled.

Posted in mysql, php | 3 Comments »

PHP and Zip Files

Thursday, March 13th, 2008

There aren't many things you can't do with PHP. One of the things you can do is deal with zip files.

PHP has a built in class for dealing with zip files which allows you to create them, unpack them, add and delete things from them and generally use them within your scripts.

Recently on a spidering / product feed integration job that I have been working on I needed to grab a load of image zip files and unpack them all into a folder called 'images/' (surprisingly enough)

Here is how I did it:

PLAIN TEXT
PHP:
  1. function unpack_zips($directory, $destination = 'images/'){
  2.     $files = dir_list($directory);
  3.     //print_r($files);
  4.     $zips = array();
  5.     foreach($files as $k=>$file){
  6.         if(stristr($file, '.zip')){
  7.             $zips[] = $directory . $file;
  8.         }
  9.     }
  10.     print_r($zips);
  11.     $zip = new ZipArchive;
  12.     foreach($zips as $z){
  13.         if ($zip->open($z) === TRUE) {
  14.             $zip->extractTo($directory . $destination);
  15.             $zip->close();
  16.             //echo "<h3>$z OK</h3>";
  17.         } else {
  18.             echo"<h3 style=\"color: red;\">$z Failed</h3>";
  19.             bottom();
  20.         }   
  21.     }
  22. }
  23.  
  24. function dir_list($directory){
  25.     echo $directory;
  26.     if ($handle = opendir($directory)) {
  27.         while (false !== ($file = readdir($handle))) {
  28.             if($file != '.' && $file != '..'){
  29.                 $return[] = $file;
  30.             }
  31.         }
  32.         closedir($handle);
  33.         return $return;
  34.     }else{   
  35.         return false;
  36.     }
  37. }

There are two functions. The first function is the one that deals with the Zip files. The second function is called by the first function and simply lists all files within a specified directory.

These two functions combined allowed me to find all zip files in a particular folder and then unpack them all into a destination folder.

Related Resources

http://www.phpclasses.org/browse/package/945.html

http://www.phpit.net/article/creating-zip-tar-archives-dynamically-php/

Posted in php, zip | No Comments »

PHP MySQL Query Function with Easy Error Message

Monday, March 3rd, 2008

This is a simple mysql query function that gives you a nice understandable error message if something goes wrong. You probably would not want this kind of error reporting on a live site, but for testing and developing its pretty handy.

What the function does it perform the database query as normal, but if the query fails, the function gives you a full breakdown of the mysql error messsage allowing you to easily see what has gone wrong and fix it.

PLAIN TEXT
PHP:
  1. function db_query($query){
  2.  
  3. $output = mysql_query($query) or die('
  4. <h1 style="color: red">Uh Oh......MySQL Error:</h1>
  5. <h3>Query:</h3>
  6. <pre>' . htmlentities($query) . '</pre>
  7. <h3>MySQL Error:</h3>
  8. ' . mysql_error() . '
  9. <hr /> <hr />');    return $output;
  10.  
  11. }

You would not want to use this query on a live site that is public facing as the error messages will help someone who is trying to break into your system. If you wanted to be able to use this function on a live site and quickly turn the error reporting on and off, we could use a definition like this:

PLAIN TEXT
PHP:
  1. define(MYSQL_ERROR_REPORTING: false;);

Then change the function to be like this:

PLAIN TEXT
PHP:
  1. function db_query($query){
  2. if(MYSQL_ERROR_REPORTING){
  3. $output = mysql_query($query) or die('
  4. <h1 style="color: red">Uh Oh......MySQL Error:</h1>
  5. <h3>Query:</h3>
  6. <pre>' . htmlentities($query) . '</pre>
  7. <h3>MySQL Error:</h3>
  8. ' . mysql_error() . '
  9. <hr /> <hr />');
  10. }else{
  11. $output = mysql_query($query);
  12. }
  13. return $output;
  14. }

Then if you need to see the mysql errors, you can quickly edit the definition to allow mysql error reporting by changing the definition to true.

We would always recommend developing and debugging web sites on the localhost and only making changes to the live site once you are sure that everything works. However sometimes for whatever reason it is hard to replicate an error on the localhost so you really need to see what's happening on the live site.

Alternatively if you are developing an internal system that will only be accessed by your own staff, then some built in error reporting helps you to fix problems that may occur, and also helps your more savvy staff to understand what has gone wrong and give you a good idea so that you can fix it.

Posted in php | No Comments »

Saving a File or Webpage using PHP

Thursday, February 28th, 2008

Sometimes you want your PHP script to grab a text file or other external resource and save it locally.

Here is my simple function for doing just that.

PLAIN TEXT
PHP:
  1. function save_external_resource($resource, $filename){
  2. $data = fopen($resource, 'r');
  3. file_put_contents($filename, $data);
  4. }

You can save any kind of resource from anywhere on the web that you have access to and save it locally.

For large files you may need to edit your php.ini and increase the resource limits and max execution time.

Posted in php | No Comments »

osCommerce Essential Modifications

Thursday, February 21st, 2008

osCommerce is an awesome ecommerce package. It has many critics and this is mainly due to the fact that unlike many modern open source packages it is not really ready to run "out of the box". That is a drawback, however it is not really so much of a drawback when you take into account that anyone that would want to establish an ecommerce presence is going to be very keen to modify the package to make the site look and feel unique.

This is where osCommerce really shines as it is very easy to modify and there is a huge user base with literally thousands of plugin modifications or "contributions" in osCommerce speak which can help you to make your store work in exactly the way you want.

There are some things though that are highly recommened for every osCommerce store though:

1. Search Engine Optimisation

As standard, osCommerce really is not very search engine friendly. Search engine friendliness is the first step towards search engine optimisation. This of course means that there are a fair few things you need to do to your store to make it truly search engine optimised. However, they are worth the hassle (especially if you get us to do it for you) and once you have some SEO modifications implemented, you will be able to start to get indexed and gaining visitors from the search engines without having to pay per click.

2. Speed

There are a few key things that every store should really do to speed up osCommerce. If however you expect your store to have a lot of visitors and/or display a lot of products and categories then you will really benefit from giving the front end of the site a bit of an overhaul in certain areas. The speed improvements possible are really quite dramatic and can make the difference between your visitors sailing through the site straight to the page or product they want or them getting bogged down, bored and finally leaving before they even get where they want to be.

3. Security

osCommerce is pretty secure out of the box. The admin side obviously needs some password protection and can be made more secure if it is felt neccessary. An easy modification is to simply rename the admin folder into something that only you know.

4. User Friendly

The osCommerce ecommerce system is fairly user friendly from the outset. One area that many people prefer to modify though is the checkout procedure which can be a bit long winded for some.

5. Easy Administration

Admin side there is a whole host of things that you can do to make your and your employees' lives easier. For example adding products one by one using the admin tool can be a bit tedious and slow. Easypopulate is an awesome addition to any osCommerce store allowing easy population and editing of the product catalogue using your favourite spreadsheet program. We like Open Office for this task.

Part of the joy of running your own web site is that you are free to edit, change, personalise and improve it to your hearts content. Some things you will add because they make a real difference to your bottom line and some things you will add just because you think its a good idea or will be cool. The great thing with osCommerce is that you can edit it and make it work the way you want.

If you are not confident with PHP or the change you want to make is a bit more complex than you can handle, then we are more than happy to get in there and give you a hand!

Posted in oscommerce, php, programming, search engine optimisation, web design, web development | No Comments »

Who Needs Photoshop? PHP GD Images and Your Online Store

Monday, February 18th, 2008

Many web masters will be familiar with Photoshop by Adobe. This highly featured photo editing and graphics application is incredibly powerful, but also incredibly expensive. If you find that the main thing you do with photoshop is basic product image cropping, resizing, trimming, rotating and watermarking then there is a better way!

If your server uses PHP and has GD functionality enabled, you can use the power of the GD library to automatically do all of these things for you. Furthermore the GD library is faster than using photoshop and as the process actually runs on your server, you do not have to worry about uploading files. Your employees can directly manipulate product photos from your web store administration screens.

Chances are the main thing you will need to do is to take one hi res source image and create one or more resized versions of it to be displayed as thumbnails or product info page images. Your Hi Res images can then be displayed as a pop up or lightbox.

There are many PHP GD thumbnail classes etc out there and you will easily find one by searching the major search engines.

Here are the basic concepts though:

1. Grab an image into memory from an external jpeg file
Before we can do anything we have to get an image into the memory. This then gives us something to work with.

PLAIN TEXT
PHP:
  1. //grab image into memory,  $img = full url to jpeg image
  2. if(!$jpeg = imagecreatefromjpeg($img)){
  3. echo '
  4. <h2 style="color: red">Failed to Grab Image ' . $img . '</h2>
  5. ';
  6. exit;
  7. }

2. Manipulate Image however you want
There are all kinds of things you can do with the image you have loaded using the GD library.

3. Display the Image or Save to Disk
Once you have manipulated the image and have it looking the way you want, you can either serve it up or save it to the disk. Of course you can also do both if you prefer.

PLAIN TEXT
PHP:
  1. //save image
  2. $save_path = 'Your Save Path';
  3. imagejpeg($jpeg,$save_path);
  4.  
  5. //display image
  6. header ("Content-Type: image/jpeg");
  7. imagejpeg($jpeg);
  8.  
  9. //destroy image to free memory
  10. imagedestroy($jpeg);

Related Resources
http://uk3.php.net/gd
http://www.phpclasses.org/browse/package/1365.html
http://www.phpit.net/article/image-manipulation-php-gd-part1/

Posted in gd, php, programming | No Comments »

EAN13 Barcode Check Digit with PHP

Friday, February 15th, 2008

EAN13 is a barcode format. It consists of 12 numbers which you will generally have a range assigned to you. The 13th digit is called the check digit and is formulated by loooking at the other 12 digits. The purpose of the check digit is to ensure that the number is being read correctly as if any of the numbers do not match up, the check digit will not validate.

If you need to create check digits in PHP, here is my handy function:

PLAIN TEXT
PHP:
  1. function ean13_check_digit($digits){
  2. //first change digits to a string so that we can access individual numbers
  3. $digits =(string)$digits;
  4. // 1. Add the values of the digits in the even-numbered positions: 2, 4, 6, etc.
  5. $even_sum = $digits{1} + $digits{3} + $digits{5} + $digits{7} + $digits{9} + $digits{11};
  6. // 2. Multiply this result by 3.
  7. $even_sum_three = $even_sum * 3;
  8. // 3. Add the values of the digits in the odd-numbered positions: 1, 3, 5, etc.
  9. $odd_sum = $digits{0} + $digits{2} + $digits{4} + $digits{6} + $digits{8} + $digits{10};
  10. // 4. Sum the results of steps 2 and 3.
  11. $total_sum = $even_sum_three + $odd_sum;
  12. // 5. The check character is the smallest number which, when added to the result in step 4,  produces a multiple of 10.
  13. $next_ten = (ceil($total_sum/10))*10;
  14. $check_digit = $next_ten - $total_sum;
  15. return $digits . $check_digit;
  16. }

Other Barcode Related Resources:

http://phpclasses.fonant.com/browse/package/3643.html

http://thinkabdul.com/2007/01/04/barcoder-freeware-ean-13-barcode-reader-for-java-j2me-mobiles/

Posted in barcode, php | No Comments »

Building Spiders: Grab Data, Post Forms and Interact with Web Sites Automatically

Thursday, February 14th, 2008

One of the most useful and powerful things you can do with PHP is to create a programme which will simulate a web browser and can grab data, post data to forms and generally interact with other web sites - automatically.

For PHP to be able to work like this it must have the CURL library installed and active. It is the CURL library which actually handles all of the interaction and PHP is my scripting language of choice for interacting with CURL.

A simple CURL function is like this:

PLAIN TEXT
PHP:
  1. function curl($url){
  2.  
  3. $timeout = '300'; //how long before CURL gives up on this page
  4. $go = curl_init();
  5. curl_setopt ($go, CURLOPT_URL, $url);
  6. curl_setopt ($go, CURLOPT_RETURNTRANSFER, 1);
  7. curl_setopt ($go, CURLOPT_FOLLOWLOCATION, 1);
  8. curl_setopt ($go, CURLOPT_TIMEOUT, $timeout);
  9. $spage = curl_exec($go);
  10. curl_close($go);
  11. return $page;
  12.  
  13. }

This function when called and echoed will output the entire html of the $url specified.

For grabbing data from this page to be inserted into a database (for example when spidering a suppliers web site for product information to be inserted into your site) we then use regular expressions to find what we are looking for and then insert that into the database.

so for example if we wanted to grab the product title and we knew that this was wrapped in a h1 tag with the class "product title" we could use this regexp to grab this:

PLAIN TEXT
PHP:
  1. $page = curl($url);
  2.  
  3. $pattern = '%
  4. <h1 class="product_title">(.+?)</h1>
  5. %i';
  6.  
  7. preg_match($pattern,$page,$matches);
  8.  
  9. print_r($matches); //we can see the entire array of matches and choose which we want to insert into the database

We can also Post data to web sites using curl. This allows us to do all kinds of things including grabbing data that is displayed on the submission of post forms. Here is an example Curl Post Function:

PLAIN TEXT
PHP:
  1. function curl_post($url,$post_data){
  2.  
  3. $timeout = '300'; //how long before CURL gives up on this page
  4. $go = curl_init();
  5. curl_setopt ($go, CURLOPT_URL, $url);
  6. curl_setopt ($go, CURLOPT_RETURNTRANSFER, 1);
  7. curl_setopt ($go, CURLOPT_FOLLOWLOCATION, 1);
  8. curl_setopt ($go, CURLOPT_TIMEOUT, $timeout);
  9. //now for the post section
  10. curl_setopt($go, CURLOPT_POST, true);
  11.  
  12. curl_setopt($go, CURLOPT_POSTFIELDS, $post);
  13. $spage = curl_exec($go);
  14. curl_close($go);
  15. return $page;
  16. }

It can be tricky to figure out exactly what data should be in the post string. To help you out though is this incredibly handy addon for firefox: Live Http Headers.

This addon lets you see exactly what is going on between your browser and the web site you are visiting. This can quickly and easily give you the information you need to replicate the same behaviour with your CURL script.

Edmonds Commerce specialise in working with PHP and CURL. If you have any spidering, screen scraping or other application that requires PHP to actively interact with other web sites - get in touch today to see how we can help you benefit from this incredibly powerful technique.

Related Resources

http://www.phpfour.com/blog/2008/01/20/php-http-class/

http://www.phpclasses.org/browse/package/1988.html

http://www.phpit.net/article/using-curl-php/

http://skeymedia.com/intro-to-curl-with-php/

Posted in curl, firefox, php, programming, spidering | 1 Comment »

Next Entries »
  • RSS Feed
  • Categories

    • apache
    • barcode
    • business
    • creloaded
    • curl
    • customer services
    • debugging
    • ecommerce
    • edmondscommerce
    • email
    • excel
    • firefox
    • flash
    • gd
    • graphs
    • hosting
    • icecat
    • internet news
    • javascript
    • link building
    • linux
    • magento
    • management
    • mod_rewrite
    • mysql
    • oscommerce
    • php
    • plesk
    • product catalogue
    • product feed
    • programming
    • regular expressions
    • scraping
    • search engine optimisation
    • security
    • seo
    • spidering
    • ubuntu
    • Uncategorized
    • vps
    • web design
    • web development
    • Windows
    • xampp
    • zip
  • Archives

    • January 2009
    • December 2008
    • November 2008
    • October 2008
    • September 2008
    • August 2008
    • July 2008
    • June 2008
    • May 2008
    • April 2008
    • March 2008
    • February 2008
  • Tags

    addons advanced adverts blackhat blocking css development directories find firefox google hosts file html javascript keywords links msn mysql myths operators oscommerce paid links paid placement performance php ppc reciprocal linking replace screen scraping search engine optimisation security seo serp speed spider spidering tuning user friendly vista web web design web developer
  • Random Posts

    • PHP Random Sleep Function with Flush
    • Debugging PHP Scripts
    • Why VPS is Not for Everyone - Yet
    • Google Checkout Integration Tools
    • Happy Christmas from Edmonds Commerce
    • Building Spiders: Grab Data, Post Forms and Interact with Web Sites Automatically
    • Favourite Firefox Extensions
    • Running Internet Explorer under U