Windows / IIS 서버에서 현재 페이지의 전체 URL을 얻으려면 어떻게해야합니까?
WordPress 설치를 Windows / IIS 서버 의 새 폴더 로 옮겼습니다 . PHP에서 301 리디렉션을 설정하고 있지만 작동하지 않는 것 같습니다. 내 게시물 URL의 형식은 다음과 같습니다.
http:://www.example.com/OLD_FOLDER/index.php/post-title/
/post-title/
URL 의 일부 를 얻는 방법을 알 수 없습니다 .
$_SERVER["REQUEST_URI"]
-모두가 권장하는 것처럼-빈 문자열을 반환합니다. $_SERVER["PHP_SELF"]
그냥 돌아오고 index.php
있습니다. 왜 이런 것이며 어떻게 해결할 수 있습니까?
아마도 당신은 IIS 아래 있기 때문에
$_SERVER['PATH_INFO']
설명에 사용한 URL을 기반으로 원하는 것입니다.
Apache의 경우을 사용 $_SERVER['REQUEST_URI']
합니다.
$pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
if ($_SERVER["SERVER_PORT"] != "80")
{
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else
{
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
Apache의 경우 :
'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']
허먼이 언급 한대로 HTTP_HOST
대신 사용할 수도 있습니다 SERVER_NAME
. 자세한 내용은 이 관련 질문 을 참조하십시오 . 요컨대, 어느 쪽을 사용해도 괜찮습니다. 다음은 '호스트'버전입니다.
'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
편집증을 위해 / 왜 중요한가
일반적으로, 나는 설정 ServerName
에 VirtualHost
내가 원하기 때문에 그 로 정식 웹 사이트의 형태로. 는 $_SERVER['HTTP_HOST']
요청 헤더를 기반으로 설정됩니다. 서버가 해당 IP 주소에서 모든 / 도메인 이름에 응답하면 사용자가 헤더를 스푸핑하거나 더 나쁜 사람이 DNS 레코드를 IP 주소로 가리킬 수 있으며 서버 / 웹 사이트에서 동적 웹 사이트를 제공하게됩니다 잘못된 URL에 작성된 링크 후자의 방법을 사용하는 경우 다음과 같이 제공하려는 도메인을 시행하도록 규칙을 vhost
설정하거나 .htaccess
규칙을 설정해야합니다 .
RewriteEngine On
RewriteCond %{HTTP_HOST} !(^stackoverflow.com*)$
RewriteRule (.*) https://stackoverflow.com/$1 [R=301,L]
#sometimes u may need to omit this slash ^ depending on your server
희망이 도움이됩니다. 이 답변의 진정한 요점은 아파치와 함께 완전한 URL을 얻는 방법을 검색 할 때 여기에 나온 사람들에게 첫 번째 코드 줄을 제공하는 것이 었습니다. :)
$_SERVER['REQUEST_URI']
IIS에서는 작동하지 않지만 이것을 찾았습니다. 유망하게 들리는 http://neosmart.net/blog/2006/100-apache-compliance-request_uri-for-iis-and-windows/
URL을 작동 시키려면이 클래스를 사용하십시오.
class VirtualDirectory
{
var $protocol;
var $site;
var $thisfile;
var $real_directories;
var $num_of_real_directories;
var $virtual_directories = array();
var $num_of_virtual_directories = array();
var $baseURL;
var $thisURL;
function VirtualDirectory()
{
$this->protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
$this->site = $this->protocol . '://' . $_SERVER['HTTP_HOST'];
$this->thisfile = basename($_SERVER['SCRIPT_FILENAME']);
$this->real_directories = $this->cleanUp(explode("/", str_replace($this->thisfile, "", $_SERVER['PHP_SELF'])));
$this->num_of_real_directories = count($this->real_directories);
$this->virtual_directories = array_diff($this->cleanUp(explode("/", str_replace($this->thisfile, "", $_SERVER['REQUEST_URI']))),$this->real_directories);
$this->num_of_virtual_directories = count($this->virtual_directories);
$this->baseURL = $this->site . "/" . implode("/", $this->real_directories) . "/";
$this->thisURL = $this->baseURL . implode("/", $this->virtual_directories) . "/";
}
function cleanUp($array)
{
$cleaned_array = array();
foreach($array as $key => $value)
{
$qpos = strpos($value, "?");
if($qpos !== false)
{
break;
}
if($key != "" && $value != "")
{
$cleaned_array[] = $value;
}
}
return $cleaned_array;
}
}
$virdir = new VirtualDirectory();
echo $virdir->thisURL;
더하다:
function my_url(){
$url = (!empty($_SERVER['HTTPS'])) ?
"https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] :
"http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
echo $url;
}
그런 다음 my_url
함수를 호출하십시오 .
다음 함수를 사용하여 현재 전체 URL을 가져옵니다. 이것은 IIS와 Apache에서 작동합니다.
function get_current_url() {
$protocol = 'http';
if ($_SERVER['SERVER_PORT'] == 443 || (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')) {
$protocol .= 's';
$protocol_port = $_SERVER['SERVER_PORT'];
} else {
$protocol_port = 80;
}
$host = $_SERVER['HTTP_HOST'];
$port = $_SERVER['SERVER_PORT'];
$request = $_SERVER['PHP_SELF'];
$query = isset($_SERVER['argv']) ? substr($_SERVER['argv'][0], strpos($_SERVER['argv'][0], ';') + 1) : '';
$toret = $protocol . '://' . $host . ($port == $protocol_port ? '' : ':' . $port) . $request . (empty($query) ? '' : '?' . $query);
return $toret;
}
REQUEST_URI는 Apache에 의해 설정되므로 IIS에서는 얻을 수 없습니다. $ _SERVER에서 var_dump 또는 print_r을 시도하고 사용할 수있는 값을 확인하십시오.
URL 의 우편 제목 부분은 index.php
파일 뒤에 있으며, mod_rewrite를 사용하지 않고 친숙한 URL을 제공하는 일반적인 방법입니다. 따라서 제목은 실제로 쿼리 문자열의 일부이므로 $ _SERVER [ 'QUERY_STRING']을 사용하여 얻을 수 있어야합니다.
Use the following line on the top of the PHP page where you're using $_SERVER['REQUEST_URI']
. This will resolve your issue.
$_SERVER['REQUEST_URI'] = $_SERVER['PHP_SELF'] . '?' . $_SERVER['argv'][0];
Oh, the fun of a snippet!
if (!function_exists('base_url')) {
function base_url($atRoot=FALSE, $atCore=FALSE, $parse=FALSE){
if (isset($_SERVER['HTTP_HOST'])) {
$http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
$hostname = $_SERVER['HTTP_HOST'];
$dir = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
$core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY);
$core = $core[0];
$tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s");
$end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir);
$base_url = sprintf( $tmplt, $http, $hostname, $end );
}
else $base_url = 'http://localhost/';
if ($parse) {
$base_url = parse_url($base_url);
if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = '';
}
return $base_url;
}
}
It has beautiful returns like:
// A URL like http://stackoverflow.com/questions/189113/how-do-i-get-current-page-full-url-in-php-on-a-windows-iis-server:
echo base_url(); // Will produce something like: http://stackoverflow.com/questions/189113/
echo base_url(TRUE); // Will produce something like: http://stackoverflow.com/
echo base_url(TRUE, TRUE); || echo base_url(NULL, TRUE); //Will produce something like: http://stackoverflow.com/questions/
// And finally:
echo base_url(NULL, NULL, TRUE);
// Will produce something like:
// array(3) {
// ["scheme"]=>
// string(4) "http"
// ["host"]=>
// string(12) "stackoverflow.com"
// ["path"]=>
// string(35) "/questions/189113/"
// }
Everyone forgot http_build_url?
http_build_url($_SERVER['REQUEST_URI']);
When no parameters are passed to http_build_url
it will automatically assume the current URL. I would expect REQUEST_URI
to be included as well, though it seems to be required in order to include the GET parameters.
The above example will return full URL.
I have used the following code, and I am getting the right result...
<?php
function currentPageURL() {
$curpageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {
$curpageURL.= "s";
}
$curpageURL.= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$curpageURL.= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else {
$curpageURL.= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $curpageURL;
}
echo currentPageURL();
?>
In my apache server, this gives me the full URL in the exact format you are looking for:
$_SERVER["SCRIPT_URI"]
Reverse Proxy Support!
Something a little more robust. Note It'll only work on 5.3
or greater.
/*
* Compatibility with multiple host headers.
* Support of "Reverse Proxy" configurations.
*
* Michael Jett <mjett@mitre.org>
*/
function base_url() {
$protocol = @$_SERVER['HTTP_X_FORWARDED_PROTO']
?: @$_SERVER['REQUEST_SCHEME']
?: ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https" : "http");
$port = @intval($_SERVER['HTTP_X_FORWARDED_PORT'])
?: @intval($_SERVER["SERVER_PORT"])
?: (($protocol === 'https') ? 443 : 80);
$host = @explode(":", $_SERVER['HTTP_HOST'])[0]
?: @$_SERVER['SERVER_NAME']
?: @$_SERVER['SERVER_ADDR'];
// Don't include port if it's 80 or 443 and the protocol matches
$port = ($protocol === 'https' && $port === 443) || ($protocol === 'http' && $port === 80) ? '' : ':' . $port;
return sprintf('%s://%s%s/%s', $protocol, $host, $port, @trim(reset(explode("?", $_SERVER['REQUEST_URI'])), '/'));
}
'Programing' 카테고리의 다른 글
재산 변경에 대한 중단 점 (0) | 2020.06.23 |
---|---|
"스타일 시트 (#)에 대한 텍스트를 가져 오지 못했습니다 : 주어진 ID를 가진 스타일 시트가 없습니다"라는 오류가 표시됩니다. 이것은 무엇을 의미합니까? (0) | 2020.06.23 |
HTML.BeginForm 및 속성 추가 (0) | 2020.06.23 |
numpy 배열에서 특정 열 추출 (0) | 2020.06.23 |
숫자 인덱스로 data.table에서 여러 열을 선택하십시오. (0) | 2020.06.23 |