这是可能的PHP协议基地网址

So - I have made a website with php includes in my header I have the following

<?php
$protocol = (!empty($_SERVER['HTTPS'])) ? 'https' : 'http';
$path = $protocol . '://domain.com/';
?>

but for some reason when I put www. in the URL bar, it breaks the site I even have a 301 direct in cpanel

is there a way to add www or no www to this?

It's possible to have a function for absolute http(s) path, the best way is check if server responses as HTTP or HTTPS and rewrite the php code according to new path...

check.php

<?php
  // Checking for HTTP or HTTPS
  function check_protocol() {
    $isSecure = false;
    if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') {
      $isSecure = true;
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && strtolower($_SERVER['HTTP_X_FORWARDED_SSL']) == 'on') {
      $isSecure = true;
    }
    return $isSecure;
  }
  $protocol = check_protocol() ? 'https://' : 'http://';
  $host = $protocol . $_SERVER['HTTP_HOST'];
?>

Usage is simple:

<?php
  include("check.php");
  echo $host;
  // it prints http://www.example.com or https://www.example.com
?>

or using the absolute path thanks to $_SERVER['DOCUMENT_ROOT']:

<?php
  include($_SERVER['DOCUMENT_ROOT'] . "/php/check.php");
  echo $host;
  // it prints http://www.example.com or https://www.example.com
?>

In addition to this may be useful a redirect using .htaccess if the server is hosted on Apache server...

I found useful this rule for my .htaccess:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

This rule may not work on different server configuration... read this thread for getting more info about the most different sever configuration...

I hope this helps.