PHP - replace http with https in URL

PHP - replace http with https in URL

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Switching from HTTP to HTTPS in PHP URLs

Manipulating URLs based on user input is a common requirement in web applications, but it introduces immediate security considerations that go beyond simple string manipulation. The core task—taking a URL like http://google.com and converting it to https://google.com when a checkbox is checked—is straightforward syntax work. However, the architecture of how you handle this data determines whether your application remains secure or inadvertently exposes sensitive information.

The provided source material presents a basic scenario where a developer checks for the presence of a POST variable named https and then attempts to modify the protocol of a hardcoded URL string. While this approach works in isolation for simple redirect headers, it is insufficient for building robust web applications that handle user data or generate links dynamically.

String Manipulation vs. Structured Parsing

In PHP, changing http:// to https:// can be achieved via string replacement functions like str_replace(). You could write logic that checks $_POST['https'] and then executes $url = str_replace('http://', 'https://', $url);. This method relies on the assumption that the input is clean and that the URL structure remains consistent.

However, relying on string replacement for protocol switching is brittle. It fails if the URL contains HTTP:// in uppercase or mixed case, which PHP treats as distinct strings unless you use case-insensitive regex. Furthermore, this approach does not validate whether the target domain actually supports HTTPS. If a user submits a form to switch to https://, but the destination server has not configured an SSL certificate, the browser will display a security warning.

The Security Implications of User-Controlled Protocols

A more significant issue with the pattern shown in the source code is the reliance on client-side state ($_POST) to dictate server-side behavior regarding security protocols. In modern development practices, we generally avoid asking users to toggle between insecure and secure connections based on a checkbox. This creates a confusing user experience where the security level depends on a form submission rather than the site's default configuration.

If you must support this functionality—for instance, in a legacy system or a specific feature request—the implementation should validate the destination URL against your own ruleset. You should never blindly accept an https flag and assume the target is safe. Additionally, if you are redirecting users, ensure that you do not strip query parameters or fragments during the protocol switch, as this can lead to data loss.

Implementing a Robust Solution

A cleaner approach involves using PHP's built-in URL parsing functions rather than raw string replacement. The parse_url() function combined with str_replace() on specific components allows for more precise control. However, the most secure method is often to use a helper function that normalizes the URL first.

Consider a utility function that accepts a base URL and an optional flag:

function getSecureUrl($url, $forceHttps = false) {
    if ($forceHttps) {
        // Use parse_url to ensure we only touch the scheme part
        $parsed = parse_url($url);
        
        // Reconstruct the URL with the https prefix
        return (isset($parsed['scheme']) ? 'https' : 'http') . '://' 
               . ($parsed['host'] ?? '') . 
               (isset($parsed['path']) ? $parsed['path'] : '') .
               (isset($parsed['query']) ? '?' . $parsed['query'] : '');
    }
    
    return $url;
}

// Usage based on the form input
$url = 'http://google.com';
if (!empty($_POST['https'])) {
    $url = getSecureUrl($url, true);
}

This pattern ensures that you are explicitly constructing the URL rather than relying on fragile string matching. It also handles cases where the original URL might be missing a scheme or contains special characters that need preserving.

When to Use LaravelCompany Resources

If you are building this feature within the Laravel ecosystem, the built-in str() helpers and Url facade provide cleaner abstractions. For more complex routing scenarios involving protocol switching, consulting resources like https://laravelcompany.com can offer insights into best practices for handling secure redirects within modern PHP frameworks. These resources often detail how to handle SSL termination at the load balancer level versus configuring it per application instance.

Final Considerations on Mixed Content

Regardless of the implementation method, you must be aware of "mixed content" warnings. If your main site is served over HTTPS but you inject a link pointing to an HTTP version of a resource (or vice versa), browsers will block the non-secure asset to protect user data. When switching protocols based on form input, ensure that the final destination matches the security context of the current page. If the user lands on https://yoursite.com but the script generates an http://google.com link, modern browsers may flag this as a downgrade attack. Always validate that the resulting URL aligns with the expected security posture of your application.

Our network