Php get url http or https

PHP Получить протокол URL сайта – http vs https

В SSL, не сервер автоматически конвертирует URL-адрес в https, даже если URL-адрес привязки использует http? Нужно ли проверять протокол?

Это не автоматическое. Ваша верхняя функция выглядит нормально.

Я знаю, что уже поздно, хотя есть гораздо более удобный способ решить эту проблему! решения, показанные выше, довольно беспорядочны, и если кто-то должен когда-либо проверять это, я бы это сделал:

$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://'; 

или даже без каких-либо условий, если вы не любите

$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,strpos( $_SERVER["SERVER_PROTOCOL"],'/'))).'://'; 

Посмотрите на $_SERVER[«SERVER_PROTOCOL»]

if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') < $protocol = 'https://'; >else < $protocol = 'http://'; > 
$scheme = $_SERVER['REQUEST_SCHEME'] . '://'; 

Для любой системы, кроме IIS, этого достаточно для определения собственного URL-адреса сайта:

$siteURL='http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['HTTP_HOST'].'/'; 
$siteURL='http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'].'/'; 

зависит от того, что вы точно хотите: HTTP_HOST и SERVER_NAME

Читайте также:  Java from integer to int

Поскольку номер порта тестирования не является хорошей практикой по моему мнению, мое решение:

define('HTTPS', isset($_SERVER['HTTPS']) && filter_var($_SERVER['HTTPS'], FILTER_VALIDATE_BOOLEAN)); 

Константа HTTPS возвращает TRUE если $_SERVER[‘HTTPS’] установлен и равен «1», «true», «on» или «yes». Возвращает FALSE в противном случае.

Используйте эту переменную сервера для получения сведений о протоколе:

 $scheme = $_SERVER['REQUEST_SCHEME'] . '://'; echo $scheme; //it gives http:// or https:// 

Обратите внимание, что эта переменная сервера ненадежна. Для получения дополнительной информации посмотрите: надежна ли функция $ _SERVER [‘REQUEST_SCHEME’]?

$protocal = 'http'; if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || $_SERVER['HTTPS'] == 'on') echo $protocal; 

В случае прокси-сервера SERVER_PORT может не дать правильное значение, так что это то, что сработало для меня –

$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443 || $_SERVER['HTTP_X_FORWARDED_PORT'] == 443) ? "https://" : "http://" 

сделал функцию, используя ответ Rid Iculous , который работал в моей системе.

Я протестировал большинство проголосовавших answe r, и это не сработало для меня , я закончил использование:

$protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://'; 

это лучшее решение для https или http:

Но не может отображать https или http, поэтому он используется только для ссылки на ваш контент сайта, например изображение и т. Д.

если вы хотите перенаправить свой сайт в https, добавьте этот код в файл .htaccess:

 RewriteCond % '"scheme":"http"' RewriteRule ^(.*)$ https://www.your-domain.com$1 [L]  

Измените http://www.your-domain.com своим именем dowmain.

Вот как я это делаю … это короткая версия, if else версия ответа Рида Икулеса

$protocol = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on' || $_SERVER['HTTPS'] === 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ? 'https' : 'http'; 

Источник

How to Check Whether a URL is Using HTTP or HTTPS in PHP

Learn how to determine the protocol of a URL in PHP using various methods, including $_SERVER[‘HTTPS’] variable, parse_url() function, strpos() function, $_SERVER[‘REQUEST_URI’] variable, and get_headers() function.

  • Using $_SERVER[’HTTPS’] Variable
  • Using parse_url() Function
  • Using strpos() Function
  • Using $_SERVER[’REQUEST_URI’] Variable
  • Using get_headers() Function
  • Other helpful code examples for checking the URL protocol in PHP
  • Conclusion
  • How to check HTTP or HTTPS in URL in PHP?
  • How do you check if a site is http or HTTPS?
  • How to check if HTTPS is enabled in PHP?
  • How do I know if my URL is http?

If you’re a web developer, it’s important to know whether a URL is using HTTP or HTTPS protocol. It not only affects the security and functionality of your application but also impacts its SEO. In this blog post, we will discuss several methods for checking whether a URL is using HTTP or HTTPS protocol in PHP.

Using $_SERVER[’HTTPS’] Variable

The $_SERVER[’HTTPS’] variable is a built-in PHP variable that can be used to determine if the URL is using HTTPS protocol. If the variable is set to “on”, then the URL is using HTTPS. Otherwise, it’s using HTTP. Here’s an example code that demonstrates how to use this variable:

if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')  echo "This URL is using HTTPS"; > else  echo "This URL is using HTTP"; > 

Using parse_url() Function

The parse_url() function in PHP can be used to parse a URL and return an associative array of its components, including the scheme (HTTP or HTTPS). Here’s an example code that demonstrates how to use this function:

$url = "https://www.example.com"; $parsed_url = parse_url($url); if ($parsed_url['scheme'] === 'https')  echo "This URL is using HTTPS"; > else  echo "This URL is using HTTP"; > 

Using strpos() Function

The strpos() function in PHP can be used to check if a URL starts with “http://” or “https://”. If the function returns 0, then the URL starts with “https://”. Otherwise, it starts with “http://”. Here’s an example code that demonstrates how to use this function:

