I Want direct link of user's profile picture
i Have Following Code
$img = file_get_contents("https://graph.facebook.com/" . $fid . "/picture?type=large");
$file = dirname(__file__). "/" . $fid . ".jpg";
file_put_contents($file, $img);
But https://graph.facebook.com/" . $fid . "/picture?type=large Have a Redirection. How do i follow the redirection? is there any way to do it via file_get_contents? I know i can do it via curl But It Seems complicated i got error that safe_mode is on and i don't know how to off it.
Thanks You
You should be able follow redirects with file_get_contents by giving it a third parameter $context – in which you set the HTTP context option follow_location to 1.
(Although this should already be the default, and in my test getting the image data worked with file_get_contents alone already.)
Her is the code that I am using and it works perfect for me. It also saves the picture to my server so I then have a local url (which can then be posted either back to the same user's profile or to the wall of another user/page/event/etc.) All you have to do is place it in your code where $user has a value and it should work just fine.
<?
$uid = $user;
function GetTheImage($linky) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_URL, $linky);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
# ADDED LINE:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$userpicture = "http://graph.facebook.com/$uid/picture?type=large";
$sourceurl = GetTheImage($userpicture);
$save = fopen("/home/arose/public_html/mydomain.com/tmp/$uid-large.jpg", "w"); //this is name of new file that i save
fwrite($save, $sourceurl);
fclose($save);
?>
<html>
<head>
</head>
<body>
<img src="./tmp/<? echo $uid; ?>-large.jpg" />
</body>
</html>
<?php
$fbid=$user_profile['id'];
$pic = file_get_contents("https://graph.facebook.com/$fbid/picture?type=large");
$filename = $fbid.".jpg";
$path="images/".$filename;
file_put_contents($path, $pic);
?>
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
function curl_redir_exec($ch)
{
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);
#list($header, $data) = #explode("\n\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)));
if (!$url)
{
//couldn't process the url to redirect to
$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']:'');
return $new_url;
} else {
$curl_loops=0;
return $data;
}
}
function get_right_url($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
return curl_redir_exec($curl);
}
$url = 'http://graph.facebook.com/' . $fbid . '/picture?type=large';
$file_handler = fopen('img/avatar/'.$fbid.'.jpg', 'w');
$curl = curl_init(get_right_url($url));
curl_setopt($curl, CURLOPT_FILE, $file_handler);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_exec($curl);
curl_close($curl);
fclose($file_handler);
Related
I'm trying to create a subdomain dynamically with php so that everytime someone creates a user they also create a subdomain.
I seems all the answers I can find is the same and they just don't work.
I.e this is the code most suggest:
function createDomain($domain) {
// your cPanel username
$cpanel_user = 'username';
$cpanel_pass = 'pass';
$cpanel_skin = 'paper_lantern';
$cpanel_host = 'mydomainname.com';
$subdomain = $domain;
// directory - defaults to public_html/subdomain_name
$dir = 'public_html/user_site';
// create the subdomain
$sock = fsockopen($cpanel_host,2082);
if(!$sock) {
print('Socket error');
exit();
}
$pass = base64_encode("$cpanel_user:$cpanel_pass");
$in = "GET /frontend/$cpanel_skin/subdomain/doadddomain.html?rootdomain=$cpanel_host&domain=$subdomain&dir=$dir\r\n";
$in .= "HTTP/1.0\r\n";
$in .= "Host:$cpanel_host\r\n";
$in .= "Authorization: Basic $pass\r\n";
$in .= "\r\n";
fputs($sock, $in);
while (!feof($sock)) {
$result = fgets($sock, 128);
}
fclose($sock);
return $result;
}
createDomain('testing');
When I try to use the link directly in browser to see what happens, the cpanel tells me there was something wrong with the security token and I get a login form.
Therefore I tried making a call to generate a security token:
function createSession() { // Example details
$ip = "example.com";
$cp_user = "username";
$cp_pwd = "password";
$url = "https://example.com:2083/login";
$cookies = "/path/to/storage/for/cookies.txt";
// Create new curl handle
$ch=curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookies); // Save cookies to
curl_setopt($ch, CURLOPT_POSTFIELDS, "user=$cp_user&pass=$cp_pwd");
curl_setopt($ch, CURLOPT_TIMEOUT, 100020);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Execute the curl handle and fetch info then close streams.
$f = curl_exec($ch);
$h = curl_getinfo($ch);
curl_close($ch);
// If we had no issues then try to fetch the cpsess
if ($f == true and strpos($h['url'],"cpsess")){
// Get the cpsess part of the url
$pattern="/.*?(\/cpsess.*?)\/.*?/is";
$preg_res=preg_match($pattern,$h['url'],$cpsess);
}
// If we have a session then return it otherwise return empty string
$token = (isset($cpsess[1])) ? $cpsess[1] : "";
}
$test = createSession();
It successfully creates the token. I then tried sending the security token through to the other call, so it would be something like this:
$token . "/frontend/paper_lantern/subdomain/doadddomain.html?rootdomain=" . $main_domain . "&domain=" . $sub_domain_name . "&dir=public_html/subdomains/" . $sub_domain_name
but nothing happens, no errors, no subdomain is created. How can I make this work?
After alot of trying and looking, I finally figured it out. I made it into a class so it would be easy to use for me, and anyone else looking.
class Subdomain {
const CP_user = env('CPANEL_USER', 'forge');
const CP_password = env('CPANEL_PASSWORD', 'forge');
const DOMAIN = env('CPANEL_DOMAIN', 'forge');
const URL = env('CPANEL_URL', 'forge');
public $token = "";
public function __construct() {
$token = self::createSession();
$this->token = $token;
}
private function createSession() {
$url = self::URL . "login";
$cookies = "/path/to/storage/for/cookies.txt";
// Create new curl handle
$ch=curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookies); // Save cookies to
curl_setopt($ch, CURLOPT_POSTFIELDS, "user=" . self::CP_user . "&pass=". self::CP_password);
curl_setopt($ch, CURLOPT_TIMEOUT, 100020);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Execute the curl handle and fetch info then close streams.
$f = curl_exec($ch);
$h = curl_getinfo($ch);
curl_close($ch);
// If we had no issues then try to fetch the cpsess
if ($f == true and strpos($h['url'],"cpsess")){
// Get the cpsess part of the url
$pattern="/.*?(\/cpsess.*?)\/.*?/is";
$preg_res=preg_match($pattern,$h['url'],$cpsess);
}
// If we have a session then return it otherwise return empty string
$token = (isset($cpsess[1])) ? $cpsess[1] : "";
return $token;
}
private function get_query( $action, $subdomain ){
$directory = $subdomain . "." . self::DOMAIN;
switch ($action) {
case 'create':
$query = self::URL . $this->token . "/json-api/cpanel?cpanel_jsonapi_func=addsubdomain&cpanel_jsonapi_module=SubDomain&cpanel_jsonapi_version=2&domain=$subdomain&rootdomain=" . self::DOMAIN . "&dir=$directory";
break;
case 'delete':
$query = self::URL . $this->token . "/json-api/cpanel?cpanel_jsonapi_func=delsubdomain&cpanel_jsonapi_module=SubDomain&cpanel_jsonapi_version=2&domain=".$subdomain.'.'.self::DOMAIN."&dir=$directory";
break;
case 'delete_dir':
$query = self::URL . $this->token . "/json-api/cpanel?cpanel_jsonapi_module=Fileman&cpanel_jsonapi_func=fileop&op=unlink&sourcefiles=$directory";
break;
}
return $query;
}
public function create($subdomain){
$query = self::get_query( 'create', $subdomain );
self::request($query);
}
public function delete($subdomain){
$query = self::get_query( 'delete', $subdomain );
$query_dir = self::get_query( 'delete_dir', $subdomain );
self::request($query, $query_dir);
}
public function request($query, $dir = false){
$curl = curl_init(); // Create Curl Object
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0); // Allow self-signed certs
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0); // Allow certs that do not match the hostname
curl_setopt($curl, CURLOPT_HEADER,0); // Do not include header in output
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); // Return contents of transfer on curl_exec
$header[0] = "Authorization: Basic " . base64_encode(self::CP_user.":".self::CP_password) . "\n\r";
curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // set the username and password
curl_setopt($curl, CURLOPT_URL, $query); // execute the query
$result = curl_exec($curl);
if ($result == false) {
error_log("curl_exec threw error \"" . curl_error($curl) . "\" for $query");
}
curl_close($curl);
if ($dir) {
self::request($dir);
}
print $result;
}
}
// how to use
$new_url = new Subdomain();
$new_url->create('mypage');
$new_url->delete('mypage');
Notes:
- I put the private variables in the .env file.
- The delete will delete the subdomain as well as the directory.
- The delete does not delete the DNS that is created, still haven't looked into that yet.
I have some problem that related to HTTP_HEADERS in curl php in opencart. The code below is caller.
$ch = curl_init();
$url = 'http://aaa.com/index.php?route=common/home/getTotalCustomer';
$url2 = 'http://bbb.com/index.php?route=common/home/getTotalCustomer';
$url3 = 'http://ccc.com/index.php?route=common/home/getTotalCustomer';
$header = array('Authorization:Basic ' . base64_encode('user:password'));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$results = curl_exec($ch);
echo '<pre>';
print_r(json_decode($results, true));
echo '</pre>';
The receiver code like below:
public function getTotalCustomer(){
$json = array();
$this->load->model('account/customer');
if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])){
if(($_SERVER['PHP_AUTH_PW'] == 'password') && ($_SERVER['PHP_AUTH_USER'] == 'user')){
$json['total_customer'] = $this->model_account_customer->getTotalCustomer();
}
} else{
$json['message'] = 'failed';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
I had tried in multiple domain with different servers. Some server can return the data but some server cannot return the data. Why?
Your header that you're sending is incorrect.
You're passing
Authorization:Basic <username:password>
it should be
Authorization: Basic <username:password>
note the space.
I am creating a checkout process in PHP and have 4 stages/pages. Each page collects different information about the user etc and the 4th stage/page is the secure checkout page which is hosted externally and accepts a POST form submission (from stage 3).
All would be fine however I need to validate the data in stage 3 before I send the user on to the external stage 4 so I looked into this and found this article on cURL...
http://www.html-form-guide.com/php-form/php-form-submit.html
All looked great but it only seems to post the data to the external 4th page but I need the user to actually be taken there at the same time so they see the 4th page. Ive tried...
header('Location: http://externalURLLink');
...straight after the cURL connection is closed but it didn't work.
The obvious way is to have a page that basically says "Now click here to go to our secure payment page but I would rather not do that.
Any suggestions?
Thanks
You could try the following function which may work for you:
function curl_redir_exec($ch,$test = false)
{
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);
list($header, $data) = explode("\n\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)));
if (!$url){
//couldn't process the url to redirect to
$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);
return $this->curl_redir_exec($ch);
} else {
$curl_loops=0;
if($test){
return curl_getinfo($ch, CURLINFO_EFFECTIVE_URL).'<br />'.$http_code.'<br />'.$data;
}else{
return curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
}
}
}
You would use it like this:
$curl_session = curl_init($DESTINATION_URL);
curl_setopt($curl_session, CURLOPT_URL, $DESTINATION_URL);
curl_setopt($curl_session, CURLOPT_COOKIESESSION, 1);
curl_setopt($curl_session, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($curl_session, CURLOPT_HTTPHEADER, array('X-Forwarded-For: '.$_SERVER['REMOTE_ADDR']));
curl_setopt($curl_session, CURLOPT_VERBOSE, 1);
curl_setopt($curl_session, CURLOPT_POST, 1);
curl_setopt($curl_session, CURLOPT_POSTFIELDS, $POST_DATA);
curl_setopt($curl_session, CURLOPT_TIMEOUT, 30);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, FALSE);
$redirect_url = $shop->curl_redir_exec($curl_session);
if(curl_errno($curl_session))
{
echo '<p>An error has occurred, please take note of the information below and contact support.</p>';
echo "<br>Errno : ".curl_errno($curl_session) ."<br>";
echo "<br>Error : ".curl_error($curl_session) ."<br>";
die();
}
curl_close($curl_session);
header("location:$redirect_url");
Hope this is useful.
Try curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
I'm trying to use Spreadshirt API to create a product on their platform, but i'm stuck with this weird error:
Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /home/anarchoi/public_html/test.php:102 Stack trace: #0 /home/anarchoi/public_html/test.php(102): SimpleXMLElement->__construct('') #1 {main} thrown in /home/anarchoi/public_html/test.php on line 102
Most of the code is just copied from their wiki so i really don't understand why it doesn't work.
I'm looking for help to understand where the error is coming from and why it is happening.
$productTypeId = "210";
$printTypeId = "17";
$printColorIds = "13,20";
$productTypeAppearanceId = "1";
$productTypePrintAreaId = "4";
$designId = "10438193";
// 1. Get shop data
$shopUrl = "http://api.spreadshirt.com/api/v1/shops/266497";
$ch = curl_init($shopUrl);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
// Close the handle
curl_close($ch);
$shop = new SimpleXMLElement($result);
$namespaces = $shop->getNamespaces(true);
// 2. Get product type data
$attributes = $shop->productTypes->attributes($namespaces['xlink']);
$productTypeUrl = $attributes->href . "/" . $productTypeId;
$ch = curl_init($productTypeUrl);
// echo "<br>$productTypeUrl<br>";
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
// Close the handle
curl_close($ch);
$productType = new SimpleXMLElement($result);
// 3. Get design data
$attributes = $shop->designs->attributes($namespaces['xlink']);
$designUrl = $attributes->href . "/" . $designId;
$ch = curl_init($designUrl);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
// Close the handle
curl_close($ch);
$design = new SimpleXMLElement($result);
// 4. Prepare product
// get positioning data for selected product type
$printArea = null;
foreach ($productType->printAreas->printArea as $current) {
if ($current['id'] == $productTypePrintAreaId) {
$printArea = $current;
}
}
$product = new SimpleXMLElement(getFileData("product.xml"));
$product->productType['id'] = $productTypeId;
$product->appearance['id'] = $productTypeAppearanceId;
$configuration = $product->configurations->configuration;
$configuration->printArea['id'] = $productTypePrintAreaId;
$configuration->printType['id'] = $printTypeId;
$configuration->offset->x =
((doubleval($printArea->boundary->size->width) - doubleval($design->size->width)) / 2);
$configuration->offset->y =
((doubleval($printArea->boundary->size->height) - doubleval($design->size->height)) / 4);
$image = $product->configurations->configuration->content->svg->image;
$image['width'] = $design->size->width;
$image['height'] = $design->size->height;
$image['designId'] = $designId;
$image['printColorIds'] = $printColorIds;
// 5. Create product
$attributes = $shop->products->attributes($namespaces['xlink']);
$productsUrl = $attributes->href;
$header = array();
$header[] = createSprdAuthHeader("POST", $productsUrl);
$header[] = "Content-Type: application/xml";
$ch = curl_init("$productsUrl"."?fullData=true");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $product->asXML());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$result = curl_exec($ch);
// Close the handle
curl_close($ch);
$productUrl = parseHttpHeaders($result, "Location");
$ch = curl_init($productUrl);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
// Close the handle
curl_close($ch);
$product = new SimpleXMLElement($result);
$resource = $product->resources->resource[0];
$attributes = $resource->attributes($namespaces['xlink']);
echo '<html><body>';
echo 'Product available at: ' . $productUrl . '</br>';
echo 'Product image is available at: ' . $attributes->href . '</br>';
echo '<img src="' . $attributes->href . '?width=1000"/>';
echo '</body></html>';
function createSprdAuthHeader($method, $url) {
$apiKey = "***";
$secret = "***";
$time = time()*1000;
$data = "$method $url $time";
$sig = sha1("$data $secret");
return "Authorization: SprdAuth apiKey=\"$apiKey\", data=\"$data\", sig=\"$sig\"";
}
function parseHttpHeaders( $header, $headername ) {
$retVal = array();
$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
foreach( $fields as $field ) {
if( preg_match('/('.$headername.'): (.+)/m', $field, $match) ) {
return $match[2];
}
}
return $retVal;
}
function getFileData($file) {
$fp = fopen($file, "r");
$data = "";
while(!feof($fp)) {
$data .= fgets($fp, 1024);
}
fclose($fp);
return $data;
}
product.xml = https://www.ni-dieu-ni-maitre.com/product.xml
I stumbled upon similar issue when implementing Spreadshirt, looks like their API server is sending (at least some) content gzipped regardless of any Accept-Encoding headers. You can tell that it's your case by var_dumping the string before it's passed to SimpleXMLElement (as suggested by others) – if it's gibberish, it's very possible you have the same issue as I did.
Setting the curl option of CURLOPT_ENCODING to an empty string ('') fixed that for me – it "magically" turned on ungzipping the response (see man page for curl_setopt() for more information).
I'm trying to code a redirect checker, to check if a URL is search engine friendly. It has to check if a URL is redirected or not, and if it's redirected it has to tell if it's SEO friendly (301 status code) or not (302/304).
Here's something similiar I've found: http://www.webconfs.com/redirect-check.php
It also should be able to follow multiple redirects (e.g. from A to B to C) and tell me that A redirects to C.
This is what I got so far, but it doesn't work quite right (example: when typing in www.example.com it doesnt find the redirect to www.example.com/page1)
<?php
// You can edit the messages of the respective code over here
$httpcode = array();
$httpcode["200"] = "Ok";
$httpcode["201"] = "Created";
$httpcode["302"] = "Found";
$httpcode["301"] = "Moved Permanently";
$httpcode["304"] = "Not Modified";
$httpcode["400"] = "Bad Request";
if(count($_POST)>0)
{
$url = $_POST["url"];
$curlurl = "http://".$url."/";
$ch = curl_init();
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $curlurl);
// User agent
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
// 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, 15);
// Download the given URL, and return output
$output = curl_exec($ch);
$curlinfo = curl_getinfo($ch);
if(($curlinfo["http_code"]=="301") || ($curlinfo["http_code"]=="302"))
{
$ch = curl_init();
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $curlurl);
// User agent
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
// 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, 15);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// Download the given URL, and return output
$output = curl_exec($ch);
$curlinfo = curl_getinfo($ch);
echo $url." is redirected to ".$curlinfo["url"];
}
else
{
echo $url." is not getting redirected";
}
// Close the cURL resource, and free system resources
curl_close($ch);
}
?>
<form action="" method="post">
http://<input type="text" name="url" size="30" />/ <b>e.g. www.google.com</b><br/>
<input type="submit" value="Submit" />
</form>
Well if you want to record every redirect you have to implement it yourself and turn off the automatic "location following":
function curl_trace_redirects($url, $timeout = 15) {
$result = array();
$ch = curl_init();
$trace = true;
$currentUrl = $url;
$urlHist = array();
while($trace && $timeout > 0 && !isset($urlHist[$currentUrl])) {
$urlHist[$currentUrl] = true;
curl_setopt($ch, CURLOPT_URL, $currentUrl);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
$output = curl_exec($ch);
if($output === false) {
$traceItem = array(
'errorno' => curl_errno($ch),
'error' => curl_error($ch),
);
$trace = false;
} else {
$curlinfo = curl_getinfo($ch);
if(isset($curlinfo['total_time'])) {
$timeout -= $curlinfo['total_time'];
}
if(!isset($curlinfo['redirect_url'])) {
$curlinfo['redirect_url'] = get_redirect_url($output);
}
if(!empty($curlinfo['redirect_url'])) {
$currentUrl = $curlinfo['redirect_url'];
} else {
$trace = false;
}
$traceItem = $curlinfo;
}
$result[] = $traceItem;
}
if($timeout < 0) {
$result[] = array('timeout' => $timeout);
}
curl_close($ch);
return $result;
}
// apparently 'redirect_url' is not available on all curl-versions
// so we fetch the location header ourselves
function get_redirect_url($header) {
if(preg_match('/^Location:\s+(.*)$/mi', $header, $m)) {
return trim($m[1]);
}
return "";
}
And you use it like that:
$res = curl_trace_redirects("http://www.example.com");
foreach($res as $item) {
if(isset($item['timeout'])) {
echo "Timeout reached!\n";
} else if(isset($item['error'])) {
echo "error: ", $item['error'], "\n";
} else {
echo $item['url'];
if(!empty($item['redirect_url'])) {
// redirection
echo " -> (", $item['http_code'], ")";
}
echo "\n";
}
}
It's possible that my code isn't fully thought out, but I guess it's a good start.
Edit
Here's some sample Output:
http://midas/~stefan/test/redirect/fritzli.html -> (302)
http://midas/~stefan/test/redirect/hansli.html -> (301)
http://midas/~stefan/test/redirect/heiri.html