쿼리 문자열을 제거하고 URL 만 얻는 방법?
현재 페이지의 URL을 빌드하기 위해 PHP를 사용하고 있습니다. 때로는 다음 형식의 URL
www.mydomian.com/myurl.html?unwantedthngs
요청됩니다. ?
결과 URL이되도록 다음과 뒤에 오는 모든 항목 (querystring) 을 제거하고 싶습니다 .
www.mydomain.com/myurl.html
내 현재 코드는 다음과 같습니다
<?php
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
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;
}
?>
strtok
처음 발생하기 전에 문자열을 얻는 데 사용할 수 있습니다.?
$url=strtok($_SERVER["REQUEST_URI"],'?');
사용 PHP 설명서 - parse_url () 당신이 필요로하는 부품을 얻을 수 있습니다.
편집 (@Navi Gamage 사용 예)
다음과 같이 사용할 수 있습니다.
<?php
function reconstruct_url($url){
$url_parts = parse_url($url);
$constructed_url = $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'];
return $constructed_url;
}
?>
편집 (두 번째 전체 예) :
구성표가 첨부되고 통지 메시지가 표시되지 않도록 기능이 업데이트되었습니다.
function reconstruct_url($url){
$url_parts = parse_url($url);
$constructed_url = $url_parts['scheme'] . '://' . $url_parts['host'] . (isset($url_parts['path'])?$url_parts['path']:'');
return $constructed_url;
}
$test = array(
'http://www.mydomian.com/myurl.html?unwan=abc',
'http://www.mydomian.com/myurl.html',
'http://www.mydomian.com',
'https://mydomian.com/myurl.html?unwan=abc&ab=1'
);
foreach($test as $url){
print_r(parse_url($url));
}
돌아올 것이다 :
Array
(
[scheme] => http
[host] => www.mydomian.com
[path] => /myurl.html
[query] => unwan=abc
)
Array
(
[scheme] => http
[host] => www.mydomian.com
[path] => /myurl.html
)
Array
(
[scheme] => http
[host] => www.mydomian.com
)
Array
(
[path] => mydomian.com/myurl.html
[query] => unwan=abc&ab=1
)
이것은 두 번째 매개 변수없이 설명 URL을 parse_url ()을 통해 전달한 결과입니다.
그리고 이것은 다음을 사용하여 URL을 구성 한 후의 최종 결과입니다.
foreach($test as $url){
echo reconstruct_url($url) . '<br/>';
}
산출:
http://www.mydomian.com/myurl.html
http://www.mydomian.com/myurl.html
http://www.mydomian.com
https://mydomian.com/myurl.html
최고의 솔루션 :
echo parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
No need to include your http://domain.com in your if you're submitting a form to the same domain.
$val = substr( $url, 0, strrpos( $url, "?"));
You'll need at least PHP Version 5.4 to implement this solution without exploding into a variable on one line and concatenating on the next, but an easy one liner would be:
$_SERVER["HTTP_HOST"].explode('?', $_SERVER["REQUEST_URI"], 2)[0];
Server Variables: http://php.net/manual/en/reserved.variables.server.php
Array Dereferencing: https://wiki.php.net/rfc/functionarraydereferencing
Most Easiest Way
$url = 'https://www.youtube.com/embed/ROipDjNYK4k?rel=0&autoplay=1';
$url_arr = parse_url($url);
$query = $url_arr['query'];
print $url = str_replace(array($query,'?'), '', $url);
//output
https://www.youtube.com/embed/ROipDjNYK4k
If you want to get request path (more info):
echo parse_url($_SERVER["REQUEST_URI"])['path']
If you want to remove the query and (and maybe fragment also):
function strposa($haystack, $needles=array(), $offset=0) {
$chr = array();
foreach($needles as $needle) {
$res = strpos($haystack, $needle, $offset);
if ($res !== false) $chr[$needle] = $res;
}
if(empty($chr)) return false;
return min($chr);
}
$i = strposa($_SERVER["REQUEST_URI"], ['#', '?']);
echo strrpos($_SERVER["REQUEST_URI"], 0, $i);
You can try:
<?php
$this_page = basename($_SERVER['REQUEST_URI']);
if (strpos($this_page, "?") !== false) $this_page = reset(explode("?", $this_page));
?>
To remove the query string from the request URI, replace the query string with an empty string:
function request_uri_without_query() {
$result = $_SERVER['REQUEST_URI'];
$query = $_SERVER['QUERY_STRING'];
if(!empty($query)) {
$result = str_replace('?' . $query, '', $result);
}
return $result;
}
Because I deal with both relative and absolute URLs, I updated veritas's solution like the code below.
You can try yourself here: https://ideone.com/PvpZ4J
function removeQueryStringFromUrl($url) {
if (substr($url,0,4) == "http") {
$urlPartsArray = parse_url($url);
$outputUrl = $urlPartsArray['scheme'] . '://' . $urlPartsArray['host'] . ( isset($urlPartsArray['path']) ? $urlPartsArray['path'] : '' );
} else {
$URLexploded = explode("?", $url, 2);
$outputUrl = $URLexploded[0];
}
return $outputUrl;
}
You can use the parse_url build in function like that:
$baseUrl = $_SERVER['SERVER_NAME'] . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
Try this
$url_with_querystring = 'www.mydomian.com/myurl.html?unwantedthngs';
$url_data = parse_url($url_with_querystring);
$url_without_querystring = str_replace('?'.$url_data['query'], '', $url_with_querystring);
could also use following as per the php manual comment
$_SERVER['REDIRECT_URL']
Please note this is working only for certain PHP environment only and follow the bellow comment from that page for more information;
Purpose: The URL path name of the current PHP file, path-info is N/A and excluding URL query string. Includes leading slash.
Caveat: This is before URL rewrites (i.e. it's as per the original call URL).
Caveat: Not set on all PHP environments, and definitely only ones with URL rewrites.
Works on web mode: Yes
Works on CLI mode: No
Try this:
$urrl=$_SERVER['HTTP_HOST'] . $_SERVER['scriptNAME']
or
$urrl=$_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']
참고URL : https://stackoverflow.com/questions/6969645/how-to-remove-the-querystring-and-get-only-the-url