Created
March 19, 2014 08:31
-
-
Save Luxian/9637614 to your computer and use it in GitHub Desktop.
Helper function to check if a page redirects correctly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Get redirect information for a given URL | |
| * | |
| * @param string $url | |
| * URL to check | |
| * | |
| * @return array | |
| * In case of success complete cURL info array returned by curl_getinfo() + | |
| * 3 extra values: error, error_message, all_headers (headers as plain | |
| * text, including redirects). In case or error, only the extra values are | |
| * returned. | |
| * | |
| * @see https://php.net/manual/en/function.curl-getinfo.php | |
| * | |
| * @example: | |
| * | |
| * var_dump(check_redirect('http://calendar.google.com')); | |
| * | |
| * @author Luxian <[email protected]> | |
| */ | |
| function check_redirect($url) { | |
| $request_options = array( | |
| // TRUE to follow any "Location: " header that the server sends as part of | |
| // the HTTP header (note this is recursive, PHP will follow as many | |
| // "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set). | |
| CURLOPT_FOLLOWLOCATION => true, | |
| CURLOPT_MAXREDIRS => 5, // The maximum amount of HTTP redirections to follow. | |
| // TRUE to exclude the body from the output. Request method is then set to | |
| // HEAD. Changing this to FALSE does not change it to GET. | |
| CURLOPT_NOBODY => true, | |
| // TRUE to include the header in the output. With CURLOPT_FOLLOWLOCATION | |
| // set to TRUE we will have all the headers included in the order they | |
| // appeared | |
| CURLOPT_HEADER => true, | |
| // TRUE to return the transfer as a string of the return value of | |
| // curl_exec() instead of outputting it out directly. | |
| CURLOPT_RETURNTRANSFER => true, | |
| // The number of seconds to wait while trying to connect. | |
| // Use 0 to wait indefinitely. | |
| CURLOPT_CONNECTTIMEOUT => 2, | |
| // The URL to fetch. This can also be set when initializing a session with | |
| // curl_init(). | |
| CURLOPT_URL => $url, | |
| ); | |
| $request = curl_init(); | |
| curl_setopt_array($request, $request_options); | |
| $all_headers = curl_exec($request); | |
| // Return | |
| $return = array( | |
| 'error' => NULL, | |
| 'error_message' => NULL, | |
| 'all_headers' => NULL, | |
| ); | |
| if ($return['error'] = curl_errno($request)) { | |
| $return['error_message'] = curl_error($request); | |
| } | |
| else { | |
| $return += curl_getinfo($request); | |
| $return['all_headers'] = $all_headers; | |
| } | |
| curl_close($request); | |
| return $return; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment