Setting up Xdebug’s remote debug with PHPStorm

Introduction

As promised in a reddit discussion, I thought I would put up an article on setting up xdebug’s remote debugger with PHPStorm. I have had to assist multiple developers in setting it up and I suspectits because there is a lack of ‘how tos’ on this topic on the interwebs.

I have broken this ‘how to’ into two sections, the server setup and the PHPStorm setup. In my case my server happens to be Debian, so if you are using a different flavour of linux, please adjust as necessary. Likewise with PHPStorm version, my screenshots are from version 7, as far as I can remember, they should differ since version 5.

The server settings

Firstly, check that you have Xdebug installed. My method of checking this is to run the following from terminal:

$ php -i | grep "xdebug"

If you get a result, fanstastic, else you will need to install xdebug, this should do it for you:

$ apt-get install php5-xdebug

Now you will need to change you php settings, so open the file /etc/php/conf.d/xdebug.ini (hopefully using vim and we all know that nano is an inferior editor!!!).

It should contain one line which will be the setting for the zend_extension. After that line add the following settings:

debug.remote_host= 192.168.0.10
xdebug.remote_port=9000
xdebug.max_nesting_level=200
xdebug.remote_enable=1
xdebug.idekey="PHPSTORM"
xdebug.remote_autostart = 1

N.B. if you are unsure of what your remote host IP address is, create a php file in which you echo $_SERVER['REOMTE_ADDR']; and run it from the machine you use PHPStorm with. It will output the correct IP address.

Finally, don’t forget to restart you web server (apache in this example):

$ service apache2 restart

The settings in PHPStorm

Go to your PHPStorm settings and make sure that you xdebug port is set to 9000 (if you can not use 9000, I sometimes 9124 else 9125; just make sure it is the same in you ini settings on your server).

PHPStorm Settings Panel

PHPStorm Settings Panel

Save those settings and now go to Run>Edit Configurations… where you will need to add a remote debug instance (see screenshot below)

add remote debug instance

add remote debug instance

You can name this remote debug instance what ever you want, just make sure the IDE key matches what is in xdebug.ini on your server (in this example we used ‘PHPSTORM’).

remote debug instance settings

remote debug instance settings

It likely you won’t have a server setup, if that is the case you can add one by clicking the ‘…’ button. In my project when adding a server, I always need to specify the mappings so you might find you have to do the same.

Finally, once have saved those settings, click on the listen button so that it goes from:

xdebug listening icon

xdebug listening icon

to:

xdebug not listening icon

xdebug not listening icon

If you add a breakpoint now, and load up the page that you want to debug, it should now stop at your breakpoint (I would probably test this with the first line of your index.php to make sure your breakpoint is getting hit!).

Hopefully you will now be a god at debugging the hardest of bugs!

Other hints

If you are not using xdebug, i highly recommend that you turn it off on your server, as if you computer is turned off and you access anything PHP via your webserver it will hang like make as it will be looking for the machine with the IP address specified.

I recommend that you check out xdebug’s profiler if you haven’t already and use it with a tool like kcachegrind else webgrind. Again, I would turn off profiling when not using it as the files it creates on each page load are vast and if you have a small server you may find you run out of storage very quickly!

My Lack of Blogging + Apology!

So, I have written anything to my blog for about 18months, one of my new year’s resolution is to blog more. I have notice that this site is painfully slow, hence new hosting is high on my list of priorities.

I was also tired of the old theme on this blog, so I have set it to WordPress’ new twenty fourteen theme until I rustle up the time to create something custom.

At least my resolution for this year was greater that 1024×768!

Quick Start guide to install LEMP server on Ubuntu 12.04 (Linux + Nginx + MySql + PHP )

I have seen some online guides about this but really was after one specific to Ubuntu 12.04. So here goes:

Step 1 – Installing Nginx

First we need to add the Nginx source

sudo add-apt-repository ppa:nginx/stable

Next, as we always do after adding a source, we need to update

sudo apt-get update

And now we install it

sudo apt-get install nginx

Next, we must start the Nginx service.

sudo /etc/init.d/nginx start

To check if it is successful, try going to http://localhost/ in your browser. If you see a Welcome to Nginx page, it has been successful.

Step 2 – Installing PHP5:

