Example #1
0
 public function send($data = null)
 {
     if ($this->ready_state !== 1) {
         self::throw_error('Invalid state; Cannot send unopened request', E_RECOVERABLE_ERROR);
     }
     // Build the data string
     if (!is_string($data) && $data !== null) {
         if (is_array($data)) {
             $data_arr = '';
             foreach ($data as $name => $value) {
                 $data_arr[] = urlencode($name) . ' = ' . urlencode($value);
             }
             $data = implode('&', $data_arr);
         } else {
             self::throw_error('Invalid data parameter given; Expects string, array, or NULL', E_RECOVERABLE_ERROR);
         }
     }
     // Build the request
     $request = $this->method . ' ' . $this->url_info['path'] . ' HTTP/1.1' . CRLF;
     $request .= 'Host: ' . $this->url_info['host'] . CRLF;
     foreach ($this->headers as $name => $value) {
         $request .= $name . ': ' . $value . CRLF;
     }
     $request .= CRLF . $data;
     // Send the request
     $response = '';
     fputs($this->fh, $request);
     while (!feof($this->fh)) {
         $response .= fgets($this->fh, 128);
     }
     fclose($this->fh);
     // Seperate the response
     $response = explode(CRLF . CRLF, $response, 2);
     $headers = explode(CRLF, $response[0]);
     $this->response_body = $response[1];
     // Parse the response status
     $http = array_shift($headers);
     preg_match('/^HTTP\\/[0-9.]+ ([0-9]{3}) (.*)$/', $http, $match);
     $this->status = (int) $match[1];
     $this->status_text = $match[2];
     // Parse the headers
     $parsed_headers = array();
     foreach ($headers as $header) {
         $header = explode(': ', $header, 2);
         $parsed_headers[$header[0]] = $header[1];
     }
     $this->response_headers = $parsed_headers;
     // Check for a location header
     if (isset($this->response_headers['Location'])) {
         $location = $this->response_headers;
         $sub_request = new self();
         $sub_request->__is_redirect($this->redirect_stack);
         $sub_request->open($this->method, $location);
         if ($sub_request->error_code) {
             $this->error_code = $sub_request->error_code;
             return false;
         }
         foreach ($this->headers as $name => $value) {
             $sub_request->set_request_header($name, $value);
         }
         $sub_request->send($data);
         $this->response_text = $sub_request->response_text;
         $this->response_headers = $sub_request->get_all_response_headers();
         $this->status_code = $sub_request->status_code;
         $this->status_text = $sub_request->status_text;
     }
     // All done
     $this->ready_state = 4;
     return $this;
 }