Posts

PHP Best Practices That You Must Follow

PHP is the most widely-used language for programming on the web. There are many beginners or even experienced PHP developers who don’t bother to follow the best practices of the language, either unintentionally or intentionally. And it’s really very difficult for anybody to get hold of the best practices overnight. So I am listing some of the best practices for php programmer below:

Follow the PHP Manual 

If you’re  a beginner PHP programmer, then you should get yourself acquainted with PHP manual. The PHP manual is incredibly thorough and has truly helpful comments following each article. To save your precious time you should directly go to PHP manual before trying to figure out an issue on your own. There are very high chances that the answer to your question is already nestled in a helpful article at the PHP.net site.

Document your Code

It is very important to maintain proper documentation of your code. It’s really very unfortunate seeing some beginners or even seasoned programmers not focusing on writing meaningful comments to their codes just because they are too lazy. Proper documentation help others to understand your code better, and remember what you have written when you review it in the future.

Maintain Proper Coding Standard

It is very important to maintain a proper coding standard. It can be a painful problem if more than one programmer is working on the same project, and they are using different coding standards. In such a case the source code can become completely unmanageable. To solve such situations you need to maintain a proper coding standard, then it would be easier for others to debug your code and your joint projects will tend to be much more productive.

Avoid Using PHP Short Tags

Many programmers try to take shortcuts when declaring PHP. Here are a few common ones:

All these methods have been officially depreciated  and they are never coming back. Moreover this malpractice can cause conflicts with XML parsers and can also make your code incompatible with future versions of PHP.

Variable and Function Names Must be Meaningful

Always use proper naming standard and avoid using generic and un-meaningful names everywhere. Using generic and un-meaningful names is not a good practice at all, and you must not follow it in any way. Your variable and function names must always by meaningful and grammatically sensible and try to make the good habit of separating every word with underscores. And also try to be consistent with the standard you are following so that other people can get to understand your convention quickly and easily.

If you just have a simple string to display, then always go for single quotes. But if you are going to have variables and special characters like “n”, “t” in your string, then you must use double quotes which will get your string parsed by the PHP interpreter and will take more execution time than single quoted strings. So, make sure you understand the difference in their working nature and use them appropriately.

Don’t Use Functions Inside Loops

There are many programmers who tend to make the mistake of using functions inside of loops. If you are one of theme and if you are doing this intentionally and are ready to compromise performance just for the sake of saving a line of code, then you certainly need to think once again.

Bad Practice:

Good Practice

If you store the value returned by the function in a separate variable before the loop, then you would be saving enough execution time as in the first case the function will be called and executed every time the loop runs which can increase the time complexity of the program for large loops.

Turning on Error Reporting for Development Purposes

PHP error reporting is a very useful function, error_reporting() which can be used to spot various problems or errors in your PHP application during development. You’ll find bugs in your code that you might not have spotted earlier, as not all bugs keep the application from working. There are different levels of strictness in the reporting that you can use, but E_ALL will show you the most errors, critical and warnings alike.

There are various levels of error reporting available in PHP, like E_NOTICE, E_WARNING, E_PARSE, etc. but you can use E_ALL to report all kinds of errors. But always remember to disable error reporting when you are done with the development process of your code, so that your visitors don’t get scared with various unintelligible messages.

Indent Code and Use White Space for Better Readability

A code which is not properly indented will be very difficult to read and understand. Ensure that your code is readable and easy to search because you’ll most definitely be making changes in the future. IDE’s and advanced text editors can add indentation automatically.

Avoid Deep Nesting

Always try to avoid deep nesting levels in your code. It will make things very difficult for you when you need to debug your code. Try to use conditions as logically as possible to avoid unnecessary deep nesting. It is not only a very poor programming practice, but also can make your code look ugly enough to your fellow developers.

Don’t Put phpinfo() in you Webroot

By creating an PHP file and placing it somewhere on you server you can instantly get all the information about you r server environment.

 

But a lot of developers make the mistake of placing this file in the root directory of their server. This is a really insecure practice, and if prying eyes gain access, it could potentially spell doom for your server. The best idea is to delete this file whenever you are done with it. 

Store Passwords with Encryption

Many PHP programmers often save sensitive data like passwords into the database without applying any encryption. Consider using MD5 to encrypt passwords before you put them into the database.