Install PHP and any required extensions

sudo apt-get install php5-cli php5-cgi php5-fpm php5-mcrypt php5-mysql

Edit the default Nginx site config (if you are not familiar with vim, try entering ‘nano’ instead)

sudo vim /etc/nginx/sites-available/default

The changes you will need to make are as follows:
1)

index index.html index.htm;

to

index index.html index.htm index.php;

2)

root /srv/http/nginx;

^this path may be different in your install, it doesn’t matter as we are changing it!
to:

root /var/www;

3) uncomment the following lines

 location ~ \.php$ {
     fastcgi_pass 127.0.0.1:9000;
     fastcgi_index index.php;
     include fastcgi_params;
  }

Now quit vim (‘:wq’) and restart the nginx service.

sudo /etc/init.d/nginx restart

If the folder /var/www/ doesn’t exist, create it

sudo mkdir /var/www/

Step 3 – Install MySQL

And finally,

sudo apt-get install mysql-server

Step 4 – Check it works!

Create a test file

vim /var/www/test.php

Add this line

<?php phpinfo();?>

Save and quit vim (:wq) and go to http://localhost/test.php in your browser.
If you see a page displaying all your PHP settings, then it works!

Ajax breaks in wordpress if back-end uses SSL

So you have a wordpress blog and you (or your client) want the wp-admin to use an SSL certificate, sounds great! However, any AJAX you use in your site has broken. I spent a while googling this issue when it happened to me and found a really easy fix; you need to change the variables in the get_admin_url() function to force the AJAX requestion to use http instead of https. Change it to look like:

get_admin_url(null,'','http');

I hope this helps a lot of people!

Guide to WordPress Settings API

I have decided to explain how to use the WordPress Settings API after having pulled out most my hair whilst googling for a easy to understand explanation.

The reason I wanted to use the WordPress Settings API was because whilst making plugins, I found that my code for my options page was getting a little messy. I had also read, that if you use the Settings API, you don’t ever have to use the update_option() function.

Finally, being a WordPress API, I would like to think that this make my plugins a little more future-proof against wordpress upgrades.

Please note that in this walkthrough I am storing the options into an array.

So this is how it is done:

add_action('admin_menu', 'create_plugin_options_page');
add_action('admin_init', 'register_and_build_plugin_options');

function create_plugin_options_page() {
  //register the menu item
  add_menu_page('Plugins Option', 'Plugin Options', 'administrator', 'option-page-name', 'plugin_options_page');
}

function register_and_build_plugin_options(){
  //register the option value you will be using.
  //N.B. the second parameter must be the same as what you have named the option in your plugin activation
  register_setting('settings_option','plugin_settings', 'validate_option');
  add_settings_section('first_setting_section', 'Settings Section 1','section1_callback','option-page1');
  add_settings_field('setting_text','Text Field: ','text_field','option-page1','first_setting_section');
}

You can have lots of fields in lots of sections. Important things to note when using add_settings_section, add_settings_field, register_setting:

  • The 3rd parameter of register_setting is a callback for validation. In the example above, I have a function (shown later) called validate_option which contains any required validation. This field is optional.
  • The 4th parameter of add_settings_field must correlate to a 1st parameter of add_settings_section
  • The 4th parameter of add_settings_section which should be the same as the 4th parameter of add_settings_field (‘option-page1′) is what you will later use to load this section by using the function do_settings_section();
  • The 3rd parameter of add_settings_section is a callback function. It can be a blank function if you want it to be.
  • The 3rd parameter of add_settings_field is a callback function that contains the input field that you want.
This is the callback function with input field:
function text_field(){
	  $optionValue = get_option('plugin_settings');
    $option = "";
    $option .= "";
    echo $option;
}

You must name the field by the option name so it will save correctly, like I have done above with name=\”plugin_settings[text_field]\”.

Now finally, the function that brings it all together:

function plugin_options_page() {
?>
<div id="theme-options-wrap">
<h2>Plugin Title</h2>
<div><form action="options.php" method="post"> 
<p class="submit"><input class="button-primary" type="submit" name="Submit" value="<?php esc_attr_e('Save Changes'); ?>" /></p>

</form></div>
</div>
<div id="theme-options-wrap">
<h2>Plugin Title</h2>
<div><form action="options.php" method="post"> 
<p class="submit"><input class="button-primary" type="submit" name="Submit" value="<?php esc_attr_e('Save Changes'); ?>" /></p>

</form></div>
</div>
<?php
}

