PHP phpinfo() Information Disclosure

Medium Risk Information Disclosure
phpphpinfoinformation-disclosureconfigurationsystem-information

What it is

The PHP application uses the phpinfo() function which exposes sensitive system information including configuration details, environment variables, loaded modules, and potentially sensitive data. This information can help attackers understand the system architecture and identify vulnerabilities.

// Vulnerable: phpinfo() exposing system information // Example 1: Direct phpinfo() call if (isset($_GET['debug'])) { // Dangerous: Exposes all system configuration phpinfo(); exit; } // Example 2: Diagnostic page function showSystemInfo() { echo '

System Information

'; // Dangerous: Full system disclosure phpinfo(INFO_ALL); } // Example 3: Error handling that exposes info function handleError($error) { if ($_GET['verbose'] === 'true') { echo 'Error details:
'; phpinfo(INFO_CONFIGURATION); echo '
' . print_r($_SERVER, true) . '
'; } } // Usage in production (dangerous) if ($isAdmin) { showSystemInfo(); // Still dangerous even with auth }
// Secure: Safe alternatives to phpinfo() // Alternative 1: Environment-controlled diagnostics function showSafeSystemInfo() { // Only allow in development environment if (getenv('APP_ENV') !== 'development') { throw new Exception('Diagnostic information not available'); } // Limit information exposure $safeInfo = [ 'php_version' => PHP_VERSION, 'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown', 'document_root' => $_SERVER['DOCUMENT_ROOT'] ?? 'Unknown', 'memory_limit' => ini_get('memory_limit'), 'max_execution_time' => ini_get('max_execution_time') ]; return $safeInfo; } // Alternative 2: Secure administrative interface class SecureSystemDiagnostics { private $allowedUsers = ['admin@example.com']; public function getDiagnosticInfo($userEmail) { // Validate user authorization if (!in_array($userEmail, $this->allowedUsers, true)) { throw new UnauthorizedAccessException('Access denied'); } // Return limited, safe information return [ 'timestamp' => date('Y-m-d H:i:s'), 'php_version' => PHP_VERSION, 'loaded_extensions' => get_loaded_extensions(), 'memory_usage' => memory_get_usage(true), 'memory_peak' => memory_get_peak_usage(true) ]; } public function logSystemEvent($event, $details) { // Secure logging instead of exposing information $logEntry = [ 'timestamp' => date('c'), 'event' => $event, 'details' => $details, 'user_ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown' ]; error_log(json_encode($logEntry)); } } // Alternative 3: Configuration-based approach function handleDiagnosticRequest() { // Check if diagnostics are enabled if (!defined('ENABLE_DIAGNOSTICS') || !ENABLE_DIAGNOSTICS) { http_response_code(404); exit('Not found'); } // Validate authentication if (!isValidAdminSession()) { http_response_code(401); exit('Unauthorized'); } // Return minimal diagnostic information $diagnostics = [ 'status' => 'healthy', 'version' => getApplicationVersion(), 'uptime' => getSystemUptime(), 'database_status' => checkDatabaseConnection() ]; header('Content-Type: application/json'); echo json_encode($diagnostics); } // Helper functions function isValidAdminSession() { return isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin'; } function getApplicationVersion() { return defined('APP_VERSION') ? APP_VERSION : '1.0.0'; } function checkDatabaseConnection() { try { // Test database connection $pdo = new PDO($dsn, $username, $password); return 'connected'; } catch (PDOException $e) { return 'disconnected'; } } // Secure usage try { $diagnostics = new SecureSystemDiagnostics(); $userEmail = $_SESSION['user_email'] ?? null; if ($userEmail) { $info = $diagnostics->getDiagnosticInfo($userEmail); // Process diagnostic information securely } } catch (Exception $e) { error_log('Diagnostic request error: ' . $e->getMessage()); // Handle error without exposing system details }

💡 Why This Fix Works

See fix suggestions for detailed explanation.

Why it happens

