Friday 6 February 2015

Towards RESTful PHP - 5 Basic Tips

What is REST?
REST is an architectural style, or set of conventions, for web applications and services that centers itself around resource manipulation and the HTTP spec. Web apps have traditionally ignored the HTTP spec and moved forward using a subset of the protocol: GET and POST, 200 OKs and 404 NOT FOUNDs. As we entered a programmable web of applications with APIs the decision to ignore HTTP gave us problems we’re still dealing with today. We have an internet full of applications with different interfaces (GET /user/1/delete vs. POST /user/delete {id=1}). With REST we can say /user/1 is a resource and use the HTTP DELETE verb to delete it. For more detail on REST check out wikipedia and “quick pitch“.

Tip #1: Using PUT and DELETE methods

In PHP you can determine which HTTP method was used with: $_SERVER['REQUEST_METHOD']; From web browsers this will be either GET or POST. For RESTful clients applications need to support PUT and DELETE (and ideally OPTIONS, etc.) as well. Unfortunately PHP doesn’t have $_PUT and $_DELETE variables like it does $_POST and $_GET. Here’s how to access the content of a PUT request in PHP:
  1. $_PUT  = array();  
  2. if($_SERVER['REQUEST_METHOD'] == 'PUT') {  
  3.     parse_str(file_get_contents('php://input'), $_PUT);  
  4. }  

Tip #2: Send Custom HTTP/1.1 Headers

PHP’s header function allows custom HTTP headers to be sent to the client. The HTTP/1.x header contains the response code from the server. PHP will, by default, send back a 200 OK status code which suggests that the request has succeeded even if it has die()’ed or a new resource has been created. There are two ways to change the status code of your response:
  1. header('HTTP/1.1 404 Not Found');  
  2. /* OR */  
  3. header('Location: http://www.foo.com/bar', true, 201); // 201 CREATED  
The first line is a generic way of setting the response status code. If your response requires another header, like the Location header to the resource of a ‘201 Created’ or ‘301 Moved Permanently’, placing the integer status code in the third parameter of header is a shortcut. It is the logical equivalent of the following example, which is easier to read at the cost of being an extra line of code.
  1. header('HTTP/1.1 201 Created');  
  2. header('Location: http://www.foo.com/bar');  

Tip #3: Send Meaningful HTTP Headers

Policy for deciding when it is appropriate to send each HTTP status code is a full post on its own and the HTTP spec leaves room for ambiguity. There are many otherresources on the net which provide insights so I’ll just touch on a few.
201 Created is used when a new resource has been created. It should include a Location header which specifies the URL for the resource (i.e. books/1). The inclusion of a location header does not automatically forward the client to the resource, rather, 201 Created responses should include an entity (message body) which lists the location of the resource.
202 Accepted allows the server to tell the client “yeah, we heard your order, we’ll get to it soon.” Think the Twitter API on a busy day. Where 201 Created implies the resource has been created before a response returns, 202 Accepted implies the request is ok and in a queue somewhere.
304 Not Modified in conjunction with caching and conditional GET requests (requests with If-Modified-Since / If-None-Match headers) allows web applications to say “the content hasn’t changed, continue using the cached version” without having to re-render and send the cached content down the pipe.
401 Unauthorized should be used when attempting to access a resource which requires authentication credentials the request does not carry. This is used in conjunction with www-authentication.
500 Internal Server Error is better than OK when your PHP script dies or reaches an exception.
In the Recess! Framework I use this StatusCodes class to provide named constants for all HTTP/1.1 status codes. Example usage:
  1. header(StatusCodes::httpHeaderFor(StatusCodes::HTTP_NOT_FOUND));  

Tip #4: Don’t Use $_SESSION

A truly RESTful PHP application should be entirely stateless- all requests should contain enough information to be handled without additional server side state. In practice this means storing authentication information in a cookie with a timestamp and a checksum. Additional data can also be stored in a cookie. In the event you need more than a cookie’s worth of data fall back to storing it in a central database with the authentication still in the cookie. This is how Flickr approaches statelessness.

Tip #5: Test with cURL or rest-client

