Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

2014-08-16

Fatal error: Maximum execution time of 30 seconds exceeded & timeout problems (PHP debugging)


The error message above in the title line indicates that you have some code that takes too long to run in your php file. There is a sanity check that keeps track of the time you spend on a page, and the timer times-out you will get the Maximum execution time exceeded message. The duration for this time-out value is set in the php.ini

maximum_execution_time = 30

You can reset this in your file to debug what is happening. Using

ini_set('max_execution_time', 300);

sets the maximum execution time to 300 seconds or 5 minutes.


You need to surround snippets of your code with some timestamp routines to figure out
which portion is taking up a long time.

$ts = microtime(true); 

   // code snippet to check timing of 

var_dump(microtime(true) - $ts);

If you are doing MySQL database queries, you can turn to the slow queries log to see if there are any SQL queries that are too complex and take a while to return (for e.g., a join with several large tables would slow down you query because of the large result set.

To enable the slow query log, start mysqld with the --log-slow-queries[=file_name]

The slow query log can be used to find queries that take a long time to execute and are therefore candidates for optimization. However, examining a long slow query log can become a difficult task. To make this easier, you can process a slow query log file using the mysqldumpslow command to summarize the queries that appear in the log.

Diagnosing slow PHP execution with Xdebug and KCachegrind

Profiling a PHP application can explain how much time the server spent in each function, each file, and each code path. It can also show you how many times a function or method was called, which is useful for diagnosing programming errors involving pointless looping. Xdebug generates cachegrind-compatible files which can also be used to create easy-to-understand graphs using KCachegrind.

The log file created by Xdebug can be small or large depending on what the application is doing. Also, it’s not really reader friendly. You’ll want to use programs like KCachegrind or Webgrind to view them. KCachegrind is a profile data visualization tool for KDE, which needs a Unix environment to run, whereas Webgrind is a web-based tool.

http://kcachegrind.sourceforge.net/html/Home.html
https://github.com/jokkedk/webgrind
https://github.com/ceefour/wincachegrind
http://ceefour.github.io/wincachegrind/

WinCacheGrind is a viewer for cachegrind.out files generated by xdebug 2. WinCacheGrind is functionally similar to KCacheGrind, only it is much simpler and runs on Windows.

As we have done in a previous PHP debugging tip, we need to enable certain Xdebug options in the php.ini file. Specifically those related to profiling.

xdebug.profiler_enable = 1
xdebug.profiler_output_name = xdebug.out.%t
xdebug.profiler_output_dir = /tmp
xdebug.profiler_enable_trigger = 1

xdebug.profiler_enable is used to enable profiling in Xdebug (off by default). xdebug.profiler_output_name is the filename of the profiler log (the %t specifier appends a timestamp to the filename. 
xdebug.profiler_output_dir stores the profiling output in the directory specified

Profiling degrades performance since the PHP engine.
xdebug.profiler_enable_trigger instructs Xdebug to perform profiling only when XDEBUG_PROFILE is passed as a GET or POST parameter.


2014-08-13

How to fix #PHP #BSOD - Blank Screen of Death / #WSOD - the White Screen of Death (PHP Debugging)

You created a PHP file which was running fine. Then you made some changes to improve it and uploaded it to your server. Suddenly, all you get is a blank screen on your browser. Not even an error message!!

What happened ?!?

You have just witnessed the well known PHP BSOD or WSOD.
This happens when error messages are turned off. This would be the default settings on many production PHP servers. You won't want your customers to see all your error messages appearing on their screens.

How to fix this? Basically, we can
1) turn on the error messages display, or
2) create custom error handlers
 
#1 - Turning on error messages

You can change the settings of the php.ini or .htaccess or include the following
at the top of the php file

<?php
ini_set('error_reporting', E_ALL); // or -1 
ini_set('display_errors', 'On');  //On or Off

On Apache web server, we can use the .htaccess file to configure
PHP error messages

