Error Handling in PHP (Part 2)

Now that we know, how to log errors in any system developed in PHP, we can move to our next section for keeping track of these logged errors. If you haven’t read how to log errors, read part 1 of error handling in PHP.

To keep track of these logged errors, we need to create a script to read those log files in a systematic way. Refer to the below code to read log files,

public function errorLogs($filePath = 'error.log') {

        $fileContent = file($filePath);

        $errorsArray = array();
        if(sizeof($fileContent) == 0) {
            return false;
        }

        foreach($fileContent as $row) {
            $errors = explode(":  ", $row);

            if(empty($errors[1])) continue;
            $errorsArray[] = $errors;
        }

        return array_reverse($errorsArray, true);
}

Explanation:

$fileContent = file($filePath);

This line of code will read the file line by line from the provided file path.

if(sizeof($fileContent) == 0) {
    return false;
}

After reading the file, if the size of the file content is 0 then, the function will return false. So, the purpose of this function is to stop the execution of the function if the provided file is empty and returns false.

foreach($fileContent as $row) {
      $errors = explode(":  ", $row);

      if(empty($errors[1])) continue;
      $errorsArray[] = $errors;
}

This part of the function will loop through the log contents row by row. For each row, it will explode the line with ‘:’ to separate the date and actual error details.

If the error details are empty for any row, it will skip that row. Otherwise, it will collect the errors in another array.

return array_reverse($errorsArray, true);

The last line of the function will reverse the error data and returned the reversed result. So, that we can see the latest errors first.

This way we can create a simple function to display the list of errors in a tabular format from the error log files we generated for each of the modules in the application system.

Error handling in PHP (Part 1)

Error handling is an important part of any developer as it provides vital flaws about the program developed by the developer. So, it becomes very crucial to learn the techniques to manage it.

As a developer, we have been told that you should not show errors on the production server because of the security risk due to the path displayed by the PHP errors displayed on the screen. So, we add the following code for the production server,

ini_set('error_reporting', 0);
error_reporting(0);

ini_set('display_errors', FALSE);

But, without error logs, developers cannot able to know actual problems or flaws in the system. So, rather than hiding errors, developers should store them in the log files. We can achieve this using the following code,

ini_set('error_reporting', E_ALL);
error_reporting(E_ALL);
ini_set('log_errors', TRUE);
ini_set('html_errors', FALSE);
ini_set('error_log', LOG_PATH.'error.log');
ini_set('display_errors', FALSE);

This way, we can manage error logs and hide errors on the production server. We can manage separate log files for the different modules of the project.

Setup and use a virtual python environment in Ubuntu

With virtualenvwrapper (user-friendly wrappers for the functionality of virtualenv)

Install virtualenv

Install virtualenv with

sudo apt-get install virtualenv

(for Ubuntu 14.04 (trusty) install python-virtualenv)

Install virtualenvwrapper

The reason we are also installing virtualenvwrapper is that it offers nice and simple commands to manage your virtual environments. There are two ways to install virtualenvwrapper:

As Ubuntu package (from Ubuntu 16.04)

Run sudo apt install virtualenvwrapper then run echo "source /usr/share/virtualenvwrapper/virtualenvwrapper.sh" >> ~/.bashrc

Using pip

  1. Install and/or update pip

    Install pip for Python 2 with
    sudo apt-get install python-pip

    or for Python 3
    sudo apt-get install python3-pip

    (if you use Python 3, you may need to use pip3 instead of pip in the rest of this guide).

    Optional (but recommended): 
    Turn on bash autocomplete for pip Run
    pip completion --bash >> ~/.bashrc

    and run 

    source ~/.bashrc 

    to enable.
  2. Install virtualenvwrapper Because we want to avoid sudo pip we install virtualenvwrapper locally (by default under ~/.local) with:
    pip install --user virtualenvwrapper

    and

    echo "export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3" >> ~/.bashrc
  3. Source virtualenvwrapper in .bashrc

    echo "source ~/.local/bin/virtualenvwrapper.sh" >> ~/.bashrc

Setup virtualenv and virtualenvwrapper:

