Archive Page 3



Finding Items in an Array with PHP

The problem: we have an array of items in PHP and we want to find out if a specific item is in the array. In code we can define the array as:

IE we have an array called $fruitBasket which contains 5 strings, each of which is the name of a fruit. We want to find out if there is an Apple in the $fruitBasket - is there an element "Apple" in the array?
We do this with the following code:

PHP:
  1. <?
  2. // create an array of strings called $fruitBasket:
  3. $fruitBasket = array( "Apple", "Orange", "Mango", "Lemon", "Pear" );
  4. // use the in_array() function to check if "Apple" is in the array:
  5. if( in_array("Apple", $fruitBasket) )
  6. {
  7.   echo "Apple is in the array";
  8. }
  9. else
  10. {
  11.   echo "Apple is not in the array";
  12. }
  13. ?>

This code uses the in_array() method to check if the element "Apple" exists in the array $fruitBasket:
in_array("Apple", $fruitBasket)

in_array() takes two parameters here: firstly the object we're looking for, in this case "Apple", and secondly the array which we're looking in, $fruitBasket. It then returns a boolean value: true if "Apple" is in the array, or false if it isn't.

References: php.net manual: in_array() function

If you have a website, consider joining the Money4Banners advertising network. They will pay you £10 + £5 each month for displaying a small advert on three of your pages, regardless of traffic. American webmasters are welcome, and since £10 == $20, you make more!

Rotating Images with PHP

This tutorial will show you how to rotate an image in your PHP scripts. You'll need to have the GD library installed to be able to use some of the functions we use in this guide, though this is included with most PHP installations so there's a chance you'll have it.

Image rotation in PHP is handled by a function called imagerotate(), which takes three parameters (and optionally a fourth, which deals with transparency and is beyond the scope of this guide). The first is the resource identifier which you obtain when you load the original image within your script, the second is the angle which you want to rotate the image and the third parameter is used when the image isn't going to be rectangular, and specifies the colour with which to fill the uncovered areas of the rotated image to make it into a rectangle (since all image formats require rectangular images).

The first thing we need to do is to load the original image into the script, we do this with a command such as imagecreatefromjpeg("file.jpg") for JPEG images, or imagecreatefrompng("file.png") for PNG images.

PHP:
  1. // filename of the original image
  2. $fileName = "cow.jpg";
  3. // load the original image from the file
  4. $original = imagecreatefromjpeg($fileName);

In this example, we're using an image called cow.jpg. The method imagecreatefromjpeg() returns a resource identifier which represents that image within the script - we store this in the variable $original. We need to pass this as the first parameter of the imagerotate() method.

The original image we're using is this particularly nice cow:
a picture of a cow

Now it's time to rotate the image! First we have to decide how many degrees to rotate the image anti-clockwise. Firstly, we'll just roate the image 90 degrees - this means that the resulting image will be rectangular and we won't have to worry about the third parameter.

PHP:
  1. // degrees to rotate the image (counter clockwise)
  2. $angle = 90.0;
  3. // rotate the image by $angle degrees
  4. $rotated = imagerotate($original, $angle, 0);

We pass the original image identifer - $original - and the angle to rotate by - $angle - into the imagerotate() function. In this special case the third parameter isn't important so we'll just enter 0 (which represents the colour black). This returns an identifier for the new rotated image, which we store in the variable $rotated.

Now it's time to display the image. We first tell the browser the content type (IE what sort of image we're going to display) then use the appropriate command to output the data of the image. We're dealing with JPEG images in this example, so the Content-type is "image/jpeg" and the method to output the image is imagejpeg().

PHP:
  1. // print the appropriate header type
  2. // this tells the browser we're displaying a jpeg image
  3. header('Content-type: image/jpeg');
  4. // use the imagejpeg() method to display the rotated image
  5. imagejpeg($rotated);

That code tells the browser we're about to display a jpeg image, then we call imagejpeg($rotated) which turns the image identified by $rotated into the a JPEG image for the browser to display. The output of this code is a sideways cow:
the cow rotated 90 degrees