php_value display_errors 1
php_value display_startup_errors 1
php_value error_reporting -1 # E_ALL

Or, if you do have access to the php.ini, you can set the error reporting in the php.ini

display_errors = On
display_startup_errors = On 
error_reporting = E_ALL 
  #2 - Custom error handling function

You can define your own handling function. When an error occurs, this custom
function gets called

<?php
// error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    if (!(error_reporting() & $errno)) {
        // This error code is not included in error_reporting
        return;
    }

    switch ($errno) {
    case E_USER_ERROR:
        echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
        echo "  Fatal error on line $errline in file $errfile";
        echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
        echo "Aborting...<br />\n";
        exit(1);
        break;

    case E_USER_WARNING:
        echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
        break;

    case E_USER_NOTICE:
        echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
        break;

    default:
        echo "Unknown error type: [$errno] $errstr<br />\n";
        break;
    }

    /* Don't execute PHP internal error handler */
    return true;
}


// you need to register the custom error handler to use it
// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");


// the #old_error_handler can be used to reset the handler

     

 




2014-08-06

Tips & Techniques for debugging PHP (part 4)

Debuggers are software that have been specifically created for this task: debugging. When you use a debugger, you get a "Swiss Army Knife" array of tools to help you in the task of tracking down the location of, finding and removing the causes of bugs.

For PHP, the debugger is XDebug. It has integrations for all populars IDEs such as Eclipse, Netbeans, PHPStorm, etc.

http://xdebug.org

For easy installation, I would suggest you check out the XDebug Wizard

http://xdebug.org/wizard.php

What it needs is the output from phpinfo()
Just create a simple checkinfo.php file with just
<?php
phpinfo();

Paste it into the form on the XDebug Wizard page. Customized installation instructions would be provided. For the binary library file for Xdebug, I have found that most installations of PHP already have the XDebug binary included, but it just needs you to uncomment the php.ini file to activate it. For example, I have included the XDebug section for my xampp php.ini (noticed that I uncommented some lines).
The additional line is the one xdebug.remote_port=9000 which is the additional line I added because I am using Netbeans and the default configuration in Netbeans uses 9000 as the debug port. http://xdebug.org/docs/remote

[XDebug]
zend_extension = "D:\xampp\php\ext\php_xdebug.dll"
;xdebug.profiler_append = 0
xdebug.profiler_enable = 1
;xdebug.profiler_enable_trigger = 0
xdebug.profiler_output_dir = "D:\xampp\tmp"
;xdebug.profiler_output_name = "cachegrind.out.%t-%s"
xdebug.remote_enable = 1
xdebug.remote_handler = "dbgp"
xdebug.remote_host = "127.0.0.1"
xdebug.remote_port=9000
xdebug.trace_output_dir = "D:\xampp\tmp"


For more details about using XDebug and Netbeans configuration, please refer to the Netbeans documentation help pages. 
http://wiki.netbeans.org/HowToConfigureXDebug
https://netbeans.org/kb/docs/php/configure-php-environment-windows.html#installAndEnableXDebug


For more info on using XDebug refer to
http://devzone.zend.com/1120/introducing-xdebug/
I will be talking more about tracing and neat other things you can do with XDebug later on in another part of this PHP debugging series of posts.
 

2014-08-04

How to debug PHP tips & techniques (Part 3)

Using print statements inside the script to display the trace of execution is a tried and tested method of debugging. For PHP is has several commands that can be used for displaying a trace of the executing PHP file.

Echo command can be used for quick debug message. You can comment them off when not in use.

echo "message line";

// echo "message line"; commented off

USING VAR_DUMP() TO AID YOUR DEBUGGING

var_dump() is a native PHP function which displays structured, humanly readable, information about one (or more) expressions. This is particularly useful when dealing with arrays and objects as var_dump() displays their structure recursively.

echo '<pre>'; var_dump($aMyData); echo '</pre>';