First, we export the WORKON_HOME variable which contains the directory in which our virtual environments are to be stored. Let’s make this ~/.virtualenvs

export WORKON_HOME=~/.virtualenvs

now also create this directory

mkdir $WORKON_HOME

and put this export in our ~/.bashrc file so this variable gets automatically defined

echo "export WORKON_HOME=$WORKON_HOME" >> ~/.bashrc

We can also add some extra tricks like the following, which makes sure that if pip creates an extra virtual environment, it is also placed in our WORKON_HOME directory:

echo "export PIP_VIRTUALENV_BASE=$WORKON_HOME" >> ~/.bashrc

Source ~/.bashrc to load the changes

source ~/.bashrc

Test if it works

Now we create our first virtual environment. The -p argument is optional, it is used to set the Python version to use; it can also be python3 for example.

mkvirtualenv -p python2.7 test

You will see that the environment will be set up, and your prompt now includes the name of your active environment in parentheses. Also if you now run

python -c "import sys; print sys.path"

you should see a lot of /home/user/.virtualenv/... because it now doesn’t use your system site packages.

You can deactivate your environment by running

deactivate

and if you want to work on it again, simply type

workon test

Finally, if you want to delete your environment, type

rmvirtualenv test

Enjoy!

Autostart Glassfish on startup in Ubuntu

To make the Glassfish Server auto start with startup, we need to setting up an init script, which helps us to manage all Glassfish Server startup events easily. And also make Glassfish start up automatically whenever Ubuntu is rebooting.

This script file is glassfish to be created at /etc/init.d/. For managing all Glassfish Server startup events, it ships with the asadmin tool. Use this tool in the startup script as follows,

  1. Create or edit glassfish file sudo nano /etc/init.d/glassfish
  2. Paste the following lines in the file #!/bin/sh #to prevent some possible problems export AS_JAVA=/usr/lib/jvm/jdk1.8.0 GLASSFISHPATH=/home/glassfish/bin case “$1” in start) echo “starting glassfish from $GLASSFISHPATH” sudo -u glassfish $GLASSFISHPATH/asadmin start-domain domain1 ;; restart) $0 stop $0 start ;; stop) echo “stopping glassfish from $GLASSFISHPATH” sudo -u glassfish $GLASSFISHPATH/asadmin stop-domain domain1 ;; *) echo $”usage: $0 {start|stop|restart}” exit 3 ;; esac :

Now, glassfish startup script is created. We need to add this file in startup to make Glassfish Server autostart during Ubuntu startup. Follow these steps,

  1. Make the startup script file executable sudo chmod a+x /etc/init.d/glassfish
  2. Add this file to Ubuntu startup boot sudo update-rc.d glassfish defaults

That’s it. Now, restart Ubuntu and check if it really autostart the Glassfish Server.

You can also manage Glassfish Server startup events as follows,

  • Start the server /etc/init.d/glassfish start
  • Stop the server /etc/init.d/glassfish stop
  • Restart the server /etc/init.d/glassfish restart  

Accessing PostgreSQL via SSH Putty tunnel

To close the port 5432 for any traffic or don’t want to configure PostgreSQL to listen to any remote traffic, use SSH Tunneling to make a remote connection to the PostgreSQL instance at AWS.

Follow these steps to connect PostgreSQL using SSH Tunneling at AWS:

  1. Open PuTTY. Setup server session in Putty.
  2. Go to Connection > SSH > Tunnels
  3. Enter 8000 in the Source Port field.
  4. Enter 127.0.0.1:5432 in the Destination field.
  5. Click the “Add” button.
  6. Go back to Session, and save, then click “Open” to connect.
  7. This opens a terminal window. After connection leaves that alone.
  8. Open pgAdmin and add a connection.
  9. Enter localhost in the Host field and 8000  in the Port field.
  10. Specify a Name for the connection, and the username and password. Click OK.
What is it doing? PuTTY is intercepting communications sent from pgAdmin to localhost:8000. The information is transferred across the internet via SSH, on port 22. When it arrives there, the SSH server sends the information on to PostgreSQL via port 5432. As far as PostgreSQL knows, the traffic came in locally, on the correct port.