If you run CURLOPT_FOLLOWLOCATION in php and get the php error message:
Warning: curl_setopt () [function. curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set...
Two key safe_mode and open_basedir are mentioned in the error. If you are a VM and do not set the APPCHE permission, you cannot modify the server configuration to solve the problem. Generally, the safe_mode of server configuration is off, then, for some security concerns, you can set open_basedir to restrict the PHP execution folder of VM users. Therefore, when you use CURLOPT_FOLLOWLOCATION (php curl function to deeply capture data, once there is a 301 redirection, the error message mentioned in this article will appear.
After checking the relevant information, I quickly found a solution: http://www.php.net/manual/en/function.curl-setopt.php, which was provided by the PHP official support team.
The specific method is to use the curl statement without using curl_setopt ($ ch, CURLOPT_FOLLOWLOCATION, true) to customize a function in the php function,
The code is as follows: |
Copy code |
Function curl_redir_exec ($ ch, $ debug = "") { Static $ curl_loops = 0; Static $ curl_max_loops = 20; If ($ curl_loops ++ >=$ curl_max_loops) { $ Curl_loops = 0; Return FALSE; } Curl_setopt ($ ch, CURLOPT_HEADER, true ); Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, true ); $ Data = curl_exec ($ ch ); $ Debbbb = $ data; List ($ header, $ data) = explode ("\ n", $ data, 2 ); $ Http_code = curl_getinfo ($ ch, CURLINFO_HTTP_CODE ); If ($ http_code = 301 | $ http_code = 302 ){ $ Matches = array (); Preg_match ('/Location :(.*?) \ N/', $ header, $ matches ); $ Url = @ parse_url (trim (array_pop ($ matches ))); // Print_r ($ url ); If (! $ Url) { // Couldn't process the url to redirect $ Curl_loops = 0; Return $ data; } $ Last_url = parse_url (curl_getinfo ($ ch, CURLINFO_EFFECTIVE_URL )); /* If (! $ Url ['scheme ']) $ Url ['scheme '] = $ last_url ['scheme']; If (! $ Url ['host']) $ Url ['host'] = $ last_url ['host']; If (! $ Url ['path']) $ Url ['path'] = $ last_url ['path']; */ $ New_url = $ url ['scheme ']. '://'. $ url ['host']. $ url ['path']. ($ url ['query']? '? '. $ Url ['query']: ''); Curl_setopt ($ ch, CURLOPT_URL, $ new_url ); // Debug ('redirecting to ', $ new_url ); Return curl_redir_exec ($ ch ); } Else { $ Curl_loops = 0; Return $ debbbb; } }
|
After the function is defined, replace the statement curl_setopt ($ ch, CURLOPT_FOLLOWLOCATION, true) with curl_redir_exec ($ ch)
In this case, I don't think an error will be prompted for your PHP file. For this code, you can find it in the official PHP connection.