Tip: Wrap var_dump() in <pre> tags to aid readability.

Sometimes you may want to collect the log messages
in separate file instead of showing it in the browse.
You can log data to the standard error log file with error_log. 

http://php.net/manual/en/function.error-log.php

PHP does not come with different debug levels (info, warning, error), you may also 
standalone log modules/classes like Monolog or KLogger.

Monolog: https://github.com/Seldaek/monolog

KLogger: http://codefury.net/projects/klogger/

Besides var_dump(), you could also use var_export and print_r() functions in PHP
to examine variable values.

print_r() displays information about a variable in a way that's readable by humans.

print_r(), var_dump() and var_export() will also show protected and private properties of objects with PHP 5. Static class members will not be shown.



2014-08-03

Debugging PHP tips and techniques (part 2)

An alternative to setting up the PHP server on your PC, Mac or Linux machine is to create a virtual server within a virtual machine (VM) running on your machine. This would closely emulate the final deployment environment. As the VM is usually running Linux, it would support things like case-sensitivity in the web server (something which causes grief on windows based web servers).

There are a number of free solutions for creating VM servers on your operating system.
VirtualBox is available on most platforms as long as you are running on Intel.
VirtualBox: https://www.virtualbox.org

VirtualBox is a powerful x86 and AMD64/Intel64 virtualization product for enterprise as well as home use. Not only is VirtualBox an extremely feature rich, high performance product for enterprise customers, it is also the only professional solution that is freely available as Open Source Software under the terms of the GNU General Public License (GPL) version 2.

Presently, VirtualBox runs on Windows, Linux, Macintosh, and Solaris hosts.

Vagrant: http://www.vagrantup.com
Vagrant is a tool that allows quick setup of development environments using virtual machines. It works well with VirtualBox.


WHY VAGRANT?
Vagrant provides easy to configure, reproducible, and portable work environments built on top of industry-standard technology and controlled by a single consistent workflow to help maximize the productivity and flexibility of you and your team.

To achieve its magic, Vagrant stands on the shoulders of giants. Machines are provisioned on top of VirtualBox, VMware, AWS, or any other provider. Then, industry-standard provisioning tools such as shell scripts, Chef, or Puppet, can be used to automatically install and configure software on the machine.


To make the configuration of PHP itself easier, we can turn to PuPHPet
PuPHPet: https://puphpet.com/
Configuration of your Vagrant+VirtualBox is as easy as choosing from a menu of options.

But, you may want to try Docker instead of VirtualBox as a Vagrant provider
http://www.tylercipriani.com/2014/05/25/lightweight-portable-vagrant-docker.html

The latest versions of Vagrant (1.6.2, as of May 26th) can actually use docker as a provider, that is, as an alternative to VirtualBox. Using Docker as a provider means that you can run a fully-independent development enviroment, on your host machine without the overhead of VirtualBox. 



2014-08-02

PHP Debugging tips and techniques (Part 1)

PHP is a script based language. It does not require a compilation process. Errors can only be detected when you run the PHP code.

Tip #1 - setup a development environment on your own machine. 

With the available of cheap PHP hosting, some PHP developers just use a text editor to write the code. Then upload the php file directly to the PHP server using FTP, and test using the PHP server. If there are any errors in the PHP file, they would be obvious when the you try to view the page on the browser.

When it comes to debugging, this is a very slow and tedious process of finding a bug, the correcting (at least hope to) and uploading the new version of the php file and testing with a browser. It would probably take far less time, to setup the development environment on your machine. At the very least, it would save you the hassle of repeatedly uploading the file to the server.

A number of pre-packaged installers exists for windows and macosx and linux

https://www.apachefriends.org/index.html
Mac, Win, Linux

http://www.easyphp.org/
Win

http://www.mamp.info/en/
Mac



Github CoPilot Alternatives (VSCode extensions)

https://www.tabnine.com/blog/github-copilot-alternatives/