Developers call phpinfo() in production applications for quick diagnostics when troubleshooting issues, creating information disclosure vulnerabilities that expose sensitive system details. Common patterns include debug query parameters: if ($_GET['debug']) { phpinfo(); } allowing anyone knowing the parameter name to view system information, conditional debugging based on IP address: if ($_SERVER['REMOTE_ADDR'] === '10.0.0.1') { phpinfo(); } which becomes exposed when IP validation bypassed or internal networks compromised, and error handlers calling phpinfo() on exceptions: catch (Exception $e) { phpinfo(); echo $e; } displaying full configuration during errors. The phpinfo() output reveals extensive sensitive information: PHP version and configuration (php.ini settings including disabled functions, memory limits, file upload settings), server software versions (Apache/Nginx version, OpenSSL version, operating system details), loaded PHP extensions and their versions identifying potential vulnerable dependencies, environment variables containing API keys, database credentials, AWS access keys, file system paths revealing directory structure and application layout useful for path traversal attacks, database connection details (hostnames, usernames, potentially passwords if stored in environment), session configuration (cookie settings, session save paths, session handlers), mail server configuration (SMTP credentials), and security settings (allow_url_fopen, allow_url_include, disable_functions, open_basedir). Attackers exploit this information: identifying PHP version-specific vulnerabilities (CVEs for specific PHP versions), discovering disabled_functions lists to determine available functions for exploitation, finding upload_tmp_dir or session.save_path for temporary file attacks, extracting credentials from environment variables, mapping internal network topology from server details, and identifying security weaknesses like missing security extensions (Suhosin) or weak configurations (register_globals enabled in legacy systems).

Root causes

Using phpinfo() in Production Environments for Debugging

Developers call phpinfo() in production applications for quick diagnostics when troubleshooting issues, creating information disclosure vulnerabilities that expose sensitive system details. Common patterns include debug query parameters: if ($_GET['debug']) { phpinfo(); } allowing anyone knowing the parameter name to view system information, conditional debugging based on IP address: if ($_SERVER['REMOTE_ADDR'] === '10.0.0.1') { phpinfo(); } which becomes exposed when IP validation bypassed or internal networks compromised, and error handlers calling phpinfo() on exceptions: catch (Exception $e) { phpinfo(); echo $e; } displaying full configuration during errors. The phpinfo() output reveals extensive sensitive information: PHP version and configuration (php.ini settings including disabled functions, memory limits, file upload settings), server software versions (Apache/Nginx version, OpenSSL version, operating system details), loaded PHP extensions and their versions identifying potential vulnerable dependencies, environment variables containing API keys, database credentials, AWS access keys, file system paths revealing directory structure and application layout useful for path traversal attacks, database connection details (hostnames, usernames, potentially passwords if stored in environment), session configuration (cookie settings, session save paths, session handlers), mail server configuration (SMTP credentials), and security settings (allow_url_fopen, allow_url_include, disable_functions, open_basedir). Attackers exploit this information: identifying PHP version-specific vulnerabilities (CVEs for specific PHP versions), discovering disabled_functions lists to determine available functions for exploitation, finding upload_tmp_dir or session.save_path for temporary file attacks, extracting credentials from environment variables, mapping internal network topology from server details, and identifying security weaknesses like missing security extensions (Suhosin) or weak configurations (register_globals enabled in legacy systems).

Leaving phpinfo() Calls in Code After Development

Development and testing code containing phpinfo() statements gets committed to version control and deployed to production without removal, persisting information disclosure vulnerabilities indefinitely. Developers create temporary diagnostic scripts during development: <?php phpinfo(); ?> saved as info.php, test.php, or phpinfo.php in web root for quick configuration checks, then forget to delete these files before deployment. These scripts often have predictable names enabling automated discovery: attackers use tools scanning common filenames (phpinfo.php, info.php, test.php, i.php, pi.php) on discovered domains. Code comments containing phpinfo() may be uncommented accidentally: // phpinfo(); /* debugging */ becomes phpinfo(); /* debugging */ during editing, then commits include uncommented code. Feature branches or development branches merged to production contain debug code including phpinfo() calls added during troubleshooting but not removed before merge. Vendor directories or third-party code included in deployments may contain their own diagnostic scripts with phpinfo() calls that developers don't review. Legacy codebases accumulate debug code over years with multiple developers adding and forgetting phpinfo() diagnostics in various locations. Version control history may remove phpinfo() from current branch but file still exists on server if deployment doesn't clean removed files: previous info.php persists even after deletion from repository. The persistence of these files creates long-term exposure: automated vulnerability scanners continuously probe for phpinfo.php and similar files, successful discovery reveals current system state even as configuration evolves, and public disclosure of vulnerable endpoints (security advisories, vulnerability databases, Shodan searches) permanently exposes the application. Attackers discover these endpoints through: automated scanning, directory brute-forcing, robots.txt or sitemap.xml leaking diagnostic URLs, GitHub searches finding repository code with phpinfo() calls revealing likely production URLs, and historical web archives (Wayback Machine) showing previously accessible diagnostic pages.

Debug Pages or Diagnostic Endpoints that Call phpinfo()

Applications implement administrative interfaces, health check endpoints, or diagnostic dashboards that intentionally call phpinfo() without adequate access controls, exposing system information to authenticated users or exposing endpoints to public access through misconfiguration. Admin panels commonly include system information sections displaying phpinfo() output: /admin/system-info, /dashboard/diagnostics, /settings/php-info making sensitive details accessible to any authenticated user regardless of whether they need this information for legitimate administrative tasks. Health check or status endpoints designed for monitoring may expose excessive information: /health, /status, /_system checking application health but including phpinfo() output alongside metrics. Framework-specific diagnostic tools in development mode remain enabled in production: Laravel's /telescope, Symfony's profiler toolbar, Django debug toolbar equivalents for PHP frameworks exposing phpinfo()-like details. Custom-built diagnostic interfaces for developers may check environment but fail securely: if (APP_ENV === 'development') { phpinfo(); } becomes vulnerable when APP_ENV misconfigured or when attackers manipulate environment detection. API endpoints for infrastructure monitoring: GET /api/system/info returning JSON-formatted phpinfo() data for integration with monitoring tools but accessible without authentication or with weak API keys. Docker health checks or Kubernetes readiness probes accessing diagnostic endpoints that expose phpinfo() information. The problem compounds through architectural issues: microservices each implementing their own diagnostic endpoints multiplying exposure surface, API gateways proxying diagnostic endpoints making internal services accessible externally, service discovery mechanisms registering diagnostic endpoints in public service registries, and load balancer health checks accessing diagnostic URLs that may be exploitable. Access control failures enable exploitation: missing authentication allowing public access to supposedly internal diagnostic pages, insufficient authorization where any authenticated user accesses admin diagnostics, horizontal privilege escalation where regular users access admin endpoints through direct URL access or parameter manipulation, and session fixation or CSRF vulnerabilities allowing attackers to trigger phpinfo() calls through victim browsers. Documentation and API specifications inadvertently expose diagnostic endpoints: Swagger/OpenAPI specs listing all endpoints including diagnostics, README files or wiki pages documenting internal diagnostic URLs for developers, and infrastructure-as-code repositories revealing endpoint paths through configuration.

Missing Removal of Development/Testing Code in Production

