Sep200825

[PHP] Operators

There are a few different types of operators in PHP and I will cover the most commonly used ones.

Arithmetic Operators

These are list basic maths. The 4 most common are:

Addition

Sum of $a and $b.

<?php
$a = 4;
$b = 3;
echo $a + $b;
?>

Outputs:

7

Subtraction

Difference of $a and $b.

<?php
$a = 4;
$b = 3;
echo $a - $b;
?>

Outputs:

1

Multiplication

Product of $a and $b.

<?php
$a = 4;
$b = 3;
echo $a * $b;
?>

Outputs:

12

Division

Quotient of $a and $b.

<?php
$a = 4;
$b = 3;
echo $a / $b;
?>

Outputs:

1.33333333333

Assignment

An assignment operator assigns a value to a variable name.

<?php
$a = ($b = 10) + 5;
?>

With this $a equals 15 and $b is set to 10.

<?php
$a = 10;
$a += 5;
$b = "hello ";
$b .= "world!";
?>

$a is initially set to 10, then is changed to 15. $b is initially set to ‘hello ‘ then ‘hello world!’ by using the period before the equals (.=).

Comparison

Comparison operators compare 2 values. These are often used in if statements, for example: if $a equals $b then do this.

$a == $b

Returns TRUE if $a is equal to $b.

<?php
$a = 3;
$b = 3;
$c = 2;
var_dump($a == $b); // 3 == 3 is true
var_dump($b == $c); // 3 == 2 is false
var_dump(0 == "s"); // 0 == 0 is true
var_dump("1" == "01"); // 1 == 1 is true
var_dump("1" == "1e0"); // 1 == 1 is true
?>

$a === $b

Returns TRUE if $a is identical to $b.

<?php
$a = 3;
$b = 3;
$c = 2;
var_dump($a === $b); // 3 === 3 is true
var_dump($b === $c); // 3 === 2 is false
var_dump(0 === "s"); // 0 === 0 is false
var_dump("1" === "01"); // 1 === 1 is false
var_dump("1" === "1e0"); // 1 === 1 is false
?>

$a != $b, $a <> $b

Returns TRUE if $a is not equal to $b.

<?php
$a = 3;
$b = 3;
$c = 2;
var_dump($a != $b); // 3 != 3 is false
var_dump($b <> $c); // 3 <> 2 is true
var_dump(0 != "s"); // 0 != 0 is false
var_dump("1" != "01"); // 1 !=1 is false
var_dump("1" <> "1e0"); // 1 <> 1 is false
?>

$a !== $b

Returns TRUE if $a is not identical to $b.

<?php
$a = 3;
$b = 3;
$c = 2;
var_dump($a !== $b); // 3 !== 3 is false
var_dump($b !== $c); // 3 !== 2 is true
var_dump(0 !== "s"); // 0 !== 0 is true
var_dump("1" !== "01"); // 1 !== 1 is true
var_dump("1" !== "1e0"); // 1 !== 1 is true
?>

$a < $b

Returns TRUE if $a is less than $b.

<?php
$a = 3;
$b = 3;
$c = 2;
var_dump($a < $b); // 3 < 3 is false
var_dump($b < $c); // 3 < 2 is false
var_dump(0 < "s"); // 0 < 0 is false
var_dump("1" < "01"); // 1 < 1 is false
var_dump("1" < "1e0"); // 1 < 1 is false
?>

$a > $b

Returns TRUE if $a is greater than $b.

<?php
$a = 3;
$b = 3;
$c = 2;
var_dump($a > $b); // 3 > 3 is true
var_dump($b > $c); // 3 > 2 is true
var_dump(0 > "s"); // 0 > 0 is false
var_dump("1" > "01"); // 1 > 1 is false
var_dump("1" > "1e0"); // 1 > 1 is false
?>

$a <= $b

Returns TRUE if $a is less than or equal to $b.