Now let's consider the case where you want to rotate an image by an angle such as 45 degrees which requires the imagerotate() method to fill around the rotated image to produce a rectangle. We need to pass an integer as the third parameter to tell the method which colour to fill around the image with. We will do this by specifying the hexidecimal representation of the colour, as is used in HTML. For example, FF0000 is red (each digit is between 0-F; the first two digits represent the red component, the next two are green and the last two are blue) - in HTML we would use #FF0000. To tell PHP that we're using hex to represent the numbers rather than decimal, we must prefix this number by 0x (zero x).

PHP:
  1. // degrees to rotate the image (counter clockwise)
  2. $angle = 45.0;
  3. // if the resulting image is not rectangular..
  4. // .. what colour will the uncovered bits be?
  5. $bgColour = 0xFF0000; // red
  6. // rotate the image by $angle degrees
  7. $rotated = imagerotate($original, $angle, $bgColour);

The imagerotate() method works as with a 90 degree rotation except fills the outsides with the colour red. The resulting output is:
the cow rotated 45 degrees

Other hexidecimal colour codes are:

  • 0xFFFFFF - white
  • 0x00FF00 - green
  • 0x000000 - black

That's it! This tutorial should have helped you to rotate images in PHP.

The full PHP code for the 45 degree example is below:

PHP:
  1. <?
  2. // filename of the original image
  3. $fileName = "cow.jpg";
  4.  
  5. // degrees to rotate the image (counter clockwise)
  6. $angle = 45.0;
  7.  
  8. // if the resulting image is not rectangular..
  9. // .. what colour will the uncovered bits be?
  10. $bgColour = 0xFFFFFF; // red
  11.  
  12. // load the original image from the file
  13. $original = imagecreatefromjpeg($fileName);
  14.  
  15. // rotate the image by $angle degrees
  16. $rotated = imagerotate($original, $angle, $bgColour);
  17.  
  18. // print the appropriate header type
  19. // this tells the browser we're displaying a jpeg image
  20. header('Content-type: image/jpeg');
  21. // use the imagejpeg() method to display the rotated image
  22. imagejpeg($rotated);
  23. ?>

Reading a file’s contents with PHP

PHP provides three built-in functions which allow you to easily read the contents of a file on your webserver. This is useful when, for example, another program may write information to the file and you could access that information through your script.

In this example, we're going to use the following example 5 line file, saved as file.txt:

line 1
line 2
line 3
line 4
line 5

In the same directory as file.txt, we're going to work with the PHP file test.php. We'll outline the file reading functions below.

readfile()

readfile() is the least useful of the file functions. As a parameter, it takes a string which specifies the location of the file to read - this can be relative or absolute; since our file is the same directory as the script, we just need to pass the string 'file.txt' as this paramter. We call the function using the code readfile('file.txt') and it prints out the contents of the file straight to the browser:

PHP:
  1. // readfile() writes the contents of the file straight to the browser
  2. echo 'Contents of file.txt using readfile():<br />';
  3. readfile('file.txt');

The disadvantage of readfile() is that it doesn't allow you to manipulate the file contents before displaying it - the next two functions we're going to look at will allow you to do that.

file()

The code file('file.txt') will read the contents of file.txt into an array, which you can then manipulate in your scripts and display yourself. Each line of the file is stored in a seperate element of the array, this means that we can access and manipulate each line of the file seperately using normal array notation.

PHP:
  1. // file() loads the contents of file.txt into an array, $lines
  2. // each line in the file becomes a seperate element of the array.
  3. $lines = file('file.txt');
  4.  
  5. // now loop through the array to print the contents of the file
  6. echo 'Contents of file.txt using file():<br />';
  7. foreach ($lines as $line)
  8. {
  9.     echo htmlspecialchars($line) . '<br />';
  10. }
  11.  
  12. // we can also access each line of the file seperately
  13. echo '3rd line of the file: "' . htmlspecialchars($lines[2]) . '"<br />';

In this example, we've loaded the contents of file.txt into an array called $lines then used foreach to loop through the array and display each line on the user's browser. We then use $lines[2] to access the third line of the file (the element at array index 2, since line 1 is $lines[0]).

You may notice that we've used a function called htmlspecialchars() when displaying the file's contents - this enables that special characters used in HTML, such as > and " are displayed correctly. This illustrates the power of file() over readfile() since readfile() was unable to perform this kind of processing.

get_file_contents()

The last method we will look at is get_file_contents('file.txt') which is similar to file() however rather than returning an array, it returns a string with all the lines of the file. We can manipulate and display this in a similar way as with file():

PHP:
  1. // file_get_contents() reads the file and places the contents in a string
  2. $fileString = file_get_contents('file.txt');
  3. echo 'Contents of file.txt using file_get_contents():<br />';
  4. echo nl2br( htmlspecialchars($fileString) );

Since we have no way of seperating the lines with this method, we've used the nl2br() function which converts line breaks in the string (represented by the special character \n) into the HTML line break <br /> so that the file will display correctly on the visitor's browser.

The full contents of test.php is below:

PHP:
  1. <?php
  2. // file() loads the contents of file.txt into an array, $lines
  3. // each line in the file becomes a seperate element of the array.
  4. $lines = file('file.txt');
  5.  
  6. // now loop through the array to print the contents of the file
  7. echo 'Contents of file.txt using file():<br />';
  8. foreach ($lines as $line)
  9. {
  10.     echo htmlspecialchars($line) . '<br />';
  11. }
  12.  
  13. // we can also access each line of the file seperately
  14. echo '3rd line of the file: "' . htmlspecialchars($lines[2]) . '"<br />';
  15. echo '<br />';
  16.  
  17. // file_get_contents() reads the file and places the contents in a string
  18. $fileString = file_get_contents('file.txt');
  19. echo 'Contents of file.txt using file_get_contents():<br />';
  20. echo nl2br( htmlspecialchars($fileString) );
  21. echo '<br /><br />';
  22.  
  23. // readfile() writes the contents of the file straight to the browser
  24. echo 'Contents of file.txt using readfile():<br />';
  25. readfile('file.txt');
  26. ?>

The output from test.php is:

Contents of file.txt using file():
line 1
line 2
line 3
line 4
line 5
3rd line of the file: "line 3 "

Contents of file.txt using file_get_contents():
line 1
line 2
line 3
line 4
line 5

Contents of file.txt using readfile():
line 1 line 2 line 3 line 4 line 5

Generating Random Numbers in PHP