Deployment processes lack proper build pipelines, code review, or cleanup procedures allowing development-only code containing phpinfo() to reach production environments. No distinction exists between development and production code: single codebase deployed to all environments without build process filtering debug code, missing conditional compilation or dead code elimination removing development utilities, and lack of separate debug/release builds common in compiled languages but often absent in interpreted language deployments like PHP. Deployment automation deploys entire codebases including test directories: /tests, /debug, /dev directories containing phpinfo() scripts deploy to production web servers with directory listing enabled or predictable paths. Configuration management tools deploy uniform configurations across environments: Ansible, Puppet, Chef recipes deploying same files to development and production without environment-specific filtering. Containerization amplifies the issue when development images deploy to production: Docker images built with debugging tools and phpinfo() scripts for development testing used in production deployments, environment variable differences intended to control behavior but phpinfo() calls remain present in code. Continuous integration/continuous deployment (CI/CD) pipelines lacking security gates: automated deployments pushing code immediately to production without scanning for information disclosure vulnerabilities, missing pre-deployment security checks that would identify phpinfo() calls, and insufficient integration testing failing to detect exposed diagnostic endpoints. Code review processes don't catch information disclosure: pull request reviews focusing on functionality not security implications, reviewers not recognizing phpinfo() as security issue in contexts that appear administrative, and approval processes missing security specialist review. Source code management issues contribute: .gitignore not excluding debug files allowing accidental commits, submodules or vendor dependencies containing phpinfo() diagnostics not reviewed during dependency updates, and monorepo structures where debug code from one service propagates to others. Emergency hotfix deployments bypass normal processes: urgent production fixes deployed directly without review or testing potentially including phpinfo() added during troubleshooting. The fundamental issue is treating security as post-deployment concern rather than development and deployment stage responsibility, lacking automated security controls in CI/CD pipelines that would prevent information disclosure vulnerabilities from reaching production.

Inadequate Access Controls on Administrative Functions

Administrative interfaces and diagnostic functions implement insufficient authentication, authorization, or network-level access controls allowing unauthorized users to access phpinfo() output. Authentication bypass vulnerabilities enable phpinfo() access: missing authentication checks on admin routes (/admin/phpinfo.php accessible without login), weak authentication implementations (hardcoded credentials, default passwords, credentials in source code), session management flaws (predictable session IDs, session fixation, lack of session expiration) allowing session hijacking to access authenticated admin areas. Authorization flaws permit privilege escalation: role-based access control (RBAC) not enforced on diagnostic endpoints allowing regular users to access admin functions, insecure direct object references enabling users to access other users' admin sessions or diagnostic data, horizontal privilege escalation through URL manipulation (/admin/phpinfo?user=1 changing to user=2), and vertical privilege escalation exploiting application logic flaws to gain admin rights. IP-based access controls implemented incorrectly: IP allowlists checked against X-Forwarded-For header which attackers spoof, localhost restrictions bypassed through SSRF vulnerabilities or DNS rebinding, private IP checks failing to account for IPv6 addresses or proxy configurations, and VPN/network-based restrictions assuming internal networks are trusted despite insider threats or compromised hosts. Authentication credentials exposed or weak: admin interfaces using HTTP Basic Auth with weak passwords discoverable through brute force or credential stuffing, API keys for diagnostic endpoints stored in client-side code or public repositories, JWT tokens for admin access using weak secrets enabling token forgery, and OAuth configurations with overly permissive scopes. Multi-factor authentication (MFA) not enforced: admin interfaces lacking MFA allowing credential compromise to fully compromise admin access, MFA implemented only for primary login but not for privileged actions like viewing phpinfo(), and MFA bypass vulnerabilities through backup authentication methods. Network segmentation failures: admin interfaces deployed on same servers as public web applications without network isolation, missing firewall rules restricting admin interface access to specific IP ranges or VPNs, cloud security groups overly permissive allowing 0.0.0.0/0 access to admin ports, and microservices exposing admin endpoints to service mesh without mTLS authentication. The root cause is defense-in-depth failure: relying on single control (like authentication) without layered security including network segmentation, authorization checks, audit logging, rate limiting, and anomaly detection that would provide multiple barriers preventing unauthorized phpinfo() access.

Fixes

1

Remove All phpinfo() Calls from Production Code

