Zareef Ahmed

A polyglot programmer and enterprise architect having hands on experience in Ruby,Python, PHP, Perl, Java and many other languages. Specialist in Devops, Cloud migration and implementation on Amazon Cloud (AWS), Google Cloud (GCP) and Microsoft Azure along with Hadoop programming for big data processing.

Use Exit after redirecting user via header function

Some weeks ago I got an old PHP application to work with. I was asked to look for the potential problems and bottlenecks in the application. So I decide to use APD as a profiler for the application, after installing the APD on that server. I enabled profiler on one of the reportedly slow page.

That page was meant to be displayed and executed only if user is logged in and session variables are set. If we dont found user session then user was being redirected to Login page of the application.

I called that page directly in the browser and got the login screen. It was perfectly acceptable behavior.

BUT when I run the profiler to get the information about the execution of page I was surprised to see that almost all functions which were only meant to be executed for logged in users were being called and they were taking the system resources.

Just to confirm I refresh the page in browser many time (without login), and each time I got same profile information for page.

Then I run the test using Apache benchmark (ab) and while test was in running I decide to see the process list of mysql database, again I see that heavy queries were being fired on the database. (But this time I was not surprised, as it was expected and I did just to confirm and take the screen shot so I can show that to the owner of the application.)

Now I decide to check the reason behind this, so I opened that page in my Zend Studio, and yes I got the reason

Application was redirecting the user to login page if user is not logged in using header function via location define mechanism Like

header("location: login.php");

And they were not using exit after that. I just add the exit(); after that header function call and problem was fixed.

header("location: login.php");
exit();

Just an improper use of header was the reason behind unnecessary load on the web server as well as on database server.

Note : If you do use the location setting of the header to redirect to another page, do not forget to use exit; to prevent further execution of script code.