cURL makes it easy to execute any HTTP METHOD on a resource URL. You can pass request parameters and headers as well as inspect response headers and data. The command line tool ‘curl’ is standard on many *nix distros. Windows users should check out MinGW/MSYS which supports cURL. EvenPHP has cURL functions which are enabled on most hosts (tp://us2.php.net/manual/en/curl.setup.php">php/curl install page).
cURL Example Usage & Common Parameters:
# curl -X PUT http://www.foo.com/bar/1 -d "some=var" -d "other=var2" -H "Accept: text/json" -I
-X [METHOD] Specify the HTTP method.
-d “name=value” Set a POST/PUT field name and value.
-H [HEADER] Set a header.
-I Only display response’s headers.
Alternatively, a free GUI to test REST interfaces is Java/Swing based rest-client. rest-client is scriptable and has support for JSON/XML.

Tip #6 - Use a RESTful PHP Framework

Frankly, developers shouldn’t have to worry about many of these low-level details of REST when writing PHP apps. REST is based on conventions and conventions, by nature, involve a lot of boilerplate. This was one of the motivating reasons for Recess, a REST PHP Framework. Recess has RESTful routing that makes creating friendly URLs that respond to PUT, POST, DELETE, & GET with ease. Check out this REST routing screencast for a preview of how it works or download Recess and have some fun!
Friday 30 January 2015

Core PHP vs PHP Framework




This article is not dealing with technical terms and concentrates to deliver the content simple. If you are a programmer let me tell you, why you should prefer Framework ahead of Core PHP for your projects. If you are a business guy let me tell you, why it is so important to insist your software vendor to develop your web applications and websites with PHP Framework.

The comparison between Core PHP and PHP Framework can be related to Mathematics.


  • To solve a complicated problem in scientific mathematics, you can either take a paper to work out, or you can use a scientific calculator to solve it.
  • Working out mathematics in a paper is like coding in Core PHP, tapping a scientific calculator is like coding in Framework.
So what do I mean?
Core PHP – Maths with Paper 
  • Best student can solve the problem in few steps. Accuracy level – 75% to 100%.
  • Average student may or may not solve the problem, he will write down few more steps to solve the same problem. Accuracy level – 50% to 75%.
  • Poor student cannot solve the problems. Still he will write down, lot and lot of steps to solve the problem. Accuracy level – 0% to 50%.
Framework – Scientific Calculator
  • Every student can solve the problem with 100% accuracy, once they learnt how to use the calculator.
  • The predefined formulas in the calculator will provide you accurate results faster for any problem.
Problem with Core PHP
Core PHP becomes complicated, when people start writing their own logic in it.
One can bring the output in few lines of code, where the other can take a few hundred of lines to bring the same. Both of them cannot read each other’s code. So the problem starts here, that is inconsistency.
Why choose Framework?
Framework assures reliability, consistency and a big time-saver. It has rich set of functionalities, so you don’t need to reinvent the wheel again and again. You will have almost all the functionalities to develop a PHP web application. Since it has been developed in OOPS, you can extend the existing functionality and create your own to have a full control over the application. Framework will not let you to write bad code, unless you purposely do it. When you work as a team, integrating your entire module becomes very easier, also it helps a lot in understanding each other’s code.
When you start developing a project, there are a lot of things, which you have to take care about, but we know only half of the things in it. Framework does everything for you, so you can be assured that your application is clean and safe. Inputs can be sanitized easily. MVC is one of the key functionality of Frameworks, separation of logics from views is a very good practice.
Modification Projects
We all know that the client will surely come back to us one day to enhance the website with lot of his innovative requirements. If the project was done in Core PHP, you will have to say no for 50% of his new requirements, or simply you can tell him that the project is expired. But if the project was done is Framework, the beauty of Framework can be witnessed here. All you have to do is a cakewalk and give the updated project back to the client. I can assure this to you with the personal experiences I had.
Is Core PHP that bad?
No, not at all. Core PHP helps you to understand the logics behind framework. Your logical thinking can be improved with Core PHP. The Core PHP becomes bad only when it goes to a bad programmer’s desk. Don’t dive into Framework without learning or coding in Core PHP. Please make sure that you read the full documentation before you start coding in Framework, writing Core PHP inside Framework has become common nowadays, it’s an insult to Frameworks.

Innoppl suggests its clients to prefer frameworks for their web applications. Choosing a framework depends upon the requirement of the project, will explain you about the functionalities and unique features of frameworks and how should you pick a framework in upcoming blogs.