2010-04-24 41 views
1

好吧,我的朋友給了我這個代碼,用於請求標題並將它們與標題的內容進行比較。它完美的工作,但我不知道爲什麼。下面是代碼:這個PHP代碼究竟做了什麼?

$headers = apache_request_headers(); 
    $customheader = "Header: 7ddb6ffab28bb675215a7d6e31cfc759"; 
    foreach ($headers as $header => $value) { // 1 
     $custom .= "$header: $value"; // 2 
    } 
    $mystring = $custom; // 3 
    $findme = $customheader; // 4 
    $pos = strpos($mystring, $findme); 
    if ($pos !== false) { 
// Do something 
} else{ exit(); } //If it doesn't match, exit. 

我評論與涉及以下問題的一些數字:

  1. 正是這裏發生了什麼?它是否將$ headers設置爲$ header AND $ value?

  2. 再次,不知道這裏發生了什麼。

  3. 爲什麼設置變量爲一個不同的變量?這是變量正在被使用的唯一領域,那麼是否有理由將其設置爲其他內容?

  4. 同樣的問題3.

對不起,如果這是一個可怕的問題,但它一直困擾着我,我真的想知道爲什麼它的工作原理。那麼,我明白它爲什麼會起作用,我想我只是想更具體地瞭解一下。感謝您提供的任何見解。

回答

3
$headers = apache_request_headers(); 

獲取標題數組。

$customheader = "Header: 7ddb6ffab28bb675215a7d6e31cfc759"; 

定義了它將搜索的「customheader」。

foreach ($headers as $header => $value) { // 1 
     $custom .= "$header: $value"; // 2 
    } 

遍歷並創建一個$custom變量來保存膨脹$key=>$value報頭。

$mystring = $custom; // 3 
    $findme = $customheader; // 4 
    $pos = strpos($mystring, $findme); 

查找擴展字符串中的$customheader

if ($pos !== false) { 
// Do something 
} else{ exit(); } //If it doesn't match, exit. 

確實不需要重新分配變量。本質上,它將頭部數組變成一個大字符串,然後搜索文本以查看是否存在文本。

+0

謝謝,這一個解釋它是最好的。現在我明白了 :) – Rob 2010-04-24 02:54:53

1
  1. 它遍歷$ headers,將每個元素的關鍵字分配給$ header,並將值分配給$ value。因此,在塊內部,我們在不同的變量中獲取標題的名稱和它的值。
  2. 在這一步中,我們使用點運算符將單個字符串中的所有標題連接起來。實質上,我們將數組中的標題轉換爲字符串。
  3. 除非在其他地方使用這些變量,否則沒有重新分配的理由。

免責聲明:我是一個紅寶石的人,所以如果我錯了,請糾正我。

1

apache_request_headers()返回當前請求中所有HTTP標題的關聯數組,如果失敗返回false。所以它很好地檢查返回值爲:

$headers = apache_request_headers(); 
if(! $headers) { 
die("Error fetching headers"); 
} 

1:您正在迭代您獲得的關聯數組。
2:在數組中形成粘貼鍵值對的字符串,鍵和值由冒號分隔。
3和4只是將一個變量分配給另一個變量。您可以直接使用:$pos = strpos($custom, $customheader);代替步驟3和4. strpos返回false如果找不到$customheader,則返回$custom否則返回找到的位置。

總的來說,這段代碼會檢查您的自定義標題是否存在於由apache_request_headers返回的標題中。