$url = "https://www.example.com"; if (strpos($url, "https://") === 0)  echo "This URL is using HTTPS"; > else  echo "This URL is using HTTP"; > 

Using $_SERVER[’REQUEST_URI’] Variable

The $_SERVER[’REQUEST_URI’] variable can be used to get the current URL and determine its protocol. Here’s an example code that demonstrates how to use this variable:

$current_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; if (strpos($current_url, "https://") === 0)  echo "This URL is using HTTPS"; > else  echo "This URL is using HTTP"; > 

Using get_headers() Function

The get_headers() function in PHP can be used to check if a URL exists and its status code. To check if a URL is using HTTPS, look for “https” at the beginning of the URL. Here’s an example code that demonstrates how to use this function:

$url = "https://www.example.com"; $headers = get_headers($url); if (strpos($headers[0], "200") !== false && strpos($url, "https://") === 0)  echo "This URL is using HTTPS"; > else  echo "This URL is using HTTP"; > 

Other helpful code examples for checking the URL protocol in PHP

In php, php check whether the url is http or https code example

if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') $link = "https"; else $link = "http";

Conclusion

In this blog post, we have discussed several methods for checking whether a URL is using HTTP or HTTPS protocols in PHP. These methods include using the $_SERVER[’HTTPS’] variable, parse_url() function, strpos() function, $_SERVER[’REQUEST_URI’] variable, and get_headers() function. It’s important for web developers to understand the protocol of a URL, as it can impact the security and functionality of their applications. We hope this blog post has been informative and helpful for those looking to check the protocol of a URL in their PHP applications.

Источник

Get Full URL & URL Parts In PHP (Simple Examples)

Welcome to a quick tutorial on how to get the full URL and URL parts in PHP. Need to get the path, base, domain, or query string from the URL? In Javascript, we can pretty much get all this information with just one line of code. But sadly in PHP, things are a little… backward.

  • To get the full URL in PHP – $full = (isset($_SERVER[«HTTPS»]) ? «https://» : «http://») . $_SERVER[«HTTP_HOST»] . $_SERVER[«REQUEST_URI»];
  • To remove the query string from the full URL – $full = strtok($full, «?»);

That should cover the basics, but if you need more specific “URL parts” – Read on for more examples!

TLDR – QUICK SLIDES

How To Get Full URL & URL Parts In PHP

TABLE OF CONTENTS

URL BASICS

All right, let us start with some “boring” basic URL parts. Yep, this stuff is important if you are new.

THE VARIOUS URL PARTS

  • Protocol – HTTP, HTTPS, FTP, WS, WSS, and whatever else.
  • Host – Better known as the “website address” to the non-technical folks.
  • Port – Usually left out. Commonly understood to be 80 for HTTP, 443 for HTTPS, and 21 for FTP.
  • Path – Beginners usually mistake this to be the “folder”, but it’s really not. I.E. The path can be virtual, not an actual physical folder.
  • File – Yes, the physical file name.
  • Query String – Extra information and parameters.

I know, it’s kind of ironic. The URL is supposed to be “easily understood” by humans, but there are so many parts to it.

GET FULL URL & URL PARTS

Now that you know the individual parts of a URL, let us now walk through how to obtain the full URL and the “common parts” using PHP.

1) URL PARTS IN PHP

2) GETTING THE FULL URL

 // (A4) THE PATH, FILE NAME, AND QUERY $url .= $_SERVER["REQUEST_URI"]; // (A5) INCLUDE QUERY STRING? if ($query===false) < $url = strtok($url, "?"); >// (A6) THE FULL URL return $url; > // (B) GET CURRENT URL echo getFullURL(true); // WITH QUERY echo getFullURL(); // WITHOUT QUERY

This is pretty much the “expanded version” of the introduction snippet, packaged into a function for your convenience.

3) COMMON URL PARTS

As for the “rest of the parts” that are not included in $_SERVER , we will need to do some mix-and-match on our own. Here are a few of the common ones.

PROTOCOL & HOST

// (A) PROTOCOL + DOMAIN $host = isset($_SERVER["HTTPS"]) ? "https://" : "http://" . $_SERVER["HTTP_HOST"] ; echo $host;

PATH ONLY

// (B) PATH ONLY $path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH); echo $path;

https://site.com/ path /file.php?p=123

FILENAME ONLY

// (C) FILENAME ONLY // USE BASENAME() TO GET THE FILE + STRIP QUERY STRING $file = basename($_SERVER["REQUEST_URI"], "?". $_SERVER["QUERY_STRING"]); echo $file;

https://site.com/path/ file.php ?p=123

PATH WITH FILENAME

// (D) PATH + FILENAME $filepath = strtok($_SERVER["REQUEST_URI"], "?"); echo $filepath;

https://site.com /path/file.php ?p=123

EXTRA) PARSE URL

For you guys who have a URL string from somewhere – You can use the parse_url() function to quickly get all the parts.

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

HOW ABOUT THE HASH?

Want to get the hash section of the URL? For example, http://site.com/path/file.php #section . Sadly, it is nowhere to be found in $_SERVER . Your best bet is to use Javascript instead.

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment Cancel Reply

Breakthrough Javascript

Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

Socials

About Me

W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

Источник

Оцените статью