<?php
$a = 3;
$b = 3;
$c = 2;
var_dump($a <= $b); // 3 <= 3 is true
var_dump($b <= $c); // 3 <= 2 is false
var_dump(0 <= "s"); // 0 <= 0 is true
var_dump("1" <= "01"); // 1 <= 1 is true
var_dump("1" <= "1e0"); // 1 <= 1 is true
?>

$a >= $b

Returns TRUE if $a is greater than or equal to $b.

<?php
$a = 3;
$b = 3;
$c = 2;
var_dump($a >= $b); // 3 >= 3 is true
var_dump($b >= $c); // 3 >= 2 is true
var_dump(0 >= "s"); // 0 >= 0 is true
var_dump("1" >= "01"); // 1 >= 1 is true
var_dump("1" >= "1e0"); // 1 >= 1 is true
?>

Incrementing/Decrementing

Incrementing/Decrementing operators come in 2 forms, pre- and post-increment and decrement.

<?php
echo "Postincrement\n";
$a = 5;
echo "Should be 5: " . $a++ . "\n";
echo "Should be 6: " . $a . "\n";
 
echo "Preincrement\n";
$a = 5;
echo "Should be 6: " . ++$a . "\n";
echo "Should be 6: " . $a . "\n";
 
echo "Postdecrement\n";
$a = 5;
echo "Should be 5: " . $a-- . "\n";
echo "Should be 4: " . $a . "\n";
 
echo "Predecrement\n";
$a = 5;
echo "Should be 4: " . --$a . "\n";
echo "Should be 4: " . $a . "\n";
?>

Outputs:

Postincrement
Should be 5: 5
Should be 6: 6
Preincrement
Should be 6: 6
Should be 6: 6
Postdecrement
Should be 5: 5
Should be 4: 4
Predecrement
Should be 4: 4
Should be 4: 4

Logical

Logical operators return TRUE when variables match given the operator.

$a and $b, $a && $b

<?php
$a = 3;
$b = 3;
$c = 0;
var_dump($a and $b); // Returns true
var_dump($a and $c); // Returns false
var_dump($b && $c); // Returns false
?>

$a or $b, $a || $b

<?php
$a = 3;
$b = 3;
$c = 0;
var_dump($a or $b); // Returns true
var_dump($a or $c); // Returns true
var_dump($b || $c); // Returns true
?>

$a xor $b

<?php
$a = 3;
$b = 3;
$c = 0;
var_dump($a xor $b); // Returns false
var_dump($a xor $c); // Returns true
var_dump($b xor $c); // Returns true
?>

!$a

<?php
$a = 3;
$b = 3;
$c = 0;
var_dump(!$a); // Returns false
var_dump(!$b); // Returns false
var_dump(!$c); // Returns true
?>

String

String operators are the same as some of the assignment operators.

<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
 
$a = "Hello ";
$a .= "World!"; // now $a contains "Hello World!"
?>

The first use the concatenation operator (period) to concatenate both strings together. The second uses the concatenation assignment operator which appends the 2nd argument to the first.

For more information about operators in PHP, visit the PHP.net website which lists more operators and their uses.

Sep200824

[PHP] Introduction

Syntax

When writing PHP code it is best to use the following opening and closing statements:

<?php
?>

On some websites and scripts you may see it written like this:

<?
?>

This is not good practice as not all servers will be set up to allow this shorthand tag.

File extension

Files with PHP in should generally have the file extension .php but depending on the server configuration, other extensions can be used such as .php3, .php4, .php5, .html and more.

Closing statements

All commands and statements in PHP have to be closed before you can make another so that PHP knows where one item ends and the next one starts.

For example, an echo statement should end with a semi-colon:

<?php
echo "hello";
?>

Where as an if statement just needs curly brackets around it:

<?php
if ($item > 4) {
  echo $item.'<br />';
}
?>

Comments

Comments in PHP can be done in a few ways.

Single line comments

Single line comments are comments that only span one row, in our echo statement above we could add a comment after the echo to explain what our node does.

