如何在URI中检索http或https

I need to do something based on either http or https. For example:

$https = strpos($_SERVER['REQUEST_URI'], 'https') !== false;
if ($https) { ?>
    <script type="text/javascript">
    var a = 'a';
    </script>
<?php } else { ?>
    <script type="text/javascript">
    var b = 'b';
    </script>
<?php } ?>

But this doesn't work. It always goes to the second option regardless the page I access is http or https. Is there any work around? Thanks in advance.

Try using if (isset($_SERVER['HTTPS'])) instead.

$_SERVER['REQUEST_URI'] only returns the path relative to the server root, not the domain or protocol. Besides, your code would fail if I were to access http://example.com/https-is-cool.

Instead, try:

$https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== "off";
if(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443){
    echo 'https';
}else{
    echo 'http';
}

or as a variable:

$https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? true : false;

I would agree with @MichaelBertwoski's comment that if you are simply trying to do this for javascript, do the detection in javascript like this.

if (window.location.protocol == 'https:') {
    var a = 'a';
} else {
    var b = 'b';
}

If you need the information in PHP you can use one of the other answers posted.