PHP websites behind Cloudflare
In plain PHP, $_SERVER['REMOTE_ADDR'] shows the address of Cloudflare, not the visitor. Your code also may not notice that the visitor used HTTPS. This guide shows two small functions that fix both problems.
Before you begin
- The PHP website works on your hosting. See Host a PHP website.
- The domain is active in Cloudflare and the proxy is on (orange cloud).
- Access to your website files in the File Manager or by SFTP.
Steps
Create a file named
cloudflare-helpers.phpin your project and paste this code:php<?php function visitor_ip(): string { return $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['REMOTE_ADDR'] ?? ''; } function request_is_https(): bool { if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') { return true; } if (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https') { return true; } $visitor = $_SERVER['HTTP_CF_VISITOR'] ?? ''; return strpos($visitor, '"scheme":"https"') !== false; }Include the file at the top of your pages, before any other code:
phprequire __DIR__ . '/cloudflare-helpers.php';Use
visitor_ip()wherever you used$_SERVER['REMOTE_ADDR'], for example in logs and contact forms.Use
request_is_https()to decide whether to redirect to HTTPS or to set secure cookies. Do not redirect when it returns true, or the page will loop.Open your website and check the result. If you want to test, print the two values on a temporary page, then delete that page.
Do not trust these headers on a site without the proxy
Anyone who reaches your server directly can send a fake CF-Connecting-IP header. Use visitor_ip() for logs and convenience, not as the only protection for an important decision.
Common mistakes
- Redirecting to HTTPS when
$_SERVER['HTTPS']is empty. Behind the proxy this value can be empty even for HTTPS visitors, so the page loops. - Using the visitor IP from the header on a domain where the proxy is off.
- Leaving a test page with header information on the server.
Need help?
Open a support ticket in the Client Area or contact [SUPPORT_CONTACT]. Tell us the page address and what you expected to see.
Related articles
Last reviewed
2026-10-29
