Http.php
2 weeks ago
HttpTransportCurl.php
2 weeks ago
HttpTransportFopen.php
2 weeks ago
HttpTransportInterface.php
2 weeks ago
HttpTransportWp.php
2 weeks ago
HttpTransportFopen.php
95 lines
| 1 | <?php |
| 2 | |
| 3 | namespace LLAR\Core\Http; |
| 4 | |
| 5 | class HttpTransportFopen implements HttpTransportInterface { |
| 6 | |
| 7 | /** |
| 8 | * @param $url |
| 9 | * @param array $options |
| 10 | * |
| 11 | * @return array |
| 12 | */ |
| 13 | public function get( $url, $options = array() ) { |
| 14 | |
| 15 | if( !empty( $options['data'] ) ) { |
| 16 | $query_str = http_build_query( $options['data'] ); |
| 17 | $url .= "?{$query_str}"; |
| 18 | } |
| 19 | |
| 20 | $headers = !empty( $options['headers'] ) ? $options['headers'] : array(); |
| 21 | |
| 22 | return $this->request( $url, 'GET', $headers ); |
| 23 | } |
| 24 | |
| 25 | /** |
| 26 | * @param $url |
| 27 | * @param array $options |
| 28 | * |
| 29 | * @return array |
| 30 | */ |
| 31 | public function post( $url, $options = array() ) { |
| 32 | |
| 33 | $headers = !empty( $options['headers'] ) ? $options['headers'] : array(); |
| 34 | $data = !empty( $options['data'] ) ? $options['data'] : array(); |
| 35 | |
| 36 | return $this->request( $url, 'POST', $headers, $data ); |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * @param $url |
| 41 | * @param $method |
| 42 | * @param array $headers |
| 43 | * @param array $data |
| 44 | * |
| 45 | * @return array |
| 46 | */ |
| 47 | private function request( $url, $method, $headers = array(), $data = array() ) { |
| 48 | |
| 49 | $method = strtoupper( trim( $method ) ); |
| 50 | |
| 51 | $request_data = null; |
| 52 | if( !empty( $data ) ) { |
| 53 | $request_data = json_encode( $data, JSON_FORCE_OBJECT ); |
| 54 | } |
| 55 | |
| 56 | $context = stream_context_create( array( |
| 57 | 'http' => array( |
| 58 | 'method' => $method, |
| 59 | 'header' => implode( "\r\n", $headers ), |
| 60 | 'content' => $request_data |
| 61 | ) |
| 62 | )); |
| 63 | |
| 64 | $fp = @fopen( $url, 'rb', false, $context ); |
| 65 | |
| 66 | $error = null; |
| 67 | $status = null; |
| 68 | $response = null; |
| 69 | |
| 70 | if ( !$fp ) { |
| 71 | |
| 72 | if( !empty( $http_response_header[0] ) ) { |
| 73 | list(, $code, $message ) = explode( ' ', $http_response_header[0], 3 ); |
| 74 | $error = $message; |
| 75 | $status = $code; |
| 76 | |
| 77 | } else { |
| 78 | $last_err = error_get_last(); |
| 79 | $error = !empty( $last_err['message'] ) ? $last_err['message'] : 'Unknown error!'; |
| 80 | } |
| 81 | |
| 82 | } else { |
| 83 | list(, $code ) = explode( ' ', $http_response_header[0], 3 ); |
| 84 | $status = $code; |
| 85 | |
| 86 | $response = stream_get_contents( $fp ); |
| 87 | } |
| 88 | |
| 89 | return array( |
| 90 | 'data' => $response, |
| 91 | 'status' => intval( $status ), |
| 92 | 'error' => $error |
| 93 | ); |
| 94 | } |
| 95 | } |