To create random numbers in PHP, you can use the rand() function call, which takes either zero or, optionally, two parameters determining the minimum and maximum random numbers (inclusive) that you'd like. If you don't specify a maximum then it will default to a value, RAND_MAX, set in the PHP configuration. The function returns an integer, generated "randomly." (Computers can't generate real random numbers, but this tries and is suitable for most purposes.)

You can get the value of RAND_MAX with the function getrandmax(). Then if you desire a random number larger than that, you have to specify the min and max bounds as parameters, eg rand(0, 100000) will return a random number between 0 and 100000 inclusive - so both 0 and 100000 can be returned.

For example:

PHP:
  1. <?php
  2. // random number between 0 and RAND_MAX:
  3. echo rand(); // output: 28688 (for example)
  4. // random number between 37 and 50:
  5. echo rand(37, 50); // output: 44
  6. // find out the value of RAND_MAX:
  7. echo getrandmax(); // output: 32767
  8. // get a larger random number by specifying min and max:
  9. echo rand(0, 1000000); // output: 351990
  10. ?>

The output shown in the comments above is as an example. Since it is generating random numbers, the numbers generated are very likely to be be different every time.

Search Google for Synonyms

It's possible to search Google for synonyms of a word, ie other words that Google thinks has the same meaning. To do this, simply precede the term by a tilde: ~, for example: ~blog will return results for terms such as weblog and blogger as well as those for blog. If you're only interested in the synonyms then you can exclude the original word in the usual way (ie by prefixing a minus sign: - to the term.

So ~blog -blog will return results for weblog, blogger and log but exclude those with the term blog.

This could be useful from a SEO perspective: if you are writing articles which target certain keywords, then it may be useful to target other words which Google associates with those keywords, too.

Hide a hard drive from My Computer

Here's a little privacy hack for users running Windows XP. If you have a hard drive with some kind of mildly sensitive information on it, then you can stop it appearing in My Computer but you'll still be able to access it by installing a utility that Microsoft created, Tweak UI. It allows you to tweak many smaller settings which don't feature in any of the standard Windows preference menus. One such option is to control which drives appear when you open up My Computer and which don't.

Image showing tweak UI dialog

Once you've installed Tweak UI then you have to find and expand the My Computer node in the tree menu on the left, then select Drives. Once you've done that, then you'll be shown drives A to Z (even if they're not actually drives you have - if you later install a hard drive W: then the setting here will determine if it is shown then), each with a check box next to it. Uncheck the drives that you don't want to be shown. To access the drive once you've done that then you'll need to enter the drive letter, eg C: in the address bar of Windows Explorer.
I should point out that this isn't a secure solution - it doesn't do anyone to actually stop anyone accessing information on the drive, however it can be useful to prevent friends and coworkers stumbling upon information you'd rather they don't see.

Although I've mentioned that this is a privacy tip, that's not what I use it for. I have a dual boot set up with another version of Windows, though XP is my main one, and the drive from that other install shows up in My Computer. I use Tweak UI to get rid of the drive letter there, purely for tidyness. I know I could just remove the drive from that version of Windows through the Administrative Tools in the Control Panel, but it is sometimes convenient to have access to it so I use this method. Tweak UI is good at resolving small annoyances such as that.

Until recently, I'd been using Movable Type to operate a music news website, however I'd installed Wordpress 2.0 elsewhere and had it impressed me with how pleasant and satisfying it is to use. What also impressed me was the Wordpress theme, k2, which is by the same designer as the infamous (and now Wordpress default) Kubrick theme. Although still in beta, k2 is clean and functional; it is lovely to look at and to use.

So I'd made up my mind - I was going to "upgrade" that site from Movable Type 3.2 to Wordpress 2.0 (and I intend to do the same with a couple of other websites I had operating on that MT installation. Google led me to a page in the Wordpress documentation: Importing from Movable Type to WordPress, which looked like it would tell me exactly what I needed to know in the form of a step-by-step guide. By reading that, I learnt that the biggest issue when converting is that of trying to preserve the permanent links, since Wordpress and MT each use slightly different structures.

I followed the guide through the exporting from MT stages and had no problems doing so. When I reached the section on importing the entries to Wordpress, I noticed that the guide was significantly out of date. It gives instructions to upload the text file of exported entries which MT generates to your server using FTP, then edit and manually navigate a file called import-mt.php. I'm using Wordpress 2.0 and I couldn't find this file where it was supposed to be. Instead I found that the process had been improved vastly since that guide was written.

Once you save the textfile of exported entries generated by MT, you can login to the Site Admin section of your Wordpress blog and you will find that the rightmost item in the main menu is entitled Import. Clicking on that leads to a screen with various choices of file to import, which includes Movable Type. Then you are asked to choose the text file that MT generated using a file input box. A little CHMODing and some options about the import later, I had the articles in my blog and I was ready to set up the redirection of the old articles to their new Wordpress locations.

For this I used Alex King's solution as suggested by the Wordpress Guide: Movable Type template for individual entries, which provides templates for Movable Type which simply work out what the new URL will be and redirect the user accordingly. This worked almost perfectly for the individual articles, but that's all it handles.

It was then that I noticed the first major problem: I could no longer log into the Wordpress Site Admin section, infact I couldn't recover my password either! When importing articles, Wordpress had prompted me to enter author names or to select a user on this blog to assign the articles to. I wanted them to be assigned to me and there were two seperate selection boxes so I selected my admin username from the drop down menus in both and assumed that all would work ok. What actually happened was that Wordpress then seemed to create another user with the username admin, but no email address or other details assigned. I was locked out!

My solution to that problem was to manually edit the database, using phpMyAdmin provided by my web host, and delete the extra admin. That didn't fix my problem so after a minute or two of panicking I decided to login to the FTP and clear the contents of the Wordpress cache folder: /wp-content/cache and from that point it was working properly. I dont think that this extra user was because of a Wordpress bug but instead by something I'd done (maybe I can blame poor usability for that though).

Another issue I came across was that of setting up redirects for things which Alex King's individual entry templates did not cover. And I failed trying to do this but I have no idea why.

mod_rewrite has always been a strange beast to me. I have, once or twice, managed to tame it but 99% of the time I can't, and this was one of those times - even though I was copying and pasting code from the Wordpress site. I was trying to set up a redirect to point users asking for Movable Type's RSS feeds towards the new Wordpress ones, but for some reason nothing I did would work properly and I always ended up with a Wordpress 404 page. I gave up on this one; it was not a big blog, and the majority of my readers wouldn't know what RSS so it's not of particular importance. There are also other URLs which weren't set up to redirect, for example the MT category and date archives, though again I decided that they weren't important enough to try and fail to establish redirects myself.

The last "problem" that I had was that none of the old comments on my articles were present in Wordpress after converting. There were only four of these though and two were spam so again, not a problem for me.

If you're reading this article thinking "Will I bother converting to Wordpress?" then I'd say, definately, to go for it. Wordpress is an excellent application and will soon make up for any issues encountered with the transition. A lot of the problems that I had were perhaps my fault, but they didn't effect me because the blog in question isn't a very popular or particularly large blog, so I was able to disregard many issues. If that doesn't sound like your blog, then I'd suggest you read the documentation a lot more thoroughly and take your time at every step to ensure that it's done right.

As I mentioned above, I also plan to convert a couple of other MT powered websites to Wordpress so I'll report back if the experience is any better - or worse - the second time around.

Update: 24 Jan 2006 - Moving another blog
I've just managed to move another blog from Movable Type to Wordpress and it went much better than the last time. There was no problem with an extra admin user being added, and I figured out how to redirect the feeds from the Movable Type blog to the Wordpress one using .htaccess. The only problem this time is that the comments still don't appear to have imported correctly - even though the list of imported posts mentioned comments next to the post names.

Here's a simple program to convert temperatures between degrees Celcius, Fahrenheit and Kelvin written in Java. There's no GUI used here - all output is done via the command line.
The forumulae for the conversions were obtained from Temperature conversion forumlas on Wikipedia

File: Converter.java

JAVA:
  1. /**
  2. * Conversion between temperatures in Celcius, Fahrenheit and Kelvin
  3. * Uses conversion forumulas from the wikipedia:
  4. * http://en.wikipedia.org/wiki/Temperature_conversion_formulas
  5. * User: Steven
  6. * Date: 27-Dec-2005
  7. */
  8. public class Converter {
  9.     public Converter()
  10.     {
  11.  
  12.     }
  13.  
  14.     // Method to convert from degrees Celcius to degrees Fahrenheit
  15.     public static float celciusToFahrenheit(float degCelcius)
  16.     {
  17.         float degFahrenheit;
  18.         degFahrenheit = degCelcius * 9/5 + 32;
  19.         return degFahrenheit;
  20.     }
  21.  
  22.     // Method to convert from degrees Fahrenheit to degrees Celcius
  23.     public static float fahrenheitToCelcius(float degFahrenheit)
  24.     {
  25.         float degCelcius;
  26.         degCelcius =  (degFahrenheit - 32) * 5/9;
  27.         return degCelcius;
  28.     }
  29.  
  30.     // Method to convert from degrees Celcius to degrees Kelvin
  31.     public static float celciusToKelvin(float degCelcius)
  32.     {
  33.         float degKelvin;
  34.         degKelvin = degCelcius + 273.15f;
  35.         return degKelvin;
  36.     }
  37.  
  38.     // Method to convert from degrees Kelvin to degrees Celcius
  39.      public static float kelvinToCelcius(float degKelvin)
  40.     {
  41.         float degCelcius;
  42.         degCelcius = degKelvin - 273.15f;
  43.         return degCelcius;
  44.     }
  45.  
  46.     // Main method demonstrating usage of above methods
  47.     public static void main(String[] args)
  48.     {
  49.         System.out.print("100 degrees Celcius in Fahrenheit is: ");
  50.         System.out.println(celciusToFahrenheit(100));
  51.  
  52.         System.out.print("-40 degrees Fahrenheit in Celcius is: ");
  53.         System.out.println(fahrenheitToCelcius(-40));
  54.  
  55.         System.out.print("0 degrees Celcius in Kelvin is: ");
  56.         System.out.println(celciusToKelvin(0));
  57.  
  58.         // to convert from Kelvin to Fahrenheit, combine two methods:
  59.         System.out.print("373.15 degrees Kelvin in Fahrenheit is: ");
  60.         System.out.println(celciusToFahrenheit(kelvinToCelcius(373.15f)));
  61.     }
  62. }




About

You are currently browsing the DiscoMoose weblog archives.

Categories

Categories

house cover
insurance quotes
buy to let
click here