function validate_option($option){
    //put any validation on the options here.
    return $option;
}

function section1_callback(){}

function section2_callback(){
	$html = "An example of some text in the callback function";
	echo $html;
}

function text_field(){
	  $optionValue = get_option('plugin_settings');
    $option = "";
    $option .= "
<input id=\"text_field\" type=\"text\" name=\"plugin_settings[text_field]\" value=\"{$optionValue['text_field']}\"?-->";
    echo $option;
}

function select_field(){
    $options = get_option('plugin_settings');
    $items = array("Red", "Green", "Blue", "Orange", "White", "Violet", "Yellow");
    $html = "
    <select id="select_field" name="plugin_settings[select_field]">";
    foreach($items as $item) {
        $selected = ($options['select_field']==$item) ? 'selected="selected"' : ''; $html .= " <option selected="selected" value="$item">$item</option> ";
    }
    $html .= "</select>";
    echo $html;
}
function checkbox_field(){
    $optionValue = get_option('plugin_settings');
    $option = "";
    $option .= " <input type="\"checkbox\"" name="\"plugin_settings[checkbox_field]\"" value="\&quot;1\&quot;" checked="checked" />";
    echo $option;
}
function radio_field(){
    $optionValue = get_option('plugin_settings');
    $option = "";
    $option .= " <input type="\"radio\"" name="\"plugin_settings[radio_field]\"" value="\"value1\"" checked="checked" />Value1 ";
    $option .= " <input type="\"radio\"" name="\"plugin_settings[radio_field]\"" value="\"value2\"" checked="checked" />Value2 ";
    echo $option;
}

This will allow you to have a settings page that looks like:

Quite a Mouthful! However I hope this really helps for people trying to get to grips with API. Admittedly, I have written this partly as a response to lack of documentation on the API!

If you would like more help, I found this documentation helpful: http://www.presscoders.com/wordpress-settings-api-explained/

Ubuntu 11.04 first impressions

So Ubuntu 11.04 (Nutty Narwhal) is finally here, and so far it seems to be the release with the most amount of change since I started using Ubuntu 6.04.Unity Screenshot

The big change is the use of Unity instead of Gnome as the default environment, which seemed a bit of a shock as Gnome 3 has been released. I would assume that gnome 3 wasn’t ready early enough to develop in this release. However, I have heard you can manually install it and it works fine, except it breaks Unity!

Positive things I have noticed from Unity already have been:

  • I did not have to play with any settings at all for my dual monitors, however with gnome 2 I remember spending ridiculous amounts of editing various conf files else finding the right drivers so that I could use two monitors with different resolutions.
  • A much lighter interface, mainly as most programs seem to integrate with Unity’s Mac-like toolbars, however I get disappointed when some programs don’t follow the theme very well (i.e. Netbeans and Chrome!)
  • My system icons magically tidied themselves during the upgrade, and more seemed to get included into the messaging menu. My old toolbar was starting to become a mess and this is a much welcomed change.

So far my only complaints would be:

  • System settings are in the most ridiculous place! Go to shutdown and you will see them!
  • I prefer the new menu as I no longer need Gnome-Do, however, the Places menu from gnome 2 was so useful for all my shortcuts.

So without any doubt Unity is the big change in this release, however there have been other changes.

I now have libreOffice, I don’t know what was wrong with OpenOffice but I like OpenOffice! Maybe I’m just being closed minded and just need to actually give libreOffice a chance!

Rhythmbox is no longer the default music player, instead Banshee is, and I must admit, that even though Rhythmbox is plain and boring, I like it’s shear simplistic user interface and I don’t think that Banshee feels as polished.

I have noticed a few changes since upgrading from 10.10. Mainly that flash seems to run so much better. I had stopped using Grooveshark as it would crash every couple or songs and I couldn’t full-screen HD videos and vimeo and youtube, however, 11.04 seems to have fixed this.

Also it seems to that multitasking is less painless and application switching happens more fluidly.

Magento Developer’s Paradise 2010

