PHP의 URL에서 조각 (해시 '#'뒤의 값) 가져 오기
PHP의 URL에서 조각 (해시 '#'뒤의 값)을 어떻게 얻을 수 있습니까?
http://domain.com/site/gallery/1#photo45
내가 원하는 말photo45
사용자의 브라우저에서와 같이 해시 마크 또는 앵커 후 값을 얻고 싶다면이이 값을 서버로 전송되지 않습니다으로 (따라서이 글은 사용할 수 없습니다 HTTP "표준"불가능 $_SERVER["REQUEST_URI"]
또는 이와 유사한 미리 정의 된 변수). 예를 들어이 값을 POST 매개 변수로 포함하려면 클라이언트 측에서 일종의 JavaScript 마법이 필요합니다.
어떤 소스에서든 알려진 URL을 구문 분석하는 것뿐이라면 mck89 의 대답 은 완벽합니다.
이 부분을 "조각"이라고하며 다음과 같이 얻을 수 있습니다.
$url=parse_url("http://domain.com/site/gallery/1#photo45 ");
echo $url["fragment"]; //This variable contains the fragment
A) 이미 PHP에 #hash가있는 URL이 있습니까? 쉬운! 그냥 파싱하세요!
if( strpos( $url, "#" ) === false ) echo "NO HASH !";
else echo "HASH IS: #".explode( "#", $url )[1]; // arrays are indexed from 0
또는 "이전"PHP에서 배열에 액세스하려면 exploded를 미리 저장해야합니다.
$exploded_url = explode( "#", $url ); $exploded_url[1];
B) PHP로 양식을 보내서 #hash를 얻고 싶습니까?
=> JavaScript MAGIC을 사용하십시오! (양식을 전처리하려면)
var forms = document.getElementsByTagName('form'); //get all forms on the site
for(var i=0; i<forms.length;i++) forms[i].addEventListener('submit', //to each form...
function(){ //add a submit pre-processing function that will:
var hidden = document.createElement("input"); //create an extra input element
hidden.setAttribute('type','hidden'); //set it to hidden so it doesn't break view
hidden.setAttribute('name','fragment'); //set a name to get by it in PHP
hidden.setAttribute('value',window.location.hash); //set a value of #HASH
this.appendChild(hidden); //append it to the current form
});
당신에 따라 form
의 것은 method
속성 당신은 PHP에서이 해시를함으로써 얻을 :
$_GET['fragment']
또는$_POST['fragment']
가능한 반환 : 1. ""
[빈 문자열] (해시 없음) 2. #
[해시] 기호를 포함 하는 전체 해시 ( window.location.hash
그 방식으로 작동하는 JavaScript를 사용했기 때문에 :))
C) 당신은 PHP에서 #hash 싶어 그냥 요청 URL에서를?
당신은 할 수 없습니다!
... (일반적인 HTTP 요청을 고려하지 않음) ...
...이 도움이 되었기를 바랍니다 :)
나는 이것에 대한 해결 방법을 조금 찾고 있었는데 내가 찾은 유일한 것은 URL 재 작성을 사용하여 "앵커"를 읽는 것입니다. http://httpd.apache.org/docs/2.2/rewrite/advanced.html 여기 아파치 문서에서 다음을 발견했습니다 ...
기본적으로 HTML 앵커로 리디렉션하는 것은 작동하지 않습니다. mod_rewrite는 # 문자를 이스케이프하여 % 23으로 변환하기 때문입니다. 이것은 차례로 리디렉션을 중단합니다.
해결 방법 : RewriteRule에서 [NE] 플래그를 사용하십시오. NE는 No Escape를 의미합니다.
토론 : 물론이 기술은 mod_rewrite (기본적으로 URL 인코딩)하는 다른 특수 문자와 함께 작동합니다.
다른 경고가있을 수 있고 그렇지 않은 것이있을 수 있지만 적어도 서버에서 #으로 뭔가를하는 것은 가능하다고 생각합니다.
해시 마크 뒤에는 텍스트를 가져올 수 없습니다 . 요청시 서버로 전송되지 않습니다.
php로 값을 원한다고 주장한다면이 트릭을 찾았습니다. 앵커 (#) 값을 분할하고 자바 스크립트로 얻은 다음 쿠키로 저장 한 후 php ~로 쿠키 값을 얻습니다.
http://www.stoimen.com/blog/2009/04/15/read-the-anchor-part-of-the-url-with-php/
먼저 URL을 구문 분석해야하므로 다음과 같이됩니다.
$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
현재 브라우저의 실제 URL을 구문 분석해야하는 경우 서버 호출을 요청해야합니다.
$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
URL에서 동적으로 해시를 가져 오려면 https://stackoverflow.com/a/57368072/2062851 이 작동합니다.
<script>
var hash = window.location.hash, //get the hash from url
cleanhash = hash.replace("#", ""); //remove the #
//alert(cleanhash);
</script>
<?php
$hash = "<script>document.writeln(cleanhash);</script>";
echo $hash;
?>
클라이언트 측에서 서버 측에서 문자열 교체를 수행 할 수 있습니다. 특히 강력한 솔루션은 아니지만 저와 같은 빠른 솔루션을 원하지 않으면 충분하다고 생각합니다.
고객:
var tempString = stringVal.replace('#', 'hashtag');
Server:
$user_message = $_GET['userMessage'];
$user_message = str_replace("hashtag", "#", $user_message);
You can do it by a combination of javascript and php:
<div id="cont"></div>
And by the other side;
<script>
var h = window.location.hash;
var h1 = (win.substr(1));//string with no #
var q1 = '<input type="text" id="hash" name="hash" value="'+h1+'">';
setInterval(function(){
if(win1!="")
{
document.querySelector('#cont').innerHTML = q1;
} else alert("Something went wrong")
},1000);
</script>
Then, on form submit you can retrieve the value via $_POST['hash'] (set the form)
Getting the data after the hashmark in a query string is simple. Here is an example used for when a client accesses a glossary of terms from a book. It takes the name anchor delivered (#tesla), and delivers the client to that term and highlights the term and its description in blue so its easy to see.
A. setup your strings with a div id, so the name anchor goes where its supposed to and the javascript can change the text colors
<div id="tesla">Tesla</div>
<div id="tesla1">An energy company</div>
B. Use Javascript to do the heavy work, on the server side, inserted in your PHP page, or wherever..
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
C. I am launching the java function automatically when the page is loaded.
<script>
$( document ).ready(function() {
D. get the anchor (#tesla) from the url received by the server
var myhash1 = $(location).attr('hash'); //myhash1 == #tesla
E. trim the hash sign off of it
myhash1 = myhash1.substr(1) //myhash1 == tesla
F. I need to highlight the term and the description so i create a new var
var myhash2 = '1';
myhash2 = myhash1.concat(myhash2); //myhash2 == tesla1
G. Now I can manipulate the text color for the term and description
var elem = document.getElementById(myhash1);
elem.style.color = 'blue';
elem = document.getElementById(myhash2);
elem.style.color = 'blue';
});
</script>
H. This works. client clicks link on client side (xyz.com#tesla) and goes right to the term. the term and the description are highlighted in blue by javascript for quick reading .. all other entries left in black..
참고URL : https://stackoverflow.com/questions/2317508/get-fragment-value-after-hash-from-a-url-in-php
'developer tip' 카테고리의 다른 글
직접 Ctrl + Tab 순서를 사용하고 마지막 탭 이후에 새 탭을 만들도록 Sublime Text 2/3를 구성하는 방법은 무엇입니까? (0) | 2020.08.30 |
---|---|
전쟁 파일을 만드는 방법 (0) | 2020.08.30 |
옵션 메뉴의 배경색을 변경하는 방법은 무엇입니까? (0) | 2020.08.30 |
프로덕션 애플리케이션에 Coffeescript를 사용한 사람이 있습니까? (0) | 2020.08.30 |
함수형 프로그래밍-불변성은 비용이 많이 듭니까? (0) | 2020.08.30 |