There are various ways of storing password safely, like MD5, SHA1, MD4, MD2, Whirlpool, Salsa20, etc.

Protect your Script From SQL Injection

Your code is vulnerable to SQL injection if you don’t escape characters user in SQL strings. To avoid this you can use mysql_real_escape_string or prepared statements.

Example of mysql_real_escape_string in action:

Example of prepared statements:

Use Database Visualization Design Tools

If you’re finding it difficult to plan and modify databases for your PHP applications, you might look into using a database visualization tool. MySQL users can work with DBDesigner and MySQL Workbench to visually design your databases.

Try a PHP Framework

If you have become a pro PHP programmer then you should always try some PHP frameworks. There are lots of PHP frameworks available out there. Most of the PHP frameworks are designed on the basis of Model-View Controller (MVC) software architecture. Frameworks like CakePHP, CodeIgniter, Zend, Symfony can help you create some awesome PHP applications with ease.

Upgrade PHP

Many developers are reluctant enough to upgrade their PHP software in time. There are various performance improvements and feature additions in the newer versions of PHP. So there is absolutely no reason for you to avoid upgrading your PHP. There are some bug fixes and security improvements with almost every new release too. Check your server to make sure you’re up to date.

 

Top PHP IDE’s

There are a number of IDE’s available for PHP development. In this article we’ll discuss about some free/open-source and some paid IDE’s that might help you in selecting the best. A wisely selected IDE will help you increase productivity while developing web applications.

What is an IDE?

An IDE (integrated development environment) is a software application that provides comprehensive facilities to programmers for web development. An IDE normally consists of a source code editor, build automation tools and a debugger. Most IDEs offer Intelligent code completion feature.

In order to get success in developing PHP sites it is necessary to have a good development environment. While producing web sites it is often necessary to edit HTML, CSS and JavaScript files. That is why usable IDE should supply all those file types and provide full set of tools for effective development.

Below are what we think best PHP IDE’s:

Komodo

Pricing: Free/Paid Website: http://komodoide.com
OS Platforms:  Linux, Windows, Mac

Komodo is a multi-language IDE. The code intelligence is solid. Version Control is also surpported via Subversion, Mercurial, Git, Perforce, Bazaar, CVS. You can edit with multiple users simultaneously with Code Collaboration. it has also great debugging and unit testing features. For more information you can visit http://komodoide.com.

PhpStorm

Pricing: Paid Website: http://www.jetbrains.com/phpstorm/
OS Platforms:  Linux, Windows, Mac

PhpStorm provides an editor for PHP, HTML and JavaScript with on-the-fly code analysis, error prevention and automated refactorings for PHP and JavaScript code. PHP code refactoring also reviews PHPDocs to keep them up-to-date. It includes a full-fledged SQL editor with editable query results. It also helps you to form your code, run unit-tests or perform full debugging.

Codelobster PHP Edition

Pricing: Free/Paid Website: http://www.codelobster.com/
OS Platforms:  Windows

Codelobster PHP Edition streamlines and simplifies the PHP development process. You don’t need to keep in mind the names of functions, arguments, tags or their attributes — we’ve implemented all these for you with autocomplete features for PHP, HTML, JavaScript and even CSS. And you can always get necessary help information by pressing F1 or using the special Help control.

Eclipse

Pricing: Free Website: http://www.eclipse.org/
OS Platforms:  Linux, Windows, Mac

Eclipse allows you to select language, platform and vendor environment. Eclipse encompasses the development components necessary to develop PHP-based Web Applications and facilitates extensibility.  It also involves Data Tools Platform to control the databank, plug-ins for interaction with JavaScript, C / C + +, XML editor, and other different tools.

PHP Designer

Pricing: Paid Website: http://www.mpsoftware.dk/
OS Platforms:  Windows

Php Designer focus on the designing aspect of the PHP Web Development. Its features includes intelligent syntax highlighting, debug support, syntax analyzing, support for object-oriented coding, code insight on the fly, code templates, code snippets, todo and bug managers, work with projects and frameworks, intuitive code navigation, code formatters and minifiers and all wrapped into a nice looking intuitive user interface.

PhpED

Pricing: Paid Website: http://www.nusphere.com/
OS Platforms:  Windows

NuSphere PhpED  is a Windows only IDE. PhpED features include Advanced PHP Editor, PHP Debugger and PHP Profiler, Code Insight, Database Client, Integrated Help System, Code Insight. PhpED supports JavaScript, HTML, CSS, XML, SMARTY, XHTML and others. Full support for PHP versions from 4.3 to 5.4 (5.5 is fully supported for debugging and profiling) in IDE and the Editor – from functions and local variables to namespaces and aliases.

PHPEdit

Pricing: Paid Website: http://www.phpedit.com/
OS Platforms:  Windows

PHPEdit is a Windows-only IDE, and it’s easy to set up. PhpEdit works with a fully-featured, highly ergonomical Integrated Development Environment for PHP. To help with deployment, PHPEdit connects to CVS and Subversion, as well as FTP and its own proprietary ezDeployment system.

Zend Studio

Pricing: Paid Website: http://www.zend.com/
OS Platforms:  Linux, Windows, Mac

Zend Studio is one of the best IDE available for PHP development. It has very powerful PHP and Javascript debugging, team collaboration and remote server tools. The Zend studio is one of the highest priced PHP IDEs, though it has a free version however that does not come with very good features. Using Zend Studio You can easily deploy your PHP application onto public or private cloud by using the built-in cloud deployment integration features. Zend Studio includes a fully working mobile app with source code. Use the code to learn how to create mobile apps or leverage it for your apps.

NetBeans IDE

Pricing: Free Website: http://netbeans.org/
OS Platforms:  Linux, Windows, Mac

Netbeans allows developer to quickly and easily develop desktop, mobile and web applications with Java, HTML5, PHP, C/C++ and more. NetBeans IDE is FREE, open source, and has a worldwide community of users and developers. The NetBeans PHP editor provides code templates and code generation tools, such as “getter and setter” generation, refactoring, such as “instant rename”, parameter tooltips, hints, and quick fixes, and smart code completion. NetBeans IDE supports the popular web frameworks like Zend Framework, Symfony2 Framework, Symfony1 Framework.

Aptana Studio PHP Editor

Pricing: Free Website: http://www.aptana.com/
OS Platforms:  Linux, Windows, Mac

Aptana Studio is developed on Eclipse platform and is very stable and powerful. It aids in developing HTML, CSS, JavaScript, PHP, and Ruby applications. Aptana Studio supports the latest HTML5 specifications. Also includes information about the level of support for each element in the major web browsers.

WAMP does not start

A lot of time you might face a trouble that WAMP will not start. The Wamp icon may be red or yellow prompting that there is some trouble in starting the WAMP properly. Sometime even the icon is green but the WAMP would not run even then.

What is WAMP?

Wamp is package of services (Apache, Mysql, etc.) running on your computer. All these services (Apache, Mysql, etc.) use certain ports to run. If the port required by a service is being already used by some other service, then the WAMP will give you a warning by making the WAMP icon appear either in red or orange color.

Solutions

How to solve Apache port conflict:

If the issue is related to the Apache port conflict, we can resolve it by changing the default Apache port (Port 80) to some other port number. To do so please follow the steps given below:

  • In the systems tray at the bottom right of your window left-click the orange WAMP icon.
  • Go to the Apache option.
  • You can see the httpd.conf  option. Left-click on it.
  • Search for a line that says “Listen 80” and change it to “Listen 81”.
  • Now left-click the orange WAMP icon and choose “Restart all services”.

httpconfig

If the WAMP icon turns green then you had the Apache port error and it has been resolved. But you will have to use http://localhost:81 as your URL instead of http://localhost.

If you don’t like to use http://localhost:81 as your URL then you have to find the application running on port 80. To do this please follow the steps given below:

  • In the systems tray at the bottom right of your window left-click the orange WAMP icon.
  • Go to the Apache option.
  • You can see the Service  option. Left-click on it.
  • Click “Test Port 80”.

testport80

A command prompt window will open. This window will show if the Port 80 is being used by Apache or not.

port-check

Now if some other application is running on port 80, we have to find it and close it. Follow the steps below:

  • Press Window+r and type cmd. Press Ok. This will open Command Prompt.
  • Type netstat -aon | findstr:80 and press enter button. This will show all the applications running on the port 80.
  • Here you can also see the PID of the application running on the port 80.

netstat

