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-11

Debugging PHP and MySQL (Part 5)

Debugging PHP with a MySQL database backend is something which most PHP developers would have to do. Here are some tips & suggestions when doing this form of debugging.

#1. Make sure you can connect to the MySQL

It might seem kind of obvious. But, when you have a new project and development environment setup. You may not be able to connect to the database right away
1) Because you forget to start the MySQL database server
2) Because you did not configure the connection passwords correctly
3) You are trying to use root to connect to the database from the web server. (Passwords in mysql are setup per IP. Usually they are only set for access via localhost only, especially for the root user.)

#2. Use a gist of code to test the database connection first

If the gist works, then you should debug the application logic instead of the database connection

<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if (!$link) {
    die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
echo 'Connected... ' . mysqli_get_host_info($link) . "\n";


#3. Check if all the parameters for your SQL query string are actually correct

When the SQL query string looks correct, 99% it is because it is correct and you
are actually using the wrong parameter values and hence causing errors to occur 
when you execute the code.

$sqlstr = 'SELECT * FROM mydbtable WHERE myname = $input_var';
echo $sqlstr;
if (!$mysqli->query($sqlstr)) {
    echo 'Error: ', $mysqli->error;
}


In the code above, you may find that $input_var is actually an empty string and
thus the SQL statement you are running
is SELECT * FROM mydbtable WHERE myname =

This would result in an error.


<?php $link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db'); if (!$link) { die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); } echo 'Connected... ' . mysqli_get_host_info($link) . "\n"; - See more at: http://jason.pureconcepts.net/2013/04/common-debugging-php-mysql/#sthash.6ZkmQHcs.dpuf
<?php $link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db'); if (!$link) { die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); } echo 'Connected... ' . mysqli_get_host_info($link) . "\n"; - See more at: http://jason.pureconcepts.net/2013/04/common-debugging-php-mysql/#sthash.6ZkmQHcs.dpuf
<?php $link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db'); if (!$link) { die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); } echo 'Connected... ' . mysqli_get_host_info($link) . "\n"; - See more at: http://jason.pureconcepts.net/2013/04/common-debugging-php-mysql/#sthash.6ZkmQHcs.dpuf
<?php $link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db'); if (!$link) { die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); } echo 'Connected... ' . mysqli_get_host_info($link) . "\n"; - See more at: http://jason.pureconcepts.net/2013/04/common-debugging-php-mysql/#sthash.6ZkmQHcs.dpuf

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



2014-07-30

Strings to DateTime using C# (problems with different date formats from around the world)

// Date strings are interpreted according to the current culture. 
// If the culture is en-US, this is interpreted as "January 8, 2008",
// but if the user's computer is fr-FR, this is interpreted as "August 1, 2008" 
string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);            
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}", dt.Year, dt.Month, dt.Day);

// Specify exactly how to interpret the string.
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);

// Alternate choice: If the string has been input by an end user, you might  
// want to format it according to the current culture: 
// IFormatProvider culture = 
//     System.Threading.Thread.CurrentThread.CurrentCulture;
DateTime dt2 = DateTime.Parse(date, culture, 
      System.Globalization.DateTimeStyles.AssumeLocal);
Console.WriteLine("Year: {0}, Month: {1}, Day {2}", 
      dt2.Year, dt2.Month, dt2.Day);

/* Output (assuming first culture is en-US and second is fr-FR):
    Year: 2008, Month: 1, Day: 8
    Year: 2008, Month: 8, Day 1
*/

I was encountering a lot of problems converting a simple string like
"30/7/2014 11:00" to DateTime because I kept getting an exception for invalid DateTime string.


I was doing the conversion using the code like

String datestr = "30/7/2014 11:00";
DateTime mydate = Convert.ToDateTime(datestr);

Finally, I dawned upon me that the source of the problem was that the machine I was
working on was set to "en-US" mm/dd/yyy and not the UK style dates dd/mm/yyyy which I normally worked with.

Without changing the machine setting, I had to use the CulturalInfo and DateTime.Parse instead. So the code ended up like the one below

String datestr = "30/7/2014 11:00";
IFormatProvider culture = new System.Globalization.CultureInfo("en-GB", true);DateTime mydate = DateTime.Parse(datestr, culture);


The list of strings that can be used to set the CulturalInfo is below:
http://msdn.microsoft.com/en-us/goglobal/bb896001.aspx


Note that for English we can have "en-US", "en-UK", "en-SG", "en-AU", "en-IN" 
Which leads me to wonder how many versions of English there are in the world.

The reverse path of formatting a DateTime to string is easier. For example, to get at date string in ISO format I can use
mydate.ToString("yyyy-MM-ddTHH:mm:sszz");

http://en.wikipedia.org/wiki/ISO_8601
provides a detailed description of the international standard for datetime string. This should work in all countries.

There is a way to parse the datetime string in a custom format that is culture independent. We should use DateTime.ParseExact method instead of DateTime.Parse


string dateString, format;  
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;

// Parse date and time with custom specifier.
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
try 
{
    result = DateTime.ParseExact(dateString, format, provider);
    Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
    Console.WriteLine("{0} is not in the correct format.", dateString);
}







2014-07-29

