Frequently Asked Questions

Common issues and solutions for the PHP Authentication System

Quick Navigation

reCAPTCHA Configuration Issues Critical

Problem: reCAPTCHA not working or showing "Invalid domain" errors.

Solutions:
  1. For Local Development:
    Add localhost to your reCAPTCHA domains in Google reCAPTCHA Console.
    Domain: localhost Alternative: 127.0.0.1
  2. For Production:
    Add your server's IP address or domain name:
    Domain: yourdomain.com IP: 192.168.1.100 Universal (not recommended): 0.0.0.0/0
  3. Update .env file:
    Make sure your reCAPTCHA keys are correctly set:
    RECAPTCHA_SITE_KEY=your_site_key_here RECAPTCHA_SECRET_KEY=your_secret_key_here
Important: Never use 0.0.0.0/0 in production as it allows any domain to use your reCAPTCHA keys.

Domain & URL Configuration Important

Problem: Application URLs not working correctly, email links broken, or redirects failing.

Configuration Steps:
  1. Update .env APP_URL:
    # For local development APP_URL=http://localhost/your-project-folder # For production APP_URL=https://yourdomain.com
  2. Configure email URLs:
    Email verification and password reset links use APP_URL as base.
  3. Check virtual host configuration:
    Ensure your web server is configured to serve the application correctly.
Note: URL marking and SQL injection protection are not implemented in this version. Consider adding these for production use.

2FA Setup & Troubleshooting Critical

Problem: Cannot complete 2FA setup, QR code not showing, or codes rejected.

Checklist:
  1. Time Sync: Ensure your device time is in sync (enable automatic time). TOTP requires clock accuracy (<30s drift).
  2. Single Use Secret: Refreshing setup page invalidates the old preview secret (session regenerated). Scan the latest QR.
  3. Wrong Digits: Make sure you use the current 6-digit code (not recovery or old code).
  4. Already Enrolled: If you re-run setup, previous secret remains until new one is confirmed.
  5. Session Expired: If you logged in long ago, log out/in before enrolling (fresh CSRF + session).
No backup codes yet. Plan to add them under Planned Enhancements.

Password Re-Auth Gate (User 2FA) Important

Why required? Prevents a hijacked but unlocked session from silently adding 2FA (which attacker could capture) or disabling security factors.

Behavior:
  • Clicking "Enable 2FA" opens a password modal.
  • On success, a short-lived session flag user_2fa_reauth_passed is set.
  • Access to /2fa-setup is blocked without that flag (HTTP redirect back).
  • Flag cleared after successful enrollment or logout.
Consider adding an expiry (e.g., 5 minutes) for the re-auth flag in future.

Session & Cookie Security Info

Controls: Session regeneration after login, forced logout after 2FA enrollment, role-based gating.

  • Set SESSION_COOKIE_SECURE=true in production (HTTPS required).
  • Use SameSite=Strict to reduce CSRF surface.
  • Store minimal PII in session; user id + role + flags only.
  • Consider Redis or Memcached if scaling horizontally.
Ensure PHP session.save_path has proper permissions and not world-readable.

Session Variables Reference Info

Overview: The application uses isolated session keys to separate pre-auth states (verification / 2FA) from fully privileged sessions.

Key When Set Purpose Cleared
csrf_token First protected form CSRF protection Session end
pending_verification Post-register / login (unverified) Gate email verification On verification
user_email Verification workflow Resend context On verification
verification_attempts Verification resend Rate limiting Success / end
registration_time Registration Window control End
pending_2fa_user_id Password accepted (2FA enabled) Stage identity awaiting TOTP TOTP success / logout
pending_2fa_is_admin Same as above (admin) Marks admin pending flow TOTP success / logout
role Full login User vs Admin canonical role Logout
is_admin Full admin login Legacy flag Logout
admin_id Admin login Admin user id Logout
admin_username Admin login Display name Logout
user_id User login User id Logout
username User login Display name Logout
twofa_setup_secret 2FA enrollment start Proposed TOTP secret Enroll success / cancel
twofa_setup_uri 2FA enrollment Provisioning URI for QR Enroll success / cancel
force2fa_email_passed Admin email code success Permit TOTP setup After enrollment
user_2fa_reauth_passed User password modal success Permit TOTP setup (user) After enrollment
reauth_2fa_attempts User re-auth failures Throttle password prompts On success / end
Future: add expiry timestamps for re-auth & forced 2FA flags + IP/user-agent binding for higher assurance.