Audit entire codebase identifying and eliminating all phpinfo() function calls before production deployment, implementing automated checks preventing future introduction. Search codebase for phpinfo() usage: grep -r 'phpinfo(' --include='*.php' identifying all occurrences, use IDE find-in-files functionality searching entire project, and employ static analysis tools (PHPStan, Psalm, PHP_CodeSniffer) detecting phpinfo() calls. Remove phpinfo() statements from code: delete phpinfo() function calls completely rather than commenting out (commented code risks uncommenting), remove files whose sole purpose is phpinfo() display (info.php, test.php, phpinfo.php), and eliminate conditional phpinfo() calls including those in debug mode checks. Implement pre-commit hooks preventing phpinfo() commits: Git pre-commit hook script: #!/bin/bash; if git diff --cached --name-only | grep '\.php$' | xargs grep -l 'phpinfo('; then echo 'Error: phpinfo() detected'; exit 1; fi automatically rejecting commits containing phpinfo(). Add CI/CD pipeline security gates: configure continuous integration to fail builds containing phpinfo(), use security scanning tools (SonarQube, Snyk, Semgrep) detecting information disclosure patterns, and implement automated security tests checking for diagnostic endpoints. Create coding standards prohibiting phpinfo(): document in developer guidelines that phpinfo() is forbidden in production code, require code review checklist item confirming no information disclosure vulnerabilities, and train developers on information disclosure risks and secure alternatives. Search for equivalent information disclosure functions: also identify and remove var_dump(), print_r($_SERVER), get_defined_vars(), debug_backtrace(), and other functions exposing sensitive information. Remove diagnostic scripts from deployment: ensure deployment processes exclude test files (tests/, test.php, phpinfo.php), configure web server to deny access to common diagnostic filenames even if accidentally deployed, and use .htaccess or nginx.conf rules blocking access: <Files 'phpinfo.php'> Require all denied </Files>. Document removal in security checklist: maintain deployment checklist requiring verification of no phpinfo() presence, include security review gate before production deployment, and require sign-off from security team on releases. Monitor production for phpinfo() exposure: use external vulnerability scanning against production URLs testing for /phpinfo.php, /info.php, etc., implement internal monitoring checking for phpinfo() in application logs or error outputs, and subscribe to security advisories about information disclosure in your technology stack.

2

Use Environment-Specific Configuration to Disable Debug Functions

