Overview
S-PHP provides built-in security features to protect your application from common vulnerabilities including CSRF attacks, XSS attacks, and session hijacking.CSRF Protection
Cross-Site Request Forgery (CSRF) protection prevents unauthorized commands from being transmitted from a user that the web application trusts.Generating CSRF Tokens
Use thecsrf() function to generate a hidden input field with a token:
How It Works
Thecsrf() function:
- Checks if a token exists in the session
- Generates a new token using
random_bytes(32)if needed - Stores the token in
$_SESSION['csrf_token'] - Outputs a hidden input field with the token
Validating CSRF Tokens
Validate the token on form submission:validateCsrfToken()
The validation function uses timing-safe comparison:hash_equals()?
- Prevents timing attacks
- Compares strings in constant time
- More secure than
===for sensitive comparisons
Complete Example
XSS Protection
Cross-Site Scripting (XSS) protection prevents malicious scripts from being injected into your pages.sanitizeHtml()
ThesanitizeHtml() function cleans user input while preserving safe HTML:
Allowed HTML Tags
By default, these tags are allowed:Security Features
1. Removes dangerous tags:Array Support
Sanitize arrays recursively:When to Use sanitizeHtml()
Use when:- Accepting rich text from users (blog posts, comments)
- Displaying HTML content from untrusted sources
- Storing user-generated HTML in the database
- Displaying plain text (use
htmlspecialchars()instead) - Working with JSON or API data
- The data doesn’t contain HTML
Example: Blog Comment System
Session Security
Automatic Session Start
S-PHP automatically starts sessions:Session Best Practices
1. Regenerate session ID on login:Input Validation
Email Validation
URL Validation
Integer Validation
Error Handling
Error Reporting Configuration
S-PHP configures error reporting on startup:Fatal Error Handler
Automatically catches fatal errors:Security Checklist
- Use
csrf()in all forms - Validate CSRF tokens on form submission
- Sanitize user input with
sanitizeHtml() - Use
htmlspecialchars()for plain text output - Validate email, URL, and integer inputs
- Regenerate session ID on login
- Clear sessions on logout
- Use prepared statements for database queries
- Never store passwords in plain text
- Use HTTPS in production
- Set secure and httpOnly flags on cookies
- Implement rate limiting for sensitive operations