About 2 and a half months ago, my boss told me that I was to go on a business trip to learn more about Magento. I thought: “Ugh, I’m going to lose a weekend and have to do lots of driving, this is going to be dreadful”.
This thought quickly vanished when I was told that the conference was in Majorca!
So after an easy flight there my colleague and I arrived at a large and pleasant hotel. We had been expecting that we would be sharing a room so were pleased when we were given separate room and then all-inclusive bands on our wrists!
When people are all-inclusive, its amazing how generous they are at offering drinks!
So after having located our rooms and dropped off our bags we thought we would go to the bar and starting introducing ourselves as the conference would be starting with an hour or two.
Even though we had a great view of the pool, it was raining so we couldn’t make the most of that, but it was still warm and I didn’t care, the novelty of being in Majorca still hadn’t worn off!
There was a large variety of lectures. The keynote lecture by Yoav Kutner was excellent I found Ashley Schroder’s lecture on plugin development especially interesting as this something I am keen to learn. The other lectures that really grabbed my attention was Phillippe Humeau’s ‘Make Magento Run Like an Antelope’ which had me writing down pages of notes.
From this conference, I feel that the most important thing I have taken away is that to develop with Magento, you must understand Zend first. It is for this reason that I have started to really make the time to understand Zend.
The Conference was a great opportunity for meeting others in the same field of work. I was surprised that we English were a minority, the majority was very definitely German however I met people from the US, Belgium, Sweden, France, Spain and even New Zealand (just to name a few).
Given the chance, I would very happily go again and I congratulate the Magento Team who organised this event.

(Thank you to C3Media.co.uk for allowing me to use their images).

Filtering custom posts by more than one Taxonomy

With WordPress now able to use custom post types, I have asked on forums if anyone new how to filter by more than one taxonomy. I originally tried using

 query_posts('cat=6,5') 

and other similar commands but have no luck.

To resolve this I came up with the following solution:

First I create two custom fields on the page which I named taxonomy1 and taxonomy2.
I then added the following code:

 <?php 
$taxonomy1 = get_post_meta($post->ID, "taxonomy1"); 
$taxonomy2 = get_post_meta($post->ID, "taxonomy2");

//this is an sql query to find all posts containing two taxonomies
$sql_query = "SELECT * FROM (
			SELECT wp_posts.ID FROM `wp_posts` 
				JOIN wp_term_relationships ON wp_posts.ID=wp_term_relationships.object_id
				JOIN wp_terms ON wp_term_relationships.term_taxonomy_id=wp_terms.term_id
					WHERE slug = '".$taxonomy1[0]."' 
			UNION ALL
			SELECT wp_posts.ID FROM `wp_posts` 
				JOIN wp_term_relationships ON wp_posts.ID=wp_term_relationships.object_id
				JOIN wp_terms ON wp_term_relationships.term_taxonomy_id=wp_terms.term_id
					WHERE post_type = 'tiles' AND slug = '".$taxonomy2[0]."'
		) AS results

		GROUP BY results.id HAVING COUNT(*) = 2";
		
	$newresults = $wpdb->get_results($sql_query);			
		
	$ArrayOfIDs = array();
		
	foreach($newresults as $newresult){
		array_push($ArrayOfIDs, $newresult->ID);
	}

	query_posts(array('posts_per_page'=>'900','post_type' => 'tiles','post__in' => $ArrayOfIDs));
?>

The idea behind this code is that the mysql query returns the post IDs of the posts that correspond to the two taxonomy filters and then the foreach loop pushes those into an array of IDs ($ArrayOfIDs) which is then used in the query_post function.

Feedback would be much appreciated on other ways that I could have resolved this issue or also how I could improve this code.

New ventures with Electric Studio

Since July 31st I have left STFC and join Electric Studio. I have taken on the role as a web developer and it seems I shall be leaving any Perl coding behind and focusing mainly on PHP.

I am now working with the wordpress engine and shall be developing plugins. I am also updating the company’s bespoke systems and shall soon be learning about Magento.

I am also having to brush up my jquery skills which seems to be happening very quickly! I am constantly amazed at what is possible with jquery and the amount of libraries available.

Finally, I am now working on a pure linux setup! This makes the working day far more pleasant!

James Irving-Swift's portfolio and random blogging