Using vim and xdebug DBGp for debugging Drupal (or any PHP application)

Published Sat, 2006/12/09 - 22:13, Updated Sat, 2006/12/09 - 22:19

The power and simplicity of some tools is often overlooked or underestimated.

One such tool is good old vim (VI iMproved), a text editor for UNIX systems, also available for other platforms.

This articles describes how vim can be used with the xdebug protocol to provide full debugging capabilities for Drupal (or any PHP application for that matter).

Please note that other IDE's for PHP handle debugging, such as Komodo, and even Quanta Plus for KDE (Linux). However, to have this power from a text interface is very cool to say the least.

Credits

The xdebug interface for vim was written by Seung Woo Shin and is available on vim.org. A slightly modified version with a README file is attached to this article.

Requirements

To use this script, you have to get python 2.3 or higher, and xdebug 2.0 on your system (we will cover the installation an configuration of xdebug in a future article).

Installation

Extract the debugger.py and debugger.vim files and place them in your .vim/plugin directory (create it if it does not exist).

Starting the debugger

Start vim, and hit F5. A message will appear waiting for a debug session to start and attach to your vim instance.

Now, browse to the URL of the page causing you grief, and add XDEBUG_SESSION_START to the end of the URL.

For clean URLs use: http://example.com/admin/feature?XDEBUG_SESSION_START=1

Otherwise use: http://example.com?q=admin/feature&XDEBUG_SESSION_START=1

The debugger will start and several windows will appear in vim, with Drupal's index.php showing.

See a screenshot of the start of a debug session.

Setting breakpoints

Using the :e command in vim, open the file you are interested in (e.g. feature.module in this case).

Go to the function/line you suspect, and set a breakpoint using the :Bp command.

See a screenshot of setting a breakpoint.

Debugging at a breakpoint

Hit F4 to continue until the breakpoint is reached.

See a screenshot of reaching the breakpoint.

Once at the breakpoint, you can step through the program, display variables, ...etc.

Use the function keys and commands on screen.

Displaying variables

You can move the cursor to any variable, and hit F12 to see what is in this variable.

See a screenshot of displaying a variable.

Evaluating an expression or variable

Use the ,e command to evaluate an expression or print a variable. This is handy in complex variables such as objects and arrays.

See screenshot of evaluating a variable.

Of course, there are many more uses for this, such as seeing how Drupal handles things, and how elegant its internal architecture is.

Desired functionality

vim xdebug is very powerful yet simple. It is missing only one feature, which is multi-user support. This requires the xdebug proxy to be supported. This allows multiple sessions to connect to the proxy with a different IDE Key (the argument for XDEBUG_SESSION_START).

If someone adds that feature before I do, let me know. I have the setup to test this if needed.

AttachmentSize
vim-xdebug.tar.gz10.77 KB

Hi, I'm new to debugging

Hi,

I'm new to debugging using xdebug, so for checking the value of a variable I think these are the steps:

- Press F5 in vim
- Press F5 in browser
- Press F4 in vim
- Move the cursor to the variable
- Press F12 to check the value of the variable

It works ok, but for me these are too much steps just to avoid the typical var_dump($variable);die; line.

Is there anything am I doing wrong? is there any other quicker way to check the value of a variable?

Javi

POST Method

Great article! I got my Xdebug and Vim working in 5 mins thanks you it :)

I'm wondering, is there anyway to debug callback function that is called by Form API? I tried setting breakpoint in the callback function, but seems like Xdebug lost the connection to the debug session whenever I click on the submit button. Is there anyway to do that using Vim? Or do I really need to use Eclipse or Netbean to do the job?

Hope this thread is not too old just yet :P

Getting more depth out of eval

If you are slightly unimpressed with the 'depth' of the results you get from eval, add/modify this line to your ~/.vim/plugin/debugger.vim:


if !exists('g:debuggerMaxDepth')
let g:debuggerMaxDepth = 10
endif

You may have to play with this value to make it work for you.

variable content is not shown upon pressing F12

If you will have time, please take a look at
http://stackoverflow.com/questions/5467673/xdebug-vim-plugin-doesnt-show-variable-values-php
i've described there everything i did
in short: variable content is not shown upon pressing F12

F5?

I wanted to try debugging using an EC2 instance, so I downloaded the files and went to see the script in vim using vim .vim/plugin/debugger.vim. But when I hit F5, nothing happened. Does this mean that the above does not apply to running vim in a SSH terminal. If that's the case, what else would you advise for interactive debugging via SSH terminal, please?

