A modern PHP example
Work in progress
There are thousands PHP tutorials out there, an new ones coming out every day. Sadly, but many of them only contribute to PHP's bad reputation, never adhering to basic coding standards or even basic security guidelines.
Goals
My aim is to provide a reference plain PHP code example, that adheres to many important standards and practices that are obligatory in the modern programming:
- security is the main concern. And - I gave to stress on - the persistence in following the security rules; there should never be an excuse for not applying the usual security measure
- error reporting is very important but also it is very important to do it the right way
- modular structure is often forgotten, yet it's a thing that has a thousand applications:
- it makes your code portable, easily movable across different servers, or even allows to use the same code on many different sites
- it makes your code much more readable
- it makes your code more maintainable, allowing painless improvement or extension in the future
- input data validation shouldn't be confused with security. It just greatly improves both user's and programmer's experience, and therefore gets obligatory nowadays. Instead of just silently bypassing wrong data, an error must be articulated to the calling party.
My main goal however, my deepest desire is to show that a properly written code is no more complex than quick and dirty solutions, but on the contrary, being simpler and easier to write and read.
Code structure
Each generic PHP script must be split into four parts:
- Initialization (usually it's done in a separate file that's either includes the current script, or being included into it)
- Input data validation (if there is any input)
- Data manipulation
- Output (if any)
Even modern frameworks follow this separation, although never within the same file, but these parts always can be distinguished in the code.
CRUD lifecycle
Each generic PHP script that interactively processes user data, such as a registration form, should follow the below structure
- check if the form was sent
- if so, validate input
- if all input is correct
- save to database
- redirect
- exit
- if there were errors, create error messages
- display the HTML page with a form
- if there are error messages, display them in the form
- if there is input data: display it in the form
Source code: https://github.com/colshrapnel/modern_raw_php_examle
Add a comment
Please refrain from sending spam or advertising of any sort.
Messages with hyperlinks will be pending for moderator's review.
Markdown is now supported:
>
before and an empty line after for a quote