Implement environment-aware configuration ensuring debug functionality including phpinfo() access is strictly limited to non-production environments with safeguards preventing production exposure. Define environment constants or variables: use APP_ENV environment variable distinguishing production, staging, development environments, define constants in configuration: define('ENVIRONMENT', getenv('APP_ENV') ?: 'production'); ensuring default is secure (production), and validate environment configuration on application bootstrap throwing exceptions if misconfigured. Implement environment-based feature toggles: wrap all diagnostic functionality in environment checks: if (ENVIRONMENT === 'development') { /* allow phpinfo() access */ } else { throw new Exception('Not available'); }, use configuration files per environment (config/production.php, config/development.php) with debug features explicitly enabled only in development, and leverage framework environment configuration (Laravel's APP_DEBUG, Symfony's kernel.debug) properly configured for each environment. Disable dangerous functions in production php.ini: configure disable_functions = phpinfo,system,exec,passthru,shell_exec preventing phpinfo() calls from executing even if code remains, set display_errors = Off in production preventing accidental information disclosure through error messages, and configure error_reporting appropriately for environment (E_ALL in development, E_ALL & ~E_NOTICE in production with logging). Use separate codebases or branches: maintain development branch with debug features separate from production branch, implement build process stripping debug code during production compilation, and use dependency management separating development dependencies: composer require --dev phpunit/phpunit preventing development-only packages in production. Implement runtime environment detection with safeguards: check multiple indicators confirming environment (not just single variable), validate environment matches expected deployment (production code verifying it's running in production environment), and implement fail-secure defaults where environment detection failure defaults to most secure configuration. Use infrastructure-as-code for environment configuration: Terraform, CloudFormation, or Kubernetes manifests defining environment-specific settings preventing manual misconfiguration, immutable infrastructure approaches where production infrastructure cannot be modified to enable debug features without redeployment, and configuration management systems (Ansible, Puppet) enforcing environment-appropriate settings. Audit environment configuration: regularly review production environment variables and configuration files, implement automated tests verifying production configuration matches security requirements, and use configuration drift detection alerting on unexpected changes to environment settings. Implement least-privilege access to environment configuration: restrict who can modify production environment variables requiring approval workflow, store production environment variables in secrets management systems (AWS Secrets Manager, HashiCorp Vault) with access audit logging, and separate development/production access where developers cannot access or modify production environment configuration. Document environment configuration requirements: maintain runbook documenting required environment variables and their correct values for each environment, include configuration validation in deployment procedures, and train operations teams on security implications of environment misconfiguration.

3

Implement Proper Logging Instead of phpinfo() for Diagnostics

Replace phpinfo() usage with structured logging and monitoring solutions providing necessary diagnostic information without exposing sensitive system details. Implement structured application logging: use logging libraries (Monolog, Log4php) providing context-aware logging with configurable levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), log specific diagnostic information needed for troubleshooting: function logDiagnostic() { $logger->info('Diagnostic check', ['memory' => memory_get_usage(), 'time' => microtime(true)]); }, and include relevant context in logs without exposing full configuration. Configure centralized log management: send logs to centralized systems (ELK Stack, Splunk, Datadog, CloudWatch Logs) for analysis without exposing information in application, implement log aggregation collecting logs from multiple servers for comprehensive diagnostics, and use log correlation identifying issues across distributed systems. Log specific diagnostic metrics instead of full configuration: memory usage: memory_get_usage(), memory_get_peak_usage() tracking resource consumption, execution time measurements identifying performance bottlenecks, database query counts and slow query logging, cache hit/miss ratios monitoring caching effectiveness, and API response times for external service monitoring. Implement health check endpoints with limited information: create /health endpoint returning basic status: {"status": "healthy", "timestamp": "2024-01-01T00:00:00Z"} without sensitive details, include version information only: {"version": "1.2.3"} without full configuration, and implement deep health checks for authenticated monitoring: database connectivity check, cache availability check, external API availability without exposing credentials. Use application performance monitoring (APM): integrate APM tools (New Relic, AppDynamics, Dynatrace) providing detailed performance insights without phpinfo(), enable distributed tracing tracking requests across microservices, and use real user monitoring (RUM) understanding production performance from user perspective. Implement custom diagnostic functions returning safe information: function getSafeDiagnostics() { return ['version' => APP_VERSION, 'uptime' => getUptime(), 'health' => checkHealthStatus()]; } avoiding sensitive configuration exposure, create admin dashboard displaying curated metrics, and implement diagnostic CLI commands for server-side troubleshooting: php artisan diagnostics running on server with appropriate access controls. Log configuration changes: audit log when configuration values change, track who modified settings and when, and alert on unexpected configuration drift. Configure appropriate log retention: retain logs sufficient for troubleshooting and compliance but not excessive creating storage costs or retention liability, implement log rotation preventing unbounded growth, and use log anonymization removing PII before long-term retention. Secure log access: require authentication for log viewing interfaces, implement role-based access control on log data, encrypt logs in transit and at rest, and audit log access tracking who viewed sensitive diagnostic information. Implement exception logging with context: catch exceptions and log relevant context: catch (Exception $e) { $logger->error('Operation failed', ['exception' => $e->getMessage(), 'trace' => $e->getTraceAsString()]); } providing troubleshooting information without full system dump.

4

Restrict Access to Diagnostic Information with Authentication