Works on SSH

Works for me in SSH. I did nothing special to make it so. But I am on Linux (KDE Ubuntu to be specific). Maybe it is putty or whatever you are using for terminal that does not send the right sequence?

Thanks a lot for your

Thanks a lot for your reaction. Yes, I am putty under Vista 64. That must be the reason. Any other method you could advise for debugging in such situation (dev server on the cloud)?

Conditional breakpoint?

Hi, first of all thanks for the post. It is really nice to be able to use xdebug inside vim. As others mentioned before I'm also using the newer version of the plugin written by Sam Ghods (http://www.vim.org/scripts/script.php?script_id=1929). I was having some problems with the original version that I don't have with the this one.

I would like to know if it is possible to use conditional breakpoint. I tried:

:Bp $var == "something"

But this doesn't work.

Thanks, Rodrigo.

hotness

I'm so freaking happy to have found this article. Interactive debugging was the only thing Eclipse had over vim for me--now I'm free from all the ponderous bloated Java GUI interaction forever.

Can't get it to work at all

Not sure if anyone is still looking at these comment posts, but I've got a question if someone is there to help... I'm running ubuntu gutsy 7.10, vim7.1, xdebug v2.0.2-dev (installed as a zend extension using pecl), and I'm using Sam Ghoads' version of the vim debugger that he modified from Seung Woo Shin. For the life of me, no matter what I do, I always get this very unhelpful error message after hitting F5 and then refreshing the browser page to connect:

waiting for a new connection on port 9000 for 5 seconds...
Connection closed, stop debugging
(, AttributeError("DbgProtocol instance has no attribute 'stop'",),
)
File "/usr/share/vim/vim71/plugin/debugger.py", line 1078, in debugger_run
debugger.run()
File "/usr/share/vim/vim71/plugin/debugger.py", line 928, in run
self.protocol.accept()
File "/usr/share/vim/vim71/plugin/debugger.py", line 560, in accept
self.stop()

My problem is that I don't even know where to start in figuring out how to troubleshoot this... I've gone and tried re-installing xdebug in various ways, and I definitely have xdebug working because it shows up in my phpinfo() as well as it works for general profiling of php scripts. I have vim with the +python and +signs flags compiled, so I know python is working (I even tried some python from the command mode inside vim). It seems like a very simple process to set up... I've got the .vim and .py debugger files in my .vim/plugin directory so I haven't the slightest idea where to go for help on this. If anyone on here has any ideas or knows where I should go to find help, I'd be much abliged.

This is a generic error

This is a generic error message as far as I can tell -- it's an unhandled error when no connection occurs.