Now when you have found the culprit , the next step is to close the application running on port 80.

  • Right click on you taskbar. Click on the Task Manager option.
  • Click the details tab.
  • Here you can see the PID column. Search your culprit service.
  • Right click on the service and press End Task.

Once the conflicting application is stopped, you can now try to start the WAMP and it will hopefully work fine.

How to solve MySQL port conflict:

Apart from Apache port conflict MySQL port conflict is another common cause on WAMP not working. If you are facing any such issue please follow the following steps to resolve the issue.

  • Press Window+r and type cmd. Press Ok. This will open Command Prompt.
  • Type “Services.msc” and press enter.
  • Sort the columns by name and look for “wampmysqld” or  “wampmysqld64or “MySQL”.
  • If the status of the process is running, double-click it and press the “Stop” button on the dialog box which appears.
  • Click Ok.
  • On the System Tray left-click on the WAMP icon and press “Restart all services”.

How To: Fix WAMP MSVCR110.dll Not Found or Missing Errors

MSVCR110DLLThere are more than one ways to resolve the issue of missing MSVCR110.dll on WAMP  server. The most common error message which occur while installing WAMP is This application failed to start because msvcr110.dll was not found. Re-installing the application may fix this problem.

Some of the most common reasons for this error

  1. There might be an issue with Windows Registry.
  2. You PC might be infected with some Malware.
  3. There might be a hardware failure.
  4. You might be installing a program that might have corrupted the MSVCR110.dll

How to fix the error

  1. Download the Visual C++ Redistributable for Visual Studio 2012 Update 4 package and run it. This will replace/restore the msvcr110.dll with the most recent copy provided by Microsoft. You will need to select the download based on the version of Windows installed on your PC. For example: x86 (32-bit) or x64 (64-bit). This solution will resolve the issue most of the times. For downloading the Visual C++ Redistributable CLICK HERE
  2. Run a malware/virus scan with you antivirus. It’s even possible that the msvcr110.dll error you’re seeing is related to a hostile program that’s masquerading as the file. Running a malware/virus scan will resolve this issue.
  3. If you think you might have accidentally deleted the msvcr110.dll then you might find it in Recycle Bin.
  4. Repair your Windows installation. If the individual msvcr110.dll file troubleshooting advice above is unsuccessful, performing a startup repair or repair installation should restore all Windows DLL files to their working versions.

Notes

  1. Do not download msvcr110.dll from a “DLL Download” website. They might contain virus. Try to get form a legitimate source.
  2. If you cannot access Windows normally due to msvcr110.dll error, try restarting Windows in Safe Mode.

 

Parse.com Retrieving Objects Using PHP CURL

If you have already created and object, you can retrieve its records by sending a GET request to the object URL.

For this tutorial I will assume that you already have an Parse.com account. Follow the below mentioned steps to get an Application Id ans REST API key:

  1. Sign In to Parse.com
  2. Move to Dashobard
  3. Create a New App
  4. Copy Application ID, Client Key and REST API Key

The code below will send a PHP CURL GET request to REST API of Parse.  You have to place you Application ID and REST API Key with the placeholders. You can run this code on a PHP server

The response body is a JSON object containing all the user-provided fields, plus the createdAt, updatedAt, and objectId fields. A sample response body is shown below:

If the object you are retrieving have pointers to children,  then you can fetch child objects by using the include option. For example, to fetch the object pointed to by the “game” key:

 

Parse.com Create New Object Using PHP CURL

Parse.com is an external BaaS (Backend as a service) provider.

Parse.com provides REST API that lets you interact with Parse.com from anything that can send an HTTP request. In this tutorial we will send and HTTP request to Parse.com using PHP CURL.

This tutorial assumes that you have Parse.com account. Follow the below mentioned steps to create a Parse.com App and obtain Application Id.

  1. Sign In to Parse.com
  2. Move to Dashobard
  3. Create a New App
  4. Copy Application ID, Client Key and REST API Key

The code below will send a PHP CURL request to REST API of Parse. To create a new object on Parse, send a POST request to the class URL containing the contents of the object. You have to place you Application ID and REST API Key with the placeholders. You can run this code on a PHP server.

When the creation is successful, the HTTP response is a 201 Created and the Location header contains the object URL for the new object:

The response body is a JSON object containing the objectId and the createdAt timestamp of the newly-created object: