You are here

function cf_http_get_response in Common Functionality 7

Same name and namespace in other branches
  1. 7.2 modules/cf_http/cf_http.module \cf_http_get_response()

Reads an http page at the given path and returns an unprocessed response.

Why: Custom php scripts need a straight-forward and easy way to pull data from another website. This is useful as an alternative to iframe and has advantages and disadvantages to iframes. An advantage is that this allows showing remote content even if the remote url is down (via caching). A disadvantage is that remote images and links need to be processed, updated, and possibly even manually cached.

Parameters

string $server: Hostname or ip address of the server. Should not contain http:// or similary prefixes.

string $path: The file/path on the server to

int $port: (optional) port number of the page to read (defaults to 80).

array $function_history: (optional) An array of function names, ie: array('0' => 'my_function_name').

Return value

array An array containing the connection status and return http response. The array keys:

  • connected: A boolean with TRUE representing that the connection to the

server was established and FALSE otherwise.

  • response: The http response as returned by the target server. This http response must be processed.
1 call to cf_http_get_response()
cf_http_get_webpage in modules/cf_http/cf_http.module
Reads and processes a website page at the given path.

File

modules/cf_http/cf_http.module, line 47

Code

function cf_http_get_response($server, $path, $port = 80, array $function_history = array()) {
  cf_error_append_history($function_history, __FUNCTION__);
  $results = array(
    'connected' => FALSE,
    'response' => '',
    'is_local' => FALSE,
  );
  if (cf_is_empty_or_non_string($function_history, 'server', $server, WATCHDOG_ERROR)) {
    return $results;
  }
  if (cf_is_empty_or_non_string($function_history, 'path', $path, WATCHDOG_ERROR)) {
    return $results;
  }
  if (!is_numeric($port)) {
    cf_error_not_numeric($function_history, 'port');
    return $results;
  }
  $fp = fsockopen($server, $port, $errno, $errstr, 8);
  $server_address = preg_replace('@^\\w+://@i', '', $server);
  if (!$fp || !is_string($server_address)) {
    return $results;
  }
  else {
    fwrite($fp, 'GET ' . $path . ' HTTP/1.1' . "\r\n" . 'Host: ' . $server_address . "\r\n" . 'Accept-Encoding: deflate' . "\r\n" . 'Connection: Close' . "\r\n\r\n");
    stream_set_timeout($fp, 4);
    $results['is_local'] = stream_is_local($fp);
    while (!feof($fp)) {
      $results['response'] .= fgets($fp, 8192);
      $info = stream_get_meta_data($fp);
      if ($info['timed_out']) {
        fclose($fp);
        return $results;
      }
    }
    $results['connected'] = TRUE;
    fclose($fp);
    return $results;
  }
}