PHP Rules and Best Practices
1. PHP File Structure and Tags
- Use <?php ?> tags for PHP code.
- Use a single entry point for applications when possible.
- Ensure files start with <?php and avoid closing tag ?> at the end of pure PHP files to prevent trailing wh
2. Syntax and Semicolon Usage
- Every statement must end with a semicolon (;).
- Use consistent indentation (4 spaces recommended).
3. Case Sensitivity
- PHP keywords (e.g., if, else, while) are case-insensitive.
- Function names are case-insensitive, but class names and variable names are case-sensitive.
4. Variable Naming and Conventions
- Use meaningful variable names prefixed with $ (e.g., $userName).
- Follow camelCase or snake_case consistently across the project.
5. Commenting
- Single-line comments: // or #
- Multi-line comments: /* ... */
- Use PHPDoc style for functions and class documentation: /** ... */
6. Keeping Code DRY (Don't Repeat Yourself)
- Refactor repeated code into functions or classes.
- Use include/require or autoloading for reusable code.
7. Use of Functions and Classes
- Organize code into functions to improve readability and maintainability.
- Use namespaces and PSR-4 autoloading standards for class files.
- Follow PSR-1 and PSR-12 coding standards for PHP.
8. Security Best Practices
- Use prepared statements or parameterized queries to prevent SQL injection.
- Sanitize and validate all user input.
- Escape output to prevent Cross-Site Scripting (XSS).
- Use password_hash() and password_verify() for password handling.
- Store configuration and credentials outside the web root when possible.
9. Error Reporting and Handling
- During development, enable error reporting:
error_reporting(E_ALL); ini_set('display_errors', '1');
- In production, log errors instead of displaying them:
ini_set('display_errors', '0'); ini_set('log_errors', '1');
10. File Inclusion
- Use include_once and require_once to avoid multiple inclusions.
- Check file existence (file_exists) before including if necessary.
11. Sessions and Cookies
- Call session_start() before any output is sent.
- Use secure, HTTP-only cookies for session IDs.
12. Configuration Files (.env)
- Store sensitive data like database credentials in a .env file.
- Use libraries like vlucas/phpdotenv to load environment variables.
13. Version Control and Deployment
- Exclude vendor and configuration files with gitignore.
- Use Composer for dependency management.
- Follow a consistent branching and deployment strategy (e.g., Git Flow).
14. Testing
- Write unit tests using PHPUnit.
- Use continuous integration tools to run tests automatically.
15. Coding Standards and Style
- Follow PSR-12 coding standard: https://www.php-fig.org/psr/psr-12/
- Use a linter like PHP_CodeSniffer to enforce coding standards.