Rate Limiting & Attempt Counters Important

Scopes: Login attempts, forced admin 2FA email code attempts (max 3), password re-auth (e.g., 5), resend email verification, contact form, newsletter join.

Storage:

MongoDB attempts collection (pattern: key + window). You can add TTL index:

db.attempts.createIndex({"expiresAt":1},{expireAfterSeconds:0})

Idea: Add IP + User composite keys to slow credential stuffing.

Environment Variables Overview Info

See .env.example for full list. Highlights:

  • APP_URL Base URL for email links (verification/reset/2FA).
  • MONGODB_URI Connection string; keep secret.
  • MAIL_* SMTP credentials & debug level.
  • RECAPTCHA_SITE_KEY / SECRET_KEY Bot mitigation.
  • FORCE_ADMIN_2FA (bool) Enforce admin 2FA bootstrap.
  • SESSION_COOKIE_SECURE Force secure cookies when HTTPS.
  • LOG_LEVEL Adjust verbosity (error|warning|info|debug).
Missing a variable? Add it to .env, load with Dotenv before other bootstrapping.

Security & .htaccess Configuration Critical

Problem: Third-party resources blocked, CSP violations, or external API calls failing.

Understanding Security Rules:

The .htaccess file contains strict Content Security Policy (CSP) rules that only allow:

  • reCAPTCHA: Google's reCAPTCHA services
  • Bootstrap: CDN resources for styling
  • jQuery: JavaScript library
Adding New Third-Party Services:
  1. Identify the domain:
    Find the exact domain of the service you want to add.
  2. Update CSP header in .htaccess:
    Add the domain to the appropriate CSP directive:
    # Example: Adding Font Awesome script-src 'self' ... https://cdnjs.cloudflare.com; style-src 'self' ... https://cdnjs.cloudflare.com;
  3. Test the changes:
    Clear browser cache and test the functionality.
Security Warning: Only add trusted domains to prevent XSS attacks.

Debugging & Logging Info

Problem: No error logs, debugging information not available, or issues are hard to diagnose.

Enable Logging:
  1. Update .env file:
    APP_DEBUG=true LOGGING_ENABLED=true LOG_LEVEL=debug
  2. Check log files:
    Logs are typically stored in:
    /logs/app.log /logs/email.log /logs/recaptcha.log
  3. Email debugging:
    Increase mail debug level:
    MAIL_DEBUG_LEVEL=2 # 0=off, 1=client, 2=server
Production Note: Log file creation is set to zero by default for security. Always disable debugging in production.

Email Configuration Issues Important

Problem: Emails not sending, verification emails not received, or SMTP errors.

Email Setup:
  1. Gmail Configuration:
    MAIL_HOST=smtp.gmail.com MAIL_PORT=587 MAIL_USERNAME=your-email@gmail.com MAIL_PASSWORD="your-app-password" MAIL_ENCRYPTION=tls
  2. Generate App Password:
    For Gmail, use App Passwords instead of your regular password.
  3. Test email sending:
    Use the contact form or registration to test email functionality.
  4. Check spam folder:
    Verification emails might be marked as spam.
Tip: For production, consider using services like SendGrid, Mailgun, or Amazon SES for better deliverability.

Email Deliverability (SPF / DKIM / DMARC) Info

Issue: Emails land in spam or are silently dropped.

  1. SPF Record: Add your sending provider include (e.g., v=spf1 include:sendgrid.net ~all).
  2. DKIM: Enable and publish DNS TXT key from provider (SendGrid/Mailgun).
  3. DMARC: Start with p=none policy to monitor, then tighten.
  4. From Address: Use a verified domain email (avoid free mailbox for production).
  5. Consistency: Keep MAIL_FROM_NAME stable to build reputation.
