Search code examples
phpforeachstrpos

What exactly does this PHP code do?


Alright, my friend gave me this code for requesting headers and comparing them to what the header should be. It works perfectly, but I'm not sure why. Here is the code:

    $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.

I commented with some numbers relating to the following questions:

  1. What exactly is happening here? Is it setting the $headers as $header AND $value?

  2. Again, don't have any idea what is going on here.

  3. Why set the variable to a different variable? This is the only area where the variable is getting used, so is there a reason to set it to something else?

  4. Same question as 3.

I'm sorry if this is a terrible question, but its been bothering me, and I really want to know WHY it works. Well, I understand why it works, I guess I just want to know more specifically. Thanks for any insight you can provide.


Solution

  •  $headers = apache_request_headers(); 
    

    Gets the header array.

        $customheader = "Header: 7ddb6ffab28bb675215a7d6e31cfc759"; 
    

    Defined a "customheader" it will search for.

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

    Loop through and create a $custom variable to hold the expanded $key=>$value header.

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

    Look for the $customheader in the expanded string.

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

    There really isn't a need for the reassignment of variables. In essence it's taking the array of headers and turning it into one big string which it then searches through to see if the $customheader text exists.