如何在PHP中获取完整URL?

2021年3月13日16:05:02 发表评论 651 次浏览

PHP程序可获取当前正在运行的页面的完整URL

以下是获取当前运行页面的完整URL的几个步骤:

  • 创建一个PHP变量, 它将以字符串格式存储URL。
  • 检查服务器是否启用了HTTPS。如果已启用, 则在URL字符串后附加" https"。如果未启用HTTPS, 则在URL字符串后附加" http"。
  • 在网址后附加常规符号, 即"://"。
  • 附加服务器的HTTP_HOST(我们请求的主机, 例如www.google.com, www.yourdomain.com等)。
  • 将REQUEST_URI(我们请求的资源, 例如/index.php等)附加到URL字符串。

注意:使用isset()函数检查是否启用了HTTPS。 isset()函数用于检查变量是否存在。

HTTPS的状态保存在全局变量$ _SERVER [‘HTTPS’]中。因此, 在isset()函数中使用$ _SERVER [‘HTTPS’]用于检查它是否存在。这将告诉我们是否启用了HTTPS。检查$ _SERVER ['HTTPS']的值。如果它是" on", 则启用HTTPS, 我们必须在URL后面附加" https"。

程序1:

<?php
// Program to display URL of current page.
  
if (isset( $_SERVER [ 'HTTPS' ]) && $_SERVER [ 'HTTPS' ] === 'on' )
     $link = "https" ;
else
     $link = "http" ;
  
// Here append the common URL characters.
$link .= "://" ;
  
// Append the host(domain name, ip) to the URL.
$link .= $_SERVER [ 'HTTP_HOST' ];
  
// Append the requested resource location to the URL
$link .= $_SERVER [ 'REQUEST_URI' ];
      
// Print the link
echo $link ;
?>

输出如下:

https://ide.lsbin.org/

程式2:

<?php
// Program to display current page URL.
  
$link = (isset( $_SERVER [ 'HTTPS' ]) && $_SERVER [ 'HTTPS' ] === 'on' ?
                 "https" : "http" ) . "://" . $_SERVER [ 'HTTP_HOST' ] . 
                 $_SERVER [ 'REQUEST_URI' ];
  
echo $link ;
?>

输出如下:

https://ide.lsbin.org/

上面代码的输出是https://ide.lsbin.org/, 而不是https://ide.lsbin.org/index.php。为了解决此问题, 需要将$ _SERVER ['REQUEST_URI']替换为$ _SERVER ['PHP_SELF']

程式3:显示当前正在执行的PHP文件URL

<?php
// Program to display complete URL    
      
if (isset( $_SERVER [ 'HTTPS' ]) && 
             $_SERVER [ 'HTTPS' ] === 'on' )
     $link = "https" ;
     else
         $link = "http" ;
  
// Here append the common URL 
// characters.
$link .= "://" ;
      
// Append the host(domain name, // ip) to the URL.
$link .= $_SERVER [ 'HTTP_HOST' ];
      
// Append the requested resource
// location to the URL
$link .= $_SERVER [ 'PHP_SELF' ];
      
// Display the link
echo $link ;
?>

输出如下:

https://ide.lsbin.org/index.php

计划4:

<?php
// Program to display complete URL
  
$link = (isset( $_SERVER [ 'HTTPS' ]) && $_SERVER [ 'HTTPS' ]
                 === 'on' ? "https" : "http" ) . "://" .
           $_SERVER [ 'HTTP_HOST' ] . $_SERVER [ 'PHP_SELF' ];
  
// Display the complete URL
echo $link ;
?>

输出如下:

https://ide.lsbin.org/index.php

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: