Ok I am trying to access some JSON using a PHP proxy as I have been told is the only way to do a cross domain access when you don't control the sites policies.
Here is the code below I am trying to use as a php proxy as shared by a fellow stackoverflow user:
function curl_download($Url){
// is cURL installed yet?
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
// OK cool - then let's create a new cURL resource handle
$ch = curl_init();
// Now set some options (most are optional)
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $Url);
// Set a referer
curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");
// User agent
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
// Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// Download the given URL, and return output
$output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
return $output;
}
problem is when I replace $URL with http://www.nfl.com/liveupdate/scorestrip/ss.json nothing seems to happen. I am not really sure how to use this PHP proxy though either as I don't ever do this type of thing.
Am I suppose to create this in a seperate php file and then send a request to this code? I am kind of against the wall on what exactly to do here to make it so I can access the json from the site above.
Am I suppose to create this in a seperate php file and then send a request to this code?
Yes. The code above should resend your request made from JS to a remote service on another domain. Which is what does the trick - enables crossdomain POST requests from JS.
<?php
$server_url = "http://example.com/";
$options = array
(
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_CONNECTTIMEOUT => 0,
CURLOPT_HTTPGET => 1
);
$service = $_GET["service"];
$request_headers = Array();
foreach($_SERVER as $i=>$val) {
if (strpos($i, 'HTTP_') === 0) {
$name = str_replace(array('HTTP_', '_'), array('', '-'), $i);
if ($name != 'HOST')
{
$request_headers[] = "{$name}: {$val}";
}
}
}
$options[CURLOPT_HTTPHEADER] = $request_headers;
switch (strtolower($_SERVER["REQUEST_METHOD"]))
{
case "post":
$options[CURLOPT_POST] = true;
$url = "{$server_url}/services/".$service;
$options[CURLOPT_POSTFIELDS] = file_get_contents("php://input");
break;
case "get":
unset($_GET["service"]);
$querystring = "";
$first = true;
foreach ($_GET as $key => $val)
{
if (!$first) $querystring .= "&";
$querystring .= $key."=".$val;
$first = false;
}
$url = "{$server_url}/services/".$service."?".$querystring;
break;
default:
throw new Exception("Unsupported request method.");
break;
}
$options[CURLOPT_URL] = $url;
$curl_handle = curl_init();
curl_setopt_array($curl_handle,$options);
$server_output = curl_exec($curl_handle);
curl_close($curl_handle);
$response = explode("\r\n\r\n",$server_output);
$headers = explode("\r\n",$response[0]);
foreach ($headers as $header)
{
if ( !preg_match(';^transfer-encoding:;ui', Trim($header)) )
{
header($header);
}
}
echo $response[1];
This is a slightly modified version of the script I use, unfortunately not well documented.
Hope it helps.
I would suggest using Ben Almans Simple PHP Proxy
Simple PHP Proxy
Related
I don't have much experience here, so pls bear with me. I am good with cURL and sending data to API's - right now I want to set up a testing environment as the API isn't ready, but I know what he responses will be.
I will be sending some data to the API via cURL - no issue there. The main variable is called $src and it is a simple POST value. I want to set up a script on another server and echo back some messaging based on $src value.
On the remote script, that will mimic the API I'm getting returned messages like "Resource id #4" or "Resource id #5" I realize that is a generic message. Here is what I am trying to do
cURL scripting
foreach($fields as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
$fields_string = rtrim($fields_string,'& ');
$urlFX = 'http://myserver.com/NTLM/testresponse.php';
$ch = curl_init($urlFX);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo($ch);
Test script to mimic API Response:
<?php
$src = $_GET['src'];
if($src == "nt-fx-data-test") {
echo('foo');
} else {
echo('bar');
}
?>
How can I set up a script that will mimic the API's responses based on the $src var value?
Try to hit
http://goelette.net/NTLM/testresponse.php
With params:
src=nt-fx-data-test
src=xp
dst=nt-fx-data-test
Code:
<?php
foreach($_REQUEST as $param => $value) {
if ($param == 'src' and $value == 'nt-fx-data-test') {
echo 'foo';
} else if ($param == 'src' and $value != 'nt-fx-data-test') {
echo 'bar';
} else {
echo "unknown $param";
}
}
I would like to have a lottery check page written in php. The code does not work with the Hungarian lottery database ($ url2) but works with the other ($ url1). Too much data is the problem?
<?php
echo "CURL - function test <br>";
$url1 = "http://www.example.com";
$url2 = "https://bet.szerencsejatek.hu/cmsfiles/otos.html";
function curl_download($Url){
// is cURL installed yet?
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
// OK cool - then let's create a new cURL resource handle
$ch = curl_init();
// Now set some options (most are optional)
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $Url);
// Set a referer
curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");
// User agent
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
// Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// Download the given URL, and return output
$output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
return $output;
}
echo curl_download($url2);
echo strlen(curl_download($url2));
The first thing that it depends on what the error is.
I think you should dump the result of CURL work. Something like
if (!curl_errno($ch)) {
switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
case 200: # OK
$return = ['result' => 'ok', 'response_text' => $result];
break;
default:
$return = ['result' => 'unexpected_http_code', 'http_code' => $http_code,
'response_text' => $result
];
}
} else {
$return = ['result' => 'curl_error', 'curl_error' => curl_error($ch)];
}
Maybe it's because you didn't configure your SSL settings because the second URL starts with https://
I'm new to REST and I'm trying to develop a web app that will connect with JIRA from one sid (already covered) and with HP's ALM from the other side.
what I'm attempting to accomplish right now is basic authentication to ALM with PHP but can't seem to progress.
here is my code:
$handle=curl_init('http://192.168.1.7:8081');
$headers = array(
'Accept: application/xml',
'Content-Type: application/xml',
'Authorization: Basic YWRtaW46MTIzNA==',
);
$username='admin';
$password='1234';
$url = 'http://192.168.1.7:8081/qcbin/authentication-point/login.jsp';
curl_setopt_array(
$handle,
array(
CURLOPT_URL=>'http://192.168.1.7:8081/qcbin/rest/domains/default/projects/Ticomsoft/defects?login-form-required=y',
//CURLOPT_COOKIEFILE=>$ckfile,
CURLOPT_POST=>true,
//CURLOPT_HTTPGET =>true,
CURLOPT_COOKIEJAR=>$ckfile,
CURLOPT_VERBOSE=>1,
//CURLOPT_POSTFIELDS=>,
//CURLOPT_GETFIELDS=>'j_username=admin&j_password=1234&redirect-url=http://192.168.1.7:8081/myUiResource.jsps',
CURLOPT_SSL_VERIFYHOST=> 0,
CURLOPT_SSL_VERIFYPEER=> 0,
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_FOLLOWLOCATION=>true,
CURLOPT_HEADER=>false,
CURLOPT_HTTPHEADER=> $headers,
CURLOPT_AUTOREFERER=>true
//CURLOPT_COOKIE=>
//CURLOPT_USERPWD=>"admin:yahala"
//CURLOPT_CUSTOMREQUEST=>"POST"
)
);
$result=curl_exec($handle);
$ch_error = curl_error($handle);
$response = curl_getinfo($handle);
print_r($response);
if ($ch_error) {
echo "cURL Error: $ch_error";
} else {
//var_dump(json_decode($result, true));
echo $result;
}
curl_close($handle);
?>
as you can see there is a lot of garbage as my trial and error progressed.
Here we go. I followed the QC Rest API documentation to study the order that QC expects requests to be made. I've tested it against ALM11. I'm new to cURL as well, but this should get you in and working......
<?php
//create a new cURL resource
$qc = curl_init();
//create a cookie file
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
//set URL and other appropriate options
curl_setopt($qc, CURLOPT_URL, "http://qualityCenter:8080/qcbin/rest/is-authenticated");
curl_setopt($qc, CURLOPT_HEADER, 0);
curl_setopt($qc, CURLOPT_HTTPGET, 1);
curl_setopt($qc, CURLOPT_RETURNTRANSFER, 1);
//grab the URL and pass it to the browser
$result = curl_exec($qc);
$response = curl_getinfo($qc);
//401 Not authenticated (as expected)
//We need to pass the Authorization: Basic headers to authenticate url with the
//Correct credentials.
//Store the returned cookfile into $ckfile
//Then use the cookie when we need it......
if($response[http_code] == '401')
{
$url = "http://qualityCenter:8080/qcbin/authentication-point/authenticate";
$credentials = "qc_username:qc_password";
$headers = array("GET /HTTP/1.1","Authorization: Basic ". base64_encode($credentials));
curl_setopt($qc, CURLOPT_URL, $url);
curl_setopt($qc, CURLOPT_HTTPGET,1); //Not sure we need these again as set above?
curl_setopt($qc, CURLOPT_HTTPHEADER, $headers);
//Set the cookie
curl_setopt($qc, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt($qc, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($qc);
$response = curl_getinfo($qc);
//The response will be 200
if($response[http_code] == '200')
{
//Use the cookie for subsequent calls...
curl_setopt($qc, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt($qc, CURLOPT_RETURNTRANSFER, true);
curl_setopt($qc, CURLOPT_URL, "http://qualityCenter:8080/qcbin/rest/domains/Your_Domain/projects/Your_Project/defects");
//In this example we are retrieving the xml so...
$xml = simplexml_load_string(curl_exec($qc));
print_r($xml);
//Call Logout
logout($qc,"http://qualityCenter:8080/qcbin/authentication-point/logout");
}
else
{
echo "Authentication failed";
}
}
else
{
echo "Not sure what happened?!";
}
//Close cURL resource, and free up system resources
curl_close($qc);
function logout($qc, $url)
{
curl_setopt($qc, CURLOPT_URL, $url);
curl_setopt($qc, CURLOPT_HEADER, 0);
curl_setopt($qc, CURLOPT_HTTPGET,1);
curl_setopt($qc, CURLOPT_RETURNTRANSFER, 1);
//grab the URL and pass it to the browser
$result = curl_exec($qc);
}
?>
Let me know if it worked!
Thanks,
Rich
one of the important things to keep in mind is after authenticating you must do the following
POST /qcbin/rest/site-session
with cookies LWSSO
this will return QCSession and XSRF-TOKEN which are needed to perform any operations
Here is my solution in Perl for this problem: The authentication step is performed first, setting the cookie for the next libcurl request which then can be performed with no problems. This is a version for background jobs. For a dialog application, the credentials could be passed through from the user's input instead. Also, I had to do this with https instead of http. The Perl program also shows how to instruct curl for https (there is a very good how-to on http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/ ).
#!/usr/bin/perl
# This script accesses, as a proxy, the REST API of the HP quality center
# Running it without query parameter, the complete list of defects is returned
# A query parameter, e.g. 'query={id[2283]}' will be passed as is to the HP QC API
# We are using the libcurl wrapper WWW::Curl::Easy
# The access is https, so a certificate has to be passed to libcurl
# The main point for using curl, however, is the authentication procedure:
# HP requires a preparative call to a special authentication service
# The authentication ticket will then be passed back as a cookie
# Only with this ticket, the real GET request on the defects can be performed
use WWW::Curl::Easy;
use strict;
use warnings;
use constant {
URL_QC_DEFECTS => "https://[QC DOMAIN]/qcbin/rest/domains/[DOMAIN]/projects/[PROJECT]/defects/",
URL_QC_AUTH => "https://[QC DOMAIN]/qcbin/authentication-point/authenticate",
PATH_CERT => "[PATH TO CREDENTIALS]" # contains certificate and credentials, see below
};
doRequest( URL_QC_DEFECTS . "?" . $ENV{QUERY_STRING} );
return 0;
sub doRequest {
my ($url,$cookies,$response) = (shift,"","");
eval {
my $curl = get_curl_instance(\$cookies,\$response);
authenticate( $curl );
get( $curl, $url );
if ($response =~ /.*?(<\?xml\b.*)/s) {
print "Content-Type:text/xml\n\n";
print $1;
}
else {
die "The response from HP QC is not in XML format";
}
};
if ($#) {
print "Content-Type:text/plain\n\n$#";
}
}
sub get_curl_instance {
my ($cookie,$response) = #_;
my $curl = WWW::Curl::Easy->new( );
open( my $cookiefile, ">", $cookie) or die "$!";
$curl->setopt( CURLOPT_COOKIEFILE, $cookiefile );
open( my $responsefile, ">", $response) or die "$!";
$curl->setopt( CURLOPT_WRITEDATA, $responsefile );
$curl->setopt( CURLOPT_SSL_VERIFYPEER, 1);
$curl->setopt( CURLOPT_SSL_VERIFYHOST, 2);
$curl->setopt( CURLOPT_CAINFO, cert() );
$curl->setopt( CURLOPT_FOLLOWLOCATION, 1 );
return $curl;
}
sub authenticate {
my $curl = shift;
my ($rc,$status);
$curl->setopt( CURLOPT_URL, URL_QC_AUTH );
$curl->setopt( CURLOPT_USERPWD, cred( ) );
if (($rc = $curl->perform( )) != 0) {
die "Error Code $rc in curl->perform( ) on URL " . URL_QC_AUTH;
}
if (($status=$curl->getinfo(CURLINFO_HTTP_CODE))!="200") {
die "HTTP-Statuscode $status from authentication call";
}
}
sub get {
my ($curl,$url) = #_;
my ($rc,$status);
$curl->setopt( CURLOPT_URL, $url );
$curl->setopt( CURLOPT_HEADER, { Accept => "text/xml" } );
if (($rc = $curl->perform( )) != 0) {
die "Error Code $rc from defects request";
}
if (($status=$curl->getinfo(CURLINFO_HTTP_CODE))!="200") {
die "HTTP Statuscode $status from defects request";
}
}
sub cred {
open CRED, PATH_CERT . '/.cred_qc' or die "Can't open credentials file: $!";
chomp( my $cred = <CRED>);
close CRED;
return $cred;
}
sub cert {
return PATH_CERT . '/qc.migros.net.crt';
}
As an alternative to Sohaib's answer concerning the need to POST to /qcbin/rest/site-session after authenticating, you can do both in one step by POSTing to /qcbin/api/authentication/sign-in , as per the below:
"There are four cookies that come back, and in ALM 12.53 the authentication point has changed ( but the documentation has not so it sends you to the wrong place ! )
So, send a POST request with BASIC authentication, base64 encoded username / password to /qcbin/api/authentication/sign-in and you will get back
LWSSO_COOKIE_KEY
QCSESSION
ALM_USER
XSRF_TOKEN
include these with all your subsequent GETS and PUTS and you should be OK."
(This answer is taken from https://community.microfocus.com/t5/ALM-QC-User-Discussions/Authentication-fails-when-trying-to-pull-data-from-ALM-server/td-p/940921, and worked for me in a similar context).
How can I get the destination URL using cURL when the HTTP status code is 302?
<?PHP
$url = "http://www.ecs.soton.ac.uk/news/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$html = curl_exec($ch);
$status_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($status_code=302 or $status_code=301){
$url = "";
// I want to to get the destination url
}
curl_close($ch);
?>
You can use:
echo curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE); // We'll parse redirect url from header.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE); // We want to just get redirect url but not to follow it.
$response = curl_exec($ch);
preg_match_all('/^Location:(.*)$/mi', $response, $matches);
curl_close($ch);
echo !empty($matches[1]) ? trim($matches[1][0]) : 'No redirect found';
A bit dated of a response but wanted to show a full working example, some of the solutions out there are pieces:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); //set url
curl_setopt($ch, CURLOPT_HEADER, true); //get header
curl_setopt($ch, CURLOPT_NOBODY, true); //do not include response body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //do not show in browser the response
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //follow any redirects
curl_exec($ch);
$new_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); //extract the url from the header response
curl_close($ch);
This works with any redirects such as 301 or 302, however on 404's it will just return the original url requested (since it wasn't found). This can be used to update or remove links from your site. This was my need anyway.
You have to grab the Location header for the redirected URL.
In response to user437797's comment on Tamik Soziev's answer (I unfortunately do not have the reputation to comment there directly) :
The CURLINFO_EFFECTIVE_URL works fine, but for it to do as op wants you also have to set CURLOPT_FOLLOWLOCATION to TRUE of course. This is because CURLINFO_EFFECTIVE_URL returns exactly what it says, the effective url that ends up getting loaded. If you don't follow redirects then this will be your requested url, if you do follow redirects then it will be the final url that is redirected to.
The nice thing about this approach is that it also works with multiple redirects, whereas when retrieving and parsing the HTTP header yourself you may have to do that multiple times before the final destination url is exposed.
Also note that the max number of redirects that curl follows can be controlled via CURLOPT_MAXREDIRS. By default it is unlimited (-1) but this may get you into trouble if someone (perhaps intentionally) configured and endless redirect loop for some url.
The new destination for a 302 redirect ist located in the http header field "location".
Example:
HTTP/1.1 302 Found
Date: Tue, 30 Jun 2002 1:20:30 GMT
Server: Apache
Location: http://www.foobar.com/foo/bar
Content-Type: text/html; charset=iso-8859-1
Just grep it with a regex.
To include all HTTP header information include it to the result with the curl option CURLOPT_HEADER. Set it with:
curl_setopt($c, CURLOPT_HEADER, true);
If you simply want curl to follow the redirection use CURLOPT_FOLLOWLOCATION:
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
Anyway, you shouldn't use the new URI because HTTP Statuscode 302 is only a temporary redirect.
Here's a way to get all headers returned by a curl http request, as well as the status code and an array of header lines for each header.
$url = 'http://google.com';
$opts = array(CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_FOLLOWLOCATION => true);
$ch = curl_init();
curl_setopt_array($ch, $opts);
$return = curl_exec($ch);
curl_close($ch);
$headers = http_response_headers($return);
foreach ($headers as $header) {
$str = http_response_code($header);
$hdr_arr = http_response_header_lines($header);
if (isset($hdr_arr['Location'])) {
$str .= ' - Location: ' . $hdr_arr['Location'];
}
echo $str . '<br />';
}
function http_response_headers($ret_str)
{
$hdrs = array();
$arr = explode("\r\n\r\n", $ret_str);
foreach ($arr as $each) {
if (substr($each, 0, 4) == 'HTTP') {
$hdrs[] = $each;
}
}
return $hdrs;
}
function http_response_header_lines($hdr_str)
{
$lines = explode("\n", $hdr_str);
$hdr_arr['status_line'] = trim(array_shift($lines));
foreach ($lines as $line) {
list($key, $val) = explode(':', $line, 2);
$hdr_arr[trim($key)] = trim($val);
}
return $hdr_arr;
}
function http_response_code($str)
{
return substr(trim(strstr($str, ' ')), 0, 3);
}
Use curl_getinfo($ch), and the first element (url) would indicate the effective URL.
How can I do this in PHP? e.g.
bit.ly/f00b4r ==> http://www.google.com/search?q=cute+kittens
In Java, the solution is this:
You should issue a HEAD request to
the url using a HttpWebRequest
instance. In the returned
HttpWebResponse, check the
ResponseUri.
Just make sure the AllowAutoRedirect
is set to true on the HttpWebRequest
instance (it is true by default).
(Thx, casperOne)
And the code is
private static string GetRealUrl(string url)
{
WebRequest request = WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Head;
WebResponse response = request.GetResponse();
return response.ResponseUri.ToString();
}
(Thx, Fredrik Mork)
But I want to do it in PHP. HOWTO? :)
The time to try, you already found the answer.
Still, I would have gone with something like this :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://bit.ly/tqdUj");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
var_dump($url);
Some explanations :
the requested URL is the short one
you don't want the headers
you want to make sure the body is not displayed -- probably useless
you do not want the body ; ie, you want a HEAD request, and not GET
you want locations to be followed, of course
once the request has been executed, you want to get the "real" URL that has been fetched
And, here, you get :
string 'http://wordpress.org/extend/plugins/wp-pubsubhubbub/' (length=52)
(Comes from one of the last tweets I saw that contained a short URL)
This should work with any shortening-URL service, independantly of their specific API.
You might also want to tweak some other options, like timeouts ; see curl_setopt for more informations.
<?php
$url = 'http://www.example.com';
print_r(get_headers($url));
print_r(get_headers($url, 1));
?>
Did you read the bit.ly API? specifically here ?
I can't see the issue. Are you talking about possible redirects ?
CREDIT GOES TO http://forums.devshed.com/php-development-5/curl-get-final-url-after-inital-url-redirects-544144.html
function get_web_page( $url )
{
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => true, // return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
//$header['errno'] = $err;
// $header['errmsg'] = $errmsg;
//$header['content'] = $content;
print($header[0]);
return $header;
}
$thisurl = "http://www.example.com/redirectfrom";
$myUrlInfo = get_web_page( $thisurl );
echo $myUrlInfo["url"];
Here is my solution. I coded it, because none of the above worked correctly.
function get_final_location($url, $index=null) {
if (is_array($url)) {
$headers = $url;
}
else {
$headers = get_headers($url, 1)['Location'];
if (count($headers) == 0) {
return $url;
}
}
if (is_null($index)) {
$to_check = end($headers);
$index = count($headers) - 1;
}
else {
$to_check = $headers[$index];
}
if (!filter_var($to_check, FILTER_VALIDATE_URL) === false) {
if (count($headers) - 1 > $index) {
$lp = parse_url($headers[$index], PHP_URL_SCHEME) . "://" . parse_url($headers[$index], PHP_URL_HOST) . $headers[$index+1];
}
else {
$lp = $to_check;
}
}
else {
$index--;
$lp = landingpage($headers, $index);
}
return $lp;
}