In general it means no debugging information is reaching the machine you're running vim on. This might be:
- a firewall
- forgetting to add XDEBUG_SESSION_START=1 to the URL
- your settings in php.ini (especially the xdebug.remote_* settings

So, ignore the message, think about why nothing is being sent to your port 9000 or why it is being blocked. Try telnetting locally to port 9000 while vim is listening -- this should result in a different error. If it does, you should try telnetting to your machine from a remote machine ... this will tell you if it's your firewall e.g.

I was having the same

I was having the same problem. Reasons for me:
. was using the old script not the Sam Ghods one http://www.vim.org/scripts/script.php?script_id=1929
. selinux was stopping httpd connecting back to port 9000 - solution - setsebool -P httpd_can_network_connect=1
. I just wasn't refreshing the page fast enough after hitting F5!

Testing using the xdebug debugclient helped make it clear if/when it was the script or something else.

xdebug problems with SELinux

How to know SELinux enabled:
check in apache error_log for the following statemetn
[notice] SELinux policy enabled; httpd running as context user_u:system_r:httpd_t:s0

Xdebug not getting loaded:

Failed loading /usr/lib64/php/modules/xdebug.so: /usr/lib64/php/modules/xdebug.so: cannot open shared object file: Permission denied
Failed loading /usr/lib64/php/modules/xdebug.so: /usr/lib64/php/modules/xdebug.so: cannot open shared object file: Permission denied
Failed loading /usr/lib64/php/modules/xdebug.so: /usr/lib64/php/modules/xdebug.so: cannot open shared object file: Permission denied

Command to be executed

$ getsebool -a|grep httpd_disable_trans
httpd_disable_trans --> off

$ setsebool -P httpd_disable_trans 1

$ getsebool -a|grep httpd_disable_trans
httpd_disable_trans --> on

Now restart the httpd again

Attribute error

Has anyone figured this one out?

I have the same exact line "1078" issue.
Ubuntu 8.0.4, Vim 71, XDEBUG 2.0 installed properly. Using the ?XDEBUG..START=1 just fine.

The connection/debugging works fine with Eclipse and with Spectator -- so everything in the pipe is "clean".

Why isn't this Vim capability working?

Thanks in advance,
id
id@invisionix.com

I have the exact same

I have the exact same problem. So you are not alone.

Try this

May be you forgot XDEBUG_SESSION_START=1 in your url. Try the following formats immediately after pressing F5 in Vim.

For clean URLs use: http://example.com/admin/feature?XDEBUG_SESSION_START=1

Otherwise use: http://example.com?q=admin/feature&XDEBUG_SESSION_START=1

I have gutsy it's working for me

vim compiled from svn (i don't think it matters though)

zeus web server

php-cgi stock gutsy

i'm using the stock vim plugin, haven't tried his modified version.

php.ini (make sure you put this in the right php.ini as shown by phpinfo

[Zend]
# xdebug
zend_extension="/usr/lib/php5/20060613+lfs/xdebug.so"
xdebug.remote_enable = 1
xdebug.remote_port = 9000
xdebug.remote_host = localhost

These three settings were the key for me.

I finally got this working because of the three settings mentioned above.

xdebug.remote_enable = 1
xdebug.remote_port = 9000
xdebug.remote_host = localhost

Running with MAMP 1.9
(PHP 5.2)
(Mysql 5.1.44)

Mac OSX 10.6.4

Mac Vim 7.2

Many thanks!!!

Same problem

I have pretty much the same config as the Gutsy example above. I tried:
http://localhost/php1.php?XDEBUG_SESSION_START=1

I get after 5 seconds:

(, AttributeError("DbgProtocol instance has no attribute 's
File "/usr/share/vim/vim71/plugin/debugger.py", line 1078, in debugger_run
debugger.run()
File "/usr/share/vim/vim71/plugin/debugger.py", line 928, in run
self.protocol.accept()
File "/usr/share/vim/vim71/plugin/debugger.py", line 560, in accept
self.stop()

Running vim, apache and xdebug from distro packages on Hardy, 8.04 Phpinfo shows Xdebug installed and functional.

Jim.

In case this helps anyone

In case this helps anyone else, you will need to add the following line to your php.ini file if it is not already there:

xdebug.remote_handler = dbgp

watch closer

I spend a lot of time with the same error, but I fixed it when I realized that I have been written a wrong url, in my case with "??" like this:

http://localhost/php1.php??XDEBUG_SESSION_START=1

I hope that helps...

Another article

Complimentary Howto Guide

I've written a complimentary article to this one: Easy PHP Debugging in Ubuntu (using Xdebug and Vim). I've linked to this article from mine as it was a fantastic resource (that and the setting up Xdebug article) when getting this working on my machine.

My article aims to be a bit simpler, aiming for people who know about PHP but not necessarily GNU+Linux. :)

Thanks for the fantastic articles!

maybe the URL is wrong

I click the article url and get a error page. So I try to search the title inside the blog, and get the right one:
http://www.apaddedcell.com/easy-php-debugging-ubuntu-using-xdebug-and-vim

Fixed

I added the URL you pointed out. Thanks.
--
2bits -- Drupal consulting

Key bindings not working

Hey i tried running following your guide, but It's not quite working...

I'm running Debian and vim 7.0.122, xdebug is running correctly. And when i try to execute :python debugger_run() it actually starts the debugger but throws an exception if no connection is made.
This is not that big a problem.
The real issue is that all the key bindins in debugger.vim aren't binded... so starting the debugger by pressing F5 does not work and all the other bindings which is highly frustrating.

I guess the problem is really some sort of error in debugger.vim, I just don't know how do fix it :(

Hope you guys can help!

regards Simon

asking for help with installation

I'd like to ask for some help with with installing xdebug. I've installed python and vim (although I think my server might already have had it since I have been using the vi editor?), and then I have the extracted xdebug files (debugger.py and debugger.vim) at /home/myusername/.vim/plugin/, but now what?

I've tried running vim by typing "vim" at the command line, and then hitting , but that doesn't seem to do anything? Am I missing a step here?

luck with vim7?

just thought i'd make a note here that this xdebug script seems to be generally incompatible with vim7. when i rolled back to vim6.4, i got it working generally well and it's been really useful. unfortunately, i don't know anything about the vim scripting language to figure how to update the script for the new vim version.

Hello, My configuration

Hello,

My configuration is:
- Apache/2.0.59 (Win32) PHP/5.2.0 mod_python/3.2.10 Python/2.4.3
- Xdebug: php_xdebug-2.0.0rc3-5.2.1.dll
- Vim7 (gvim)
- WinXP Pro, SP2

I've setup xdebug as confirmed by phpinfo() - I've also commented-out all Zend Optimizer stuff in php.ini.

I'm successfully getting a connection to the debugger client (debugclient-0.9.0) from xdebug.
However, when I hit from within gvim and browse a web-page I get this error in vim:

E499: Empty file name for '%' or '#', only works with ":p:h": silent edit /D%3A%5Cwamp%5Cwww%5Cprojectname%5Cindex.php
File "<string>", line 1, in ?
File "C:\Documents and settings\Nasko/vim_local/vimfiles/plugin/debugger.py", line 983, in debugger_run
    debugger.ui.tracewin.write(sys.ex.info())
File "C:\Documents and settings\Nasko/vim_local/vimfiles/plugin/debugger.py", line 137, in write
    self.buffer.append(str(msg).split('\n'))
vim.error

I've googled for this error message unsuccessfully and I've no idea what to try further.
Perhaps it is related to the strange directory delimiters in the file-path?!

I'll be thankful for any hints on this one.

Cheers,
Nasko

Empty file name error fix

The problem is that the filename is coming across the wire with special characters replaced by the '%xx' notation. The solution is to add the following snippet to the bottom of 'debugger.py':

import urllib
import os
def fixFileName(fileName):
    fileName = urllib.unquote(fileName)
    if os.name=='nt' and fileName[0]=="/":
        fileName = fileName[1:] # strip off initial slash char
    return fileName

then filter the file name in handle_init around line 735 like this:

    file = res.firstChild.getAttribute('fileuri')[7:]
    file = fixFileName(file)
    self.ui.set_srcview(file, 1)

I'm still working through this so there may exist other file names that need to be fixed up as well.

Extra whitespace fix

I've applied your changes also, but though they allow for special characters, they still don't support spaces in filenames.

I've put up a fix here: http://katherina.student.utwente.nl/~matthijs/cgi-bin/blosxom/software/PHP/XDebug.html

another file name to be cleaned up

also add a call to fixFileName to handle_response_stack_get around line 769:

      for s in stacks:
        self.stacks.append( {'file':  fixFileName(s.getAttribute('filename')[7:]), \
                             'line':  int(s.getAttribute('lineno')),  \

This last change was enough

This last change was enough to get it to run. I had some problems stepping over 'required' files in the php source, but stepping into those files seemed to not cause the error. Anyway, it was enough to do the debugging I needed.

Thanks for a great article.

Not true

I am using vim 7.0.35, and it works fine for me (Ubuntu Edgy if anyone cares).
--
2bits -- Drupal consulting

still trouble here

here on gentoo (and when i was on windows) i was having a heck of a time getting it to work, especially with vim7.

right now, i'm getting "error code=5 : Command not available" errors thrown at me. anyone know why that is?

figured it out

finally figured out why i kept seeing this error! i was trying to run the debugger when my breakpoints were in code that was not being called. therefore, it couldn't find anywhere to stop when hitting and yelled with this error.

posting to help anyone who, like me, was confused by this for a while.

tnx - it helped me :)

tnx - it helped me :)

Andrei Zmievski: VIM for PHP Programmers

Andrei Zmievski is a technical Yahoo at Yahoo, Inc.

In his talk VIM for PHP Programmers given in Vancouver's PHP conference, February 2007, he links to this article about using xdebug DBGp to debug PHP applications.

He also repackages the debugging scripts in his vim configuration files.
--
2bits -- Drupal consulting

Thanks

Just wanted to say thanks for writing this extremely helpful article.

I'm using gvim + xdebug on my Mac with MAMP.

DBGP Debugger Proxy

There is actually a proxy implementation available with Komodo. While Komodo is a commercial product, the python debugger implementation is released under the MIT license and is available separately here.

You want the latest Python debugging package ( Komodo 4 Beta 2 ), and I blogged about how to get this set up for PHP debugging here.

Ping me if you have questions - althought he instructions deal mainly with Komodo, the editor-side configuration is pretty simple.

I am aware of it

Hello Jeff

Thanks for your comment.

I am aware of the xdebug proxy, and have it configured on my development server from when I was evaluating Komodo 3.5 a few months ago. I even wrote a shell wrapper around it, and created an /etc/init.d script for it to automatically start.

At the time remote debugging did not work as it should. The main problem is the mapping of local and remote files, and hence setting a breakpoint in a file does not cause Komodo to stop there.

A few weeks ago, I read on the mailing list archive that remote debugging is now working and is in the source tree. So, I downloaded the Komodo 4.0 beta, and gave it a try. I still could not get it to work. I could have spend more time on it, but time is a rare commodity these days for me.

For vim, it works perfectly since they are both on the same machine, and I do most of my editing in vim anyways.

The issue with the proxy not working with vim has to do with the debugger.py script itself. I tried changing the port to 9001 in the .vim and several places in the .py file, but it does not work. If the proxy is active, vim will close the connection as soon as the browser starts a debugging session.

If someone is using vim with xdebug and can look at that, let me know, and I will amend the article above and publish the changes.
--
2bits -- Drupal consulting

Uri Mapping in 4.0

Komodo 4.0 has a new feature called 'Mapped Uris' that allows you to map a url with a local or remote directory. This is what was described on the Beta list, but it only works once you set up these mappings in 'Preferences / Mapped URIs'. Once you have that set up Komodo is then able to map breakpoints set in a file open in the editor with the file being used by the debugger engine via Apache.

In Komodo 3.5 there was a setting in 'Preferences / Debugging' called 'Try to find files on the local filesystem when remote debugging' - this should work in cases where you are running Apache localhost.

As for the Vim implementation, if you can get ahold of the developer or are interested in fixing the proxy issues yourself let me know and I can get you in contact with Shane Caraveo and/or Derick Rethans, the authors of the DBGP protocol.

Tried it

I tried that, before, but it did not work.

Just to confirm, I downloaded the latest Komodo beta and gave it a try again.

For remote files, I used what is in the window title, for example:

Remote URI : file:///home/blah/drupal

Local path : /home/blah/drupal

So, I set this in Komodo, and use XDEBUG_SESSION_START, Komodo breaks at the beginning of index.php. I then open feature.module, which I know where the current page load will go, and set a break point.

I know that the mapping works, because now I don't get a lock (read only file from the server), but the same file I opened. I see the break point set, but Komodo just whizzes over it and does not stop.

What is even more puzzling is that the breakpoints are ignored even in the index.php. If I set a breakpoint a few lines after the start, Komodo does not break at that point either.

It makes no difference whether I set this mapping in the global (Preferences) or in the project itself.
--
2bits -- Drupal consulting

use an http url

For the 'Remote URI' field, you should use the HTTP address. So for example, if my Apache docroot is /var/www, I would do this:

Remote URI: http://localhost

Local Path: /var/www

Nope

No go.

This one makes the lock icon to come back (meaning that the file is not successfully mapped).

I had better luck mapping it as in the previous reply.

Quanta Plus (KDE's web development IDE) maps it correctly, but also does not support a proxy.

Not sure what else to try.

If you are interested to pursue this further, email me at kb at this site.
--
2bits -- Drupal consulting

Still an Issue

Has anyone figured out this issue here?

(, , )
File "/Applications/MacVim.app/Contents/Resources/vim/runtime/plugin/debugger.py", line 1078, in debugger_run
debugger.run()
File "/Applications/MacVim.app/Contents/Resources/vim/runtime/plugin/debugger.py", line 928, in run
self.protocol.accept()
File "/Applications/MacVim.app/Contents/Resources/vim/runtime/plugin/debugger.py", line 560, in accept
self.stop()

I noticed a few people here who are having that issue. Any help is much appreciated!!

Re: Still an Issue

I hope this helps someone out there ... I figured out the issue. This was probably pretty obvious to everyone else, but in case there is a lonely googler out there like me searching for this answer here it is. Apparently that error is generated when the connection to the remote session has failed (it's not very descriptive, obviously).

Paul

Is your Drupal or WordPress site slow?
Is it suffering from server resources shortages?
Is it experiencing outages?
Contact us for Drupal and WordPress Performance Optimization and Tuning Consulting