<?php
echo "hello"; // prints out hello on the screen
?>

All the user will see on their screen and the source code (when viewing source from their browser) for this is:

hello

We can also stop code from showing by adding comments before the line of code.

<?php
// echo "hello";
?>

In this case the user won’t see anything as we have commented out the line.

You can also use the following for single line comments:

<?php
# echo "hello";
?>

Multi line comments

Multi line comments are comments that span more than one line by using:

<php
/* This is the first line of our comment
  followed by another line
  and finally a third line */
echo "hello";
?>

You can also use this commenting way to take out blocks of code temporarily, like so:

<?php
/*
if ($item > 4) {
  echo $item.'<br />';
}
*/
?>

Whitespace

Much like HTML, whitespace is not important and is ignored and is purely for the presentation to the developer. The following 2 bits of code both produce the same HTML.

<?php
echo "hello";
echo "hello";
?>

Outputs:

hellohello
<?php
echo "hello";
 
 
 
 
 
echo "hello";
?>

Outputs:

hellohello

Variables

Variables are what you can use to store bits of information to reuse them later on in your script. For example:

<?php
$variable_name = 'value';
echo $variable_name;
?>

Outputs:

value

Variable names have certain restrictions that you must keep to for your script to work as expected.

  • Must start with either a letter or an underscore (_)
  • Must only contain alphanumerics (A-z (upper and lower), 0-9 and underscore (_)
  • Variables are case sensitive. $myVar is different to $myvar

Outputting data

There are 2 basic ways of outputting strings and variables. These are echo and print. For the sake of argument they are exactly the same until you get more advanced in PHP and even then you may not have any use for the extra ability of print.

<?php
print 'hello<br />';
echo 'hello';
?>

Outputs:

hello
hello

I tend to stick to using echo.

Echoing strings and variables

The format of echoing strings and variables does confuse a lot of people and early on it is understandable.

1
2
3
4
5
<?php
echo "This is a statement with \"a quote in\".<br />";
echo 'This is a statement with "a quote in".<br />';
echo 'This is a statement with \'a quote in\'.<br />';
?>

Take note of the format of both of the above lines. Line 2 is enclosed using ” ” whereas line 3 is using ‘ ‘. If you have to use quotation marks within a string then you should either enclose the string with the alternative quotes or escape them with the backwards slash (\).

Echoing strings can have it’s moments too. Example:

<?php
$myVar = 'this is a string';
echo 'Variable: $myVar<br />';
echo 'Variable: '.$myVar.'<br />';
echo "Variable: $myVar<br />";
echo "Variable: ".$myVar."<br />";
?>

Outputs:

Variable: $myVar
Variable: this is a string
Variable: this is a string
Variable: this is a string

From the output we can see the last 3 echo statements are correct and we get the result we expect. But the first one does not. This is because variables can’t be called from within ‘ ‘ quotes but they can be called from within ” ” quotes.

To get around this we close the ‘ ‘ and use a . (dot, full stop, period) to concatenate the variable to the string.

Double quotes are also more helpful if using certain escaped characters.

<?php
echo "this\nis\na\nnew\nline";
echo 'this\nis\na\nnew\nline';
?>

Outputs:

this is a new line
this\nis\na\nnew\nline

Source code:

this
is
a
new
line<br />this\nis\na\nnew\nline

Other enclosed characters include:

  • Newline: \n
  • Carriage return: \r
  • Tab: \t
  • Dollar: \$
  • Double quote: \”

In the case of a backwards slash being used before a character not shown in the list above the backwards slash will be shown as well as the letter succeeding it, example:

<?php
echo "\s";
?>

Outputs:

\s
Sep200824

[Drupal] Get a list of other nodes that are related by taxonomy terms

Building on this snippet from Drupal to get related node items sharing the same taxonomy terms for 4.7, I have made it work for multiple terms.  This snippet is for Drupal 5 and has been tested to work on 5.10.

The code will return a list view of 5 (changeable with $num_nodes) in an unordered list in a random format.

If you want to order the items you can edit the code to order the data in the SQL statement and take out lines 18 and 19.

$num_nodes = 5;
$nid = arg(1);
$terms = taxonomy_node_get_terms($nid);
$items = array();
foreach($terms as $term) {
  $sql = "SELECT DISTINCT n.title, n.nid
    FROM {node} n
    INNER JOIN {term_node} tn ON n.nid = tn.nid
    WHERE n.status =1
    AND tn.tid =".$term-&gt;tid."
    AND n.nid !=".$nid."
    LIMIT $num_nodes";
  $result = db_query(db_rewrite_sql($sql));
  while ($node = db_fetch_object($result)) {
    $items[$node-&gt;nid] = l($node-&gt;title, 'node/'. $node-&gt;nid);
  }
}
srand((float)microtime() * 1000000);
shuffle($items);
return theme('node_list', $items);

For Drupal 6, although I haven’t tried this code, it should be the same except for line 3 which should be like this:

$terms = taxonomy_node_get_terms(node_load($nid));

In Drupal 6, taxonomy_node_get_terms requires the whole node object rather than just the node ID (nid).

Sep200822

[Drupal] Installation

You will need to have set up an IIS or Apache webserver with PHP 5.2 or greater and a Mysql/PostgreSQL database before you can work on Drupal. For more requirements see [Drupal] Overview.

If you do not have a webserver yet but wish to set up your personal computer as a testing environment, please read through and complete the following guide on Setting up your PC as a test environment using Apache, PHP and MySQL.

Download Drupal

For this tutorial we will be using Drupal 6.  You will be able to follow through a fair amount using Drupal 5 but some features may be new.

Go to the Drupal website and click the link on the right hand side to download Drupal 6.  As of writing the latest version is Drupal 6.4.

Once downloaded, right click the file and extract.  This should produce a folder called drupal-6.4.  Rename this folder to drupal. Move this folder to the public web folder of your web server set up (public_html, www, htdocs, httpdocs).

Setup MySQL server

Depending on the setup that you are using, you will have to create a database using whatever tools are available to you.

PHPMyAdmin

The most common bit of software is PHPMyAdmin which is generally accessible through http://www.domain.com/phpmyadmin/.

On the homepage, type the name of the new database in the box and press Create. I will call my database drupal, although on a public website it is best to give the database an obscure name.

Command Line

Open up a command prompt, change directory to the mysql/bin folder. Type the following to login to the MySQL server:

mysql -h localhost -u root -p

Then type your password in.

Then type the following:

create database drupal;

The database is now set up.

Drupal Installation

In your browser navigate to http://localhost/drupal/. This should present you with the Choose language screen of the Drupal installer.

Click Install Drupal in English.

If you get an error like the following:

Then you need to navigate to the drupal/sites/default folder. Copy the file default.settings.php and paste it, rename it to settings.php. Then click try again.

Now the installer will ask you for your database settings.

Fill these in and press Save and continue.

On the next page fill in all of the required information and press Save and continue.

If you are on a local test environment you may get a message about being unable to send an email, ignore this message, it will be OK once put on a proper server.  Just remember that no emails will be sent from the server from this point unless you fix it.

Then click the link to view the site. You will then see the frontpage to your new website.

Sep200822

Set up your PC as a test environment using Apache, PHP and MySQL

You can approach the set up of a test environment in 2 seperate ways. You can manually set up Apache/IIS, PHP and MySQL seperately then configure them to work together or you can use a package such as WAMP (Apache, MySQL, PHP) or XAMPP (Apache, MySQL, PHP, Perl).

There are benefits to manually setting up each bit of software for the purpose of the test server we will just use Xampp.

XAMPP Installation

Go to the XAMPP website and download the correct version for your operating system. Depending on your operating system the download can vary from ~20MB to ~100MB.

Windows users

Download page

Linux users

Download page

Mac OS X users

Download page

Download the Installer package and install using the instructions on the download page.

Once installation has finished, start Apache and MySQL and set up the admin password’s to make it secure using the instructions on the download page.

XAMPP Configuration

First we need to change a few settings in Apache and PHP to make Drupal work a bit better.

Locate the directory you installed XAMPP to and open the apache folder, followed by the conf folder. Open up the httpd.conf file in your favourite plain text editor.

Around line number 118, you should see a line similar to the following:

#LoadModule rewrite_module modules/mod_rewrite.so

If you search for rewrite_module you should be able to find it. 

Change this to:

LoadModule rewrite_module modules/mod_rewrite.so

Make note that we have removed the hash (#) which commented out the line.  We need the rewrite module so that we can have friendly URLS such as http://www.domain.com/this/is/friendly rather than http://www.domain.com/?first=this&second=is&third=friendly.

Save and close the file, then location the php folder within the XAMPP directory. In this directory is a file called php.ini. Open this file in your favourite text editor.

Find the line (should be around line 246):

memory_limit = 32M      ; Maximum amount of memory a script may consume (16MB)

Change this to:

memory_limit = 96M      ; Maximum amount of memory a script may consume (16MB)

Also make sure safe_mode is set to Off.

safe_mode = Off

This should be around line 168.

Save and close the file. 

In the XAMPP control panel click the Stop button next to Apache and wait around 10-15 seconds. Then press Start. Go to http://localhost or http://127.0.01, if it loads up properly then we haven’t broken anything yet.

XAMPP Testing

Back again in the XAMPP installation directory, create a folder called test. In this folder, create a file called index.php. In this file, type the following:

<?php print 'Hello World!!'; ?>

Now direct your browser to http://localhost/test/ or http://127.0.0.1/test/.

You should see the text:

Hello World!!

If so, success.  You have now set up XAMPP correctly to enable you to install most open source PHP software.

Sep200822

[Drupal] Overview

What is Drupal?

Drupal is an open source CMF (Content Management Framework) created by Dries Buytaert.

What is the difference between a CMS and a CMF?

Not a lot but Drupal is refered to as a CMF due to is configurability and customisation that you are able to do through it’s excellent back end and through the use of third party contributed modules as well as modules created by yourself.

How do I get Drupal?

Go to http://drupal.org and download which ever version you want.

Which version do I want?

Version 6 is the latest stable release but isn’t widely used due to a lot of the contributed modules not being available.  But given time this has changed and using 6 on a live site has become more feasible.

What do I need to run Drupal?

You need a web server that supports PHP and either a MySQL or PostgreSQL database.

Drupal supports both IIS and Apache, with Apache being the prefered and most tested web server.

Which version of PHP do I need?

It is recommended for Drupal 5.1 onwards to use PHP 5.2 to make use of certain new PHP functions.

What PHP configuration do I need to run Drupal properly?

To run Drupal with good performance the PHP memory limit should be set to no less than 8MB, with 16MB or more being prefered.  Some contributed modules can need up to 96MB memory limit.

register_globals needs to be off.

session.save_handler set to user.

error_reporting set to E_ALL & ~E_NOTICE.

Additionally session.cache_limiter is recommened to be set to nocache.

If you have any other questions about the requirements of Drupal, please read the System requirements on the Drupal.org website.

Sep200822

Premier4509 show off their new kits

Premier4509 has released images of 4 new body kits.

The first being for the Aston Martin V8 Vantage.

Next we have the Bentley Continental GT.

They have also released images of both the Lamborghini Gallardo and the Lamborghini Murcielago.

Source: Seriouswheels

Sep200822

UK Counties & Countries data files (CSV + MySQL)

The following files are data files that can be used in projects that require a list of UK Counties and/or all of the Countries in the world.

The following files are useful for web developers to use for their select drop downs or a lookup table in a database.

Read the rest of this entry »