Implementing all three increases trust and inbox rate.

MongoDB Database Issues Critical

Problem: Database connection errors, authentication failures, or collection access issues.

Database Setup:
  1. MongoDB Atlas Setup:
    Ensure your MongoDB Atlas cluster is properly configured:
    MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/database MONGODB_DATABASE=auth
  2. IP Whitelist:
    Add your server's IP to MongoDB Atlas Network Access.
  3. User Permissions:
    Ensure the database user has read/write permissions.
  4. Test Connection:
    Run the database diagnostics script to test connectivity.
Security: Never expose database credentials in client-side code.

MongoDB Indexing & Performance Important

Recommended Indexes:

db.users.createIndex({ email:1 }, { unique:true }) db.users.createIndex({ username:1 }, { unique:true }) db.users.createIndex({ is_admin:1 }) db.users.createIndex({ "force2fa_code_expires":1 }, { expireAfterSeconds:0 }) db.users.createIndex({ "password_reset_expires":1 }, { expireAfterSeconds:0 }) db.attempts.createIndex({ key:1, windowStart:1 })

TTL Note: Use date fields with TTL for automatic cleanup of transient tokens.

File Permissions & Access Issues Important

Problem: Permission denied errors, unable to write logs, or file access issues.

Required Permissions:
  1. Logs Directory:
    Ensure the logs directory is writable:
    chmod 755 /logs/ chmod 644 /logs/*.log
  2. Config Files:
    Protect sensitive configuration files:
    chmod 600 .env chmod 644 config/*.php
  3. Web Server User:
    Ensure the web server has access to required files.

Performance Optimization Info

Issue: Slow loading times, high server load, or timeout errors.

Optimization Tips:
  1. Enable PHP OPcache:
    Configure OPcache in your PHP settings for better performance.
  2. Database Indexing:
    Ensure proper indexes on frequently queried fields (email, username).
  3. Rate Limiting:
    The system includes rate limiting to prevent abuse.
  4. CDN Usage:
    Use CDNs for static assets like Bootstrap and jQuery.

Post-2FA Logout & Redirect Info

Behavior: After successful 2FA enrollment the system destroys the current session and redirects to login with a query flag (e.g., ?twofa_enabled=1) so the user authenticates under elevated security context.

Why: Prevents reuse of pre-2FA session cookies and enforces fresh TOTP usage on next login.

Tip: Display a flash message acknowledging success on the login page.

Planned / Optional Enhancements Important

  • 2FA Backup Recovery Codes
  • Trusted Device / Remember Browser (long-lived signed token)
  • Device & Login Activity Log (geo/IP)
  • Admin Audit Log (newsletter sends / user role changes)
  • Role-Based Access Expansion (RBAC matrix)
  • API Token / Personal Access Tokens (HMAC)
  • WebAuthn / Passkey Support
  • Password Breach Checking (HIBP k-Anonymity API)
Contributions welcome—open an issue or PR.

Common Installation Issues Critical

Problem: Installation errors, missing dependencies, or setup failures.

Prerequisites Checklist:
  • ✅ PHP 7.4 or higher
  • ✅ Composer installed
  • ✅ MongoDB PHP extension
  • ✅ OpenSSL extension
  • ✅ cURL extension
  • ✅ JSON extension
Installation Commands:
# Install dependencies composer install # Copy environment file cp .env.example .env # Configure your settings in .env file # Set up MongoDB connection # Configure email settings # Add reCAPTCHA keys

Getting Additional Help Info

If you're still experiencing issues after following this FAQ:

  1. Check the logs:
    Enable debugging and check log files for specific error messages.
  2. Browser Console:
    Check browser developer tools for JavaScript errors.
  3. Server Logs:
    Check Apache/Nginx error logs for server-side issues.
  4. Community Support:
    Create an issue on the project's GitHub repository with:
    • Detailed description of the problem
    • Error messages (with sensitive data removed)
    • Steps to reproduce the issue
    • Your environment details
Open Source: This project is open source! Contributions and improvements are welcome.