Implement strong authentication and authorization protecting any legitimate diagnostic interfaces requiring system information access. Require authentication for all administrative endpoints: implement login system for admin interfaces using proven authentication libraries (OAuth 2.0, OpenID Connect, SAML), enforce strong password requirements (minimum length, complexity, password history), and require multi-factor authentication (MFA) for administrative access using authenticator apps (Google Authenticator, Authy) or hardware tokens (YubiKey). Implement role-based access control (RBAC): define admin roles with specific permissions (viewer, operator, administrator), restrict diagnostic information access to minimum required roles, and implement principle of least privilege ensuring users have only necessary permissions. Use session management best practices: generate cryptographically random session IDs using random_bytes(32), set secure session cookie flags: session.cookie_secure=1, session.cookie_httponly=1, session.cookie_samesite=Strict, implement session expiration with reasonable timeouts, and invalidate sessions on logout and password change. Implement network-level access controls: restrict admin interfaces to VPN-only access using firewall rules, configure IP allowlisting permitting only trusted IP ranges, and use separate admin subdomains or ports with restricted network access. Use API authentication for programmatic access: implement API keys for monitoring tools with limited scope, rotate API keys regularly and on compromise, and require API requests include authentication header: Authorization: Bearer {token}. Implement authorization checks on every request: verify authentication before processing any admin request, check user permissions for specific action being performed, and re-authenticate for sensitive operations (viewing phpinfo equivalents, modifying configuration). Audit admin access: log all authentication attempts (successful and failed) with timestamp, IP address, user agent, implement alerting on suspicious patterns (multiple failed logins, access from unusual locations), and maintain audit trail of who accessed what diagnostic information when. Use security headers protecting admin interfaces: Content-Security-Policy preventing XSS, X-Frame-Options preventing clickjacking, Strict-Transport-Security enforcing HTTPS. Implement rate limiting: limit authentication attempts preventing brute force (5 attempts per 15 minutes), implement progressive delays on failed attempts, and use CAPTCHA after multiple failed attempts. Consider certificate-based authentication for administrative access: require client TLS certificates for admin interface access, implement mutual TLS (mTLS) between monitoring tools and diagnostic endpoints, and use certificate pinning for critical administrative operations. Segregate administrative interfaces: deploy admin interfaces on separate servers/containers from public applications, use separate database credentials with read-only access for admin interfaces that only view data, and implement network segmentation isolating admin networks from public networks. Regularly review and audit access: quarterly review who has administrative access removing former employees and unnecessary access, audit authorization rules ensuring they match current security requirements, and perform penetration testing specifically targeting admin interface authentication and authorization.

5

Use Secure Administrative Interfaces for System Information

Develop purpose-built administrative dashboards providing necessary system information through secure interfaces with proper authentication, authorization, and information filtering rather than exposing raw phpinfo() output. Build custom admin dashboards: create administrative UI displaying curated system information (version, uptime, resource usage) without sensitive configuration, implement dashboard framework (Laravel Nova, Symfony EasyAdmin) providing secure admin interface foundation, and use admin UI libraries (AdminLTE, React Admin) for professional secure admin interfaces. Implement information filtering: display only necessary information for administrative tasks excluding sensitive data like credentials, connection strings, or internal IP addresses, create different views for different admin roles (viewer sees status, operator sees metrics, administrator sees configuration), and implement data masking showing partial information (database password as db_pass: ****). Use read-only diagnostic views: provide system information as read-only displays preventing accidental modification, implement separate configuration management interface with change control requiring approval, and use configuration-as-code approaches where configuration changes happen through version-controlled files not web UI. Integrate monitoring dashboards: embed Grafana dashboards showing system metrics without exposing configuration, use APM tool dashboards (New Relic, DataDog) providing performance insights, and create custom metrics dashboards displaying health status, response times, error rates, resource utilization. Implement secure configuration viewing: if configuration viewing is necessary, require elevated privileges with MFA verification, log all configuration views creating audit trail, and display configuration in sanitized format excluding secrets and credentials. Use secure transport for admin interfaces: enforce HTTPS for all admin interface access, implement HTTP Strict Transport Security (HSTS) preventing HTTP access, and use TLS 1.3 with strong cipher suites. Build diagnostic CLI tools for server-side access: create command-line tools for troubleshooting accessible only via SSH: php artisan system:info displaying safe diagnostic information when run on server with appropriate permissions, implement sub-commands for different diagnostic needs (php artisan system:health, php artisan system:metrics), and restrict CLI tool access to authorized system administrators with proper SSH key management. Integrate with existing admin tools: use phpMyAdmin, Adminer alternatives with proper authentication rather than custom database information display, integrate with server management panels (cPanel, Plesk) that implement security controls, and use configuration management tools (Ansible AWX, Puppet Enterprise Console) for viewing system state. Implement change management workflow: require approval for configuration changes with multi-person authorization, implement configuration change audit log tracking who changed what when, and use rollback capabilities allowing reversion of configuration changes. Document administrative interfaces: maintain documentation describing what information each admin interface provides and security controls protecting it, document who should have access to each admin function with business justification, and provide training for administrators on proper use of diagnostic interfaces. Regular security assessment: conduct periodic security reviews of admin interfaces, perform penetration testing targeting admin authentication and authorization, and scan admin interfaces for information disclosure and other vulnerabilities.

