Changeset 787 for trunk


Ignore:
Timestamp:
Mar 16, 2023 2:37:04 AM (14 months ago)
Author:
anonymous
Message:

Update getHttpHeader() to support redirection

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/lib/Utilities.inc.php

    r785 r787  
    17201720* @since    28 Oct 2020 20:00:36
    17211721*/
    1722 function getHttpHeader($url, $key, Array $valid_response_codes=[200])
    1723 {
    1724     $headers = @get_headers($url, 1);
    1725 
    1726     if ($headers && preg_match(sprintf('/\b(%s)\b/', join('|', $valid_response_codes)), $headers[0])) {
     1722function getHttpHeader($url, $key=null, Array $valid_response_codes=[200], $method='GET')
     1723{
     1724    $context = stream_context_create(['http' => ['method' => $method]]);
     1725    $headers = get_headers($url, 1, $context);
     1726    $app =& \App::getInstance();
     1727    $app->logMsg(getDump($headers, true, SC_DUMP_JSON), LOG_DEBUG, __FILE__, __LINE__);
     1728    if (empty($headers)) {
     1729        return false;
     1730    }
     1731
     1732    // Status lines are found in numeric-indexed keys.
     1733    $http_status_keys = preg_grep('/^\d$/', array_keys($headers)); // [0] => "HTTP/1.1 302 Found", [1] => "HTTP/1.1 200 OK",
     1734    $final_http_status_key = end($http_status_keys); // E.g., `1`
     1735    $final_http_status = $headers[$final_http_status_key]; // E.g., `HTTP/1.1 200 OK`
     1736    $app->logMsg(sprintf('$final_http_status: %s', $final_http_status), LOG_DEBUG, __FILE__, __LINE__);
     1737    if ($headers && preg_match(sprintf('/\b(%s)\b/', join('|', $valid_response_codes)), $final_http_status)) {
    17271738        $headers = array_change_key_case($headers, CASE_LOWER);
     1739        if (!isset($key)) {
     1740            return $headers;
     1741        }
    17281742        $key = strtolower($key);
    17291743        if (isset($headers[$key])) {
    1730             return $headers[$key];
     1744            // If multiple redirects, the header key is an array; return only the last one.
     1745            return is_array($headers[$key]) && isset($headers[$key][$final_http_status_key]) ? $headers[$key][$final_http_status_key] : $headers[$key];
    17311746        }
    17321747    }
     
    18051820
    18061821    case 408:
    1807         $app->logMsg(sprintf('IP Intelligence timeout', null), LOG_WARNING, __FILE__, __LINE__);
     1822        $app->logMsg(sprintf('IP Intelligence timeout', null), LOG_NOTICE, __FILE__, __LINE__);
    18081823        return false;
    18091824    case 429:
     
    18231838        return false;
    18241839    case -3:
    1825         $app->logMsg('IP Intelligence: Unroutable or private address', LOG_WARNING, __FILE__, __LINE__);
     1840        $app->logMsg('IP Intelligence: Unroutable or private address', LOG_NOTICE, __FILE__, __LINE__);
    18261841        return false;
    18271842    case -4:
Note: See TracChangeset for help on using the changeset viewer.