Tuesday, 24 April 2012

Autoload your classes in PHP

Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn’t been defined yet.

This is how it works in action. We will create two classes. So create Image.php file and paste this in:

[sourcecode language="php"]
<?php
class Image {
function __construct() {
echo 'Class Image loaded successfully <br />';
}
}
?>
[/sourcecode]

Now create Test.php file and paste this in:

[sourcecode language="php"]
<?php
class Test {

function __construct() {
echo 'Class Test working <br />';
}
}
?>
[/sourcecode]




Basically, we created 2 simple classes with constructors which echo some text out. Now, create a file index.php and paste this in:


[sourcecode language="php"]
<?php
function __autoload($class_name) {
require_once $class_name . '.php';
}

$a = new Test();
$b = new Image();
?>
[/sourcecode]





When you run index.php in browser, everything is working fine (assuming all 3 files are in the same folder). Maybe you don’t see a point, but imagine that you have 10 or more classes and have to write require_once as many times.

I will show you how to properly throw exception if you are using PHP 5.3 and above. Chane your index.php to look like this:
[sourcecode language="php"]
<?php
function __autoload($class_name) {
if(file_exists($class_name . '.php')) {
require_once($class_name . '.php');
} else {
throw new Exception("Unable to load $class_name.");
}
}

try {
$a = new Test();
$b = new Image();
} catch (Exception $e) {
echo $e->getMessage(), "\n";
}
?>
[/sourcecode]





Now, it checks if file exists and throws a proper Exception if it doesn’t.

That’s it. A handy functionality to spare some typing.

Sunday, 18 March 2012

PHP 5.4 is Released — What’s New?

It’s difficult to believe almost three years have elapsed since PHP 5.3.0. The next version should have been PHP 6.0 but unicode problems have delayed development. This latest version provides many of the features planned for version 6.0.

PHP 5.4 is available to download from the php.net website. There’s a PHP 5.3 migration guide if you want to keep your old settings. While it’s stable, you’d be advised to test your sites and applications before installing it on live servers. The PHP team often release a bug-fix version a few weeks after the initial release.

So let’s look at the best new features and improvements…

Short Array Syntax


It’s now possible to use finger-saving JavaScript-like square brackets rather than using the old array(…) construct, e.g.


  1. $array1 = [1, 2, 3];

  2. $array2 = [

  3. "one" => "first",

  4. "two" => "second",

  5. "three" => "third"

  6. ];



Traits


Traits reduce some limitations of single inheritance. In essence, traits are similar to abstract classes and can contain any number of properties and methods. A class can then use any number of traits, e.g.



  1. trait Hello

  2. {

  3. function sayHello() {

  4. return "Hello";

  5. }

  6. }

  7. trait World

  8. {

  9. function sayWorld() {

  10. return "World";

  11. }

  12. }

  13. class MyWorld

  14. {

  15. use Hello, World;

  16. }

  17. $world = new MyWorld();

  18. echo $world->sayHello() . ' ' . $world->sayWorld();



For more information, refer to Using Traits in PHP 5.4 on PHPmaster.com.

Built-in Web Server


PHP 5.4 offers a built-in web server which runs from the Windows, Mac or Linux command line. While it’s not Apache or IIS, it’s fine for simple testing. I suspect many of the better PHP IDEs will implement support shortly.

For more information, refer to PHP 5.4′s New Built-in Web Server.

New Commands


A number of useful commands have been implemented:

  1. hextobin(string $hex): coverts a hex representation of data to binary.

  2. http_response_code(int $code): allows you to set or get the HTTP response code, e.g. http_response_code(404);

  3. header_register_callback(string $function): allows you to register a function which is called when PHP starts sending output.

  4. trait_exists(string $name [,bool $autoload]): determines whether a trait exists and, optionally, whether it should be autoloaded.


Miscellaneous Updates


If that’s not enough…

  • Class members can be accessed on instantiation, e.g. (new MyClass)->MyMethod()

  • <?=$variable?> is always available regardless of how your short_open_tag ini option is set.

  • Binary numbers can be declared, e.g. 0b11110000

  • Session upload progress has been implemented so PHP can track the state of file uploads.

  • Some users are reporting speed increases of up to 25% with a memory reduction of 35%.


Compatibility Issues


Most older PHP code should run without modification but there are a few gotchas to look out for:

You should also note that PHP 5.4.x will be the last edition to support Windows XP and Windows 2003.

PHP 5.4 isn’t quite as radical has 5.3, but there are enough new features to keep developers happy for a while. Let us know if you have any positive or negative experiences with the latest version.

Tuesday, 17 January 2012

Regular Expressions Cheat Sheet