6

Regular Code Review to Identify Information Disclosure Risks

Establish systematic code review processes specifically checking for information disclosure vulnerabilities including phpinfo() usage and similar issues. Implement mandatory code review: require all code changes undergo peer review before merging using pull request workflow, assign security-focused reviewers familiar with information disclosure risks to reviews, and use review checklist including information disclosure check items. Create security-specific review guidelines: document common information disclosure patterns to watch for (phpinfo(), var_dump(), print_r() on sensitive data, error messages exposing stack traces), provide examples of secure alternatives to information disclosure anti-patterns, and train reviewers on identifying subtle information disclosure issues. Use automated code review tools: integrate static analysis security testing (SAST) tools in CI/CD pipeline (SonarQube, Semgrep, Snyk Code), configure rules detecting phpinfo() and similar function calls, and enable automated comments on pull requests identifying security issues. Implement security gates in deployment: require security team approval for production deployments, run automated security scans before deployment blocking releases with critical findings, and maintain security checklist validated before each release. Review third-party dependencies: audit vendor code and dependencies for information disclosure issues, check release notes and security advisories for dependencies, and use dependency scanning tools (npm audit, composer audit) identifying vulnerable dependencies. Conduct periodic security audits: schedule quarterly comprehensive code audits focusing on information disclosure, review admin interfaces and diagnostic endpoints specifically, and analyze application logs for accidental information exposure. Use threat modeling: identify sensitive information in application (credentials, API keys, user data, system configuration), map data flows showing where sensitive information moves through system, and review each flow for information disclosure risks. Implement security training: train developers on information disclosure vulnerabilities and impact, provide examples from real incidents demonstrating consequences, and include information disclosure in onboarding security training for new team members. Create reference implementations: maintain examples of secure diagnostic implementations, document approved patterns for troubleshooting and monitoring, and provide code snippets for common diagnostic needs avoiding phpinfo(). Review error handling: ensure exception handlers don't expose sensitive information in error messages, verify error pages use generic messages in production, and check that error logging captures necessary information without exposing it to users. Monitor for information disclosure in production: implement security monitoring detecting exposed diagnostic endpoints, use external vulnerability scanning checking for common information disclosure URLs, and subscribe to security mailing lists learning about new information disclosure vectors. Conduct red team exercises: simulate attacker reconnaissance attempting to discover system information, test whether automated scanners can discover diagnostic endpoints, and use findings to improve security controls and code review processes. Document review findings: track information disclosure issues discovered in code review, analyze trends identifying common mistakes requiring additional training, and measure improvement over time in information disclosure vulnerability discovery rate. Implement continuous improvement: retrospectively analyze security incidents involving information disclosure, update code review guidelines based on lessons learned, and share knowledge across development teams about information disclosure prevention.

Detect This Vulnerability in Your Code

Sourcery automatically identifies php phpinfo() information disclosure and many other security issues in your codebase.