Interactive dashboard on #top #programming-languages #ranking 2014

http://spectrum.ieee.org/static/interactive-the-top-programming-languages

Whenever I see a title like "Top Programming Languages," I get intrigued. But, at the same time I also become a little cautious about what exactly is meant by "top." The link above is done by the IEEE -- no doubt a fairly reliable information source. Even better, the dash board is not just a static graph, it is interactive and allows you to explore different facets. For example, you can see the ranking by Web Programming, or by Mobile Programming. Or from the viewpoint of employers' demand.

http://spectrum.ieee.org/ns/IEEE_TPL/methods.html

There is no secret sauce; their methodology is spelled out clearly.

"IEEE Top Programming Languages: Design, Methods, and Data Sources
The IEEE Spectrum Top Programming Languages app synthesizes 12 metrics from 10 sources to arrive at an overall ranking of language popularity. The sources cover contexts that include social chatter, open-source code production, and job postings." 

What is interesting is that Github is used as a starting point to get an initial list of potential programming languages. Not asking any of the top technology companies to come up with their favourites. Or any computer scientists in academia to nominate their list. What is missing is perhaps a geographic dimension to this poll. Some languages are much more popular in certain parts of the world compared with the US or other countries. 

'What We Track
Starting from a list of over 150 programming languages gathered from GitHub, we looked at the volume of results found on Google when we searched for each one in the pattern “X programming” where “X” is the name of the language. We filtered out languages if they had a very low number of search results and then went through the list by hand to identify the most interesting languages. We labeled each language according to its use in Web, mobile, enterprise/desktop, or embedded environments.'



2014-07-25

Free PHP hosting on the cloud for developers

When you are developing new PHP application, you would like to test it out on a free hosting platform. A number of cloud providers have started providing such services for developers. However, caveat-emptor -- these may be beta services and you should not run production stuff on them, the service may be "freezed" at anytime.

http://fortrabbit.com/pricing
FOC for developers and you get MySQL database with your PHP server.


https://www.openshift.com/developers/php
https://www.openshift.com/products/pricing
FOC for PHP developers

http://bowery.io/pricing/
Interesting twist. They try to make it easy for developers
to setup their cloud development environment

https://elasticdot.io/pricing
PHP Developer -- always free + MySQL Database

Here is a comparison done (in 2014) by the FortRabbit folks
http://blog.fortrabbit.com/cloudscapes-revisited-php-cloud-overview/

Not needing credit card to sign-up is really useful for academic setting, or places where credit cards are not so common among the developers. 

"dotCloud made a 540deg turn. As far as is read the story: Like AppFog (and us in the future), they ditched the freemium plan. Alongside they open-sourced a core component of their platform: Docker (LXC made easy). Docker went boom. DotCloud pivoted and became Docker.comoffering B2B solutions services around Docker. Alongside a new category was born: Docker as a Service with commercial services like: Flynn,StackdockDeisOrchardTutumAppsdeck … A really interesting story about combining open source and business." -- source: FortRabbbit blog article.

I think it is pretty interesting about what's happening with dotcloud.com ==> docker.com
Freemium is not the only path. For a PHP developer, LXC/Docker.com provides a plug+socket kind of arrangement when deploying your PHP app+LAMP stack.

http://www.slideshare.net/bingoarunprasath/docker-demo-on-php-application-deployment

Many docker cloud "sockets" out there to plug your PHP application in.
https://www.orchardup.com/
https://www.tutum.co/
https://stackdock.com/
https://flynn.io/
http://deis.io/get-deis/



D

How to prevent database orphans from appearing?

What is a database orphaned record?

Suppose you have a parent-child relationship between two database tables (for example Orders and OrdersLine. Each record in the OrdersLine table must have one foreign key that is linked to an orderId in the Orders table.

What happens when we do a delete on the Orders table? One of the orderId gets removed.  All the records in the OrdersLine table that referred to this parent record orderId are then "orphaned"; i.e., they have lost the parent record. To automatically prevent this from happening we can use a convenient trick called ON DELETE CASCADE when we define the database


Example.

CREATE TABLE Orders
(
orderId INT PRIMARY KEY,
product_name VARCHAR(50) NOT NULL,
category VARCHAR(25)
);


CREATE TABLE OrdersLine
(
orderlineId INT PRIMARY KEY,
product_id INT NOT NULL,
quantity INT,
CONSTRAINT fk_order_id
FOREIGN KEY (orderId)
REFERENCES Orders (orderId)
ON DELETE CASCADE
);



What is a foreign key with Cascade DELETE in SQL Server?
A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table with automatically be deleted. This is called a cascade delete in SQL Server. 

It is also possible to configure this in the SQL Server Management Studio (SSMS) 2014. 
Go to the table with the FK (foreign key). Right-click on the table and select the Design option.
Right click on the foreign key column, look under Relationships... (A Pop-up Dialog appears, Choose the FK relationship you want to edit). Scroll down to where you can see INSERT and UPDATE Specification, and chose on DELETE CASCADE. Click close to close the Pop-up.
(REMEMBER TO PRESS THE SAVE BUTTON in the toolbar)







Github CoPilot Alternatives (VSCode extensions)

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