The Regular Expressions cheat sheet is a one-page reference sheet. It is a guide to patterns in regular expressions, and is not specific to any single language.

regular-expressions-cheat-sheet

Wednesday, 14 December 2011

How to Install Apache, PHP, MySQL and PHPMyAdmin in Ubuntu 11.04

If you are a PHP based web developer, you need all the software running and configured properly. Here I am talking about installing them One by One in your Ubuntu Desktop. We are installing all the applications from terminal.

How to Open Terminal:
So, to fire up the terminal follow any of these steps:

  1. If you are running Unity Desktop, click on the Ubuntu Logo at top left corner and type Terminal in the search application bar. Then click on the terminal icon.

  2. If you are running GNome Desktop, click on Applications->Accessories->Terminal

  3. For shortcut, you can also press Ctrl+Alt+T at once, to open the terminal.


How to install Apache:

1. Make sure you have the internet connection. To install apache execute the following command in the terminal:










1


sudo apt-get install apache2




It takes some time to download and install apache. After the setup completes, type http://localhost/ in your browser window to make sure apache is installed and running properly. If you see the page with It Works!, the setup of apache2 completes successfully.

How to Install PHP:

1. To install PHP 5, type following commands in the terminal one by one:










1

2


sudo apt-get install php5

sudo apt-get install libapache2-mod-php5




The first line installs PHP5 in the computer. The second one provides the PHP5 module for the Apache 2 webserver. If second one is not installed, then Apache cannot parse PHP codes in a web page.

2. After installing PHP5 and PHP module for apache, restart the apache with following code:










1


sudo /etc/init.d/apache2 restart




3. While restarting the apache server, if you see a warning as “Could not reliably determine the server’s fully qualified domain name, using 127.0.1.1 for ServerName”, then you can fix this by creating a file with the Server name. To do this type the following command in the terminal:










1


sudo gedit /etc/apache2/conf.d/fqdn




When the text editor opens, type “ServerName localhost” inside the file and click Save. Then close it. Now restart again with the above code and you will see that the warning message has gone.

4. Now, we have successfully installed php and apache web server. However, still we don’t know if PHP is successfully installed. To check this, create a file inside /var/www/ folder named test.php as:










1


sudo gedit /var/www/test.php




and write following code in it










1


<?php   phpinfo();  ?>




Save the file and type this in browser: http://localhost/test.php

If you see the various information about PHP and installed modules there, then we can confirm that Apache is parsing PHP codes. Hence the installation is successful up to this point.

How to Install MySQL:

1. To install MySQL Server in ubuntu, type following code in terminal window:










1


sudo apt-get install mysql-server libapache2-mod-auth-mysql php5-mysql




This will install latest mysql server and other necessary PHP modules for recognizing mysql functions from PHP code. While installing MySQL server, you may require to enter the password for MySQL root user.

How to Install PHPMyAdmin:

1. To Install PHPMyAdmin, type the following codes in the terminal:










1


sudo apt-get install phpmyadmin




While installing PHPMyAdmin, you may require to select the web server. In such case, tick the Apache2 Server and proceed with the installation. You may also require to input MySQL root user password during installation.

Once the installation completes, type this in your browser window to confirm the successful installation of PHPMyAdmin: http://localhost/phpmyadmin/index.php.

Now, you are finished. Your environment is setup and you can enjoy using all these applications. Next, you can install other applications that may be necessary such as Eclipse, GIMP etc.

Tuesday, 29 November 2011

The Right Way to Get a File Extension in PHP

I made a recent search on retrieving file extensions in PHP.

I found out that a lot have been re-inventing the wheel. They have been creating code for functionality that PHP already has. This is one example of re-inventing the wheel

function get_file_extension($file_name)
{
return substr(strrchr($file_name,'.'),1);
}


Another example was this:

function file_extension($filename)
{
return end(explode(".", $filename));
}


PHP already has a function that does the same thing and more.

Welcome, pathinfo.

$file_path = pathinfo('/www/htdocs/your_image.jpg');
echo "$file_path ['dirname']\n";
echo "$file_path ['basename']\n";
echo "$file_path ['extension']\n";
echo "$file_path ['filename']\n"; // only in PHP 5.2+


// Output
/www/htdocs
your_image.jpg
jpg
your_image


A much easier way to use the constants:
[PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME]

PATHINFO_DIRNAME - the directory
PATHINFO_BASENAME - the file name
PATHINFO_EXTENSION - the extension
PATHINFO_FILENAME - the filename without the extension

echo pathinfo('/www/htdocs/your_image.jpg', PATHINFO_EXTENSION);

// Output

jpg