Get Facebook Profile URL From Facebook Profile id Using PHP - php

I have a list of Facebook links in xls sheet with Facebook id something like this
and when i go through these links means if i access Facebook with id www.facebook.com/7500
i get urls something like this https://www.facebook.com/davesachs/
so my question is i want to do this with PHP, i have a PHP page which read data from xls sheet
my code here:
require_once 'src/SimpleXLSX.php';
if ( $xlsx = SimpleXLSX::parse('fburl.xlsx') ) {
$rows= $xlsx->rows();
foreach($rows as $data){
echo $data[0].'<br>';
}
} else {
echo SimpleXLSX::parseError();
}
its returning all Facebook link with id same that i am passing like www.facebook.com/7500 but i want it return URL / link of profile as https://www.facebook.com/davesachs/ ,if it is possible please help me to do that.

You can do something like that, Taken reference from here
<?php
require_once 'src/SimpleXLSX.php';
if ( $xlsx = SimpleXLSX::parse('fburl.xlsx') ) {
$rows= $xlsx->rows();
foreach($rows as $data){
getRedirectedUrl($data[0]);
}
} else {
echo SimpleXLSX::parseError();
}
function getRedirectedUrl($link){
$url=$link;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Must be set to true so that PHP follows any "Location:" header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$a = curl_exec($ch); // $a will contain all headers
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // This is what you need, it will return you the last effective URL
// Uncomment to see all headers
/*
echo "<pre>";
print_r($a);echo"<br>";
echo "</pre>";
*/
echo $url; // Voila
}
?>

Related

How to extract and access data from JSON with PHP when some data changes?

I am trying to bring in some API data to a directory in wordpress.
The data I am trying to get is just crypto coin price, none of the other information but because its format is sort of nested (?) it doesnt seem to work.
{
"bitcoin": {
"usd": 16808.82
}
}
This is my code so far:
<?php
$handle = curl_init();
$url = get_post_meta($entity-\>post()-\>ID, '\_drts_field_004', true);
// Set the url
curl_setopt($handle, CURLOPT_URL, $url);
// Set the result output to be a string.
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($handle);
curl_close($handle);
$data = json_decode($output);
echo $output;
var_dump($data);
The results are:
{
"bitcoin":{
"usd":16833.02
}
}
object(stdClass)#10399 (1) {
["bitcoin"]=> object(stdClass)#10492 (1) {
["usd"]=> float(16833.02)
}
}
In this example I am only after the 16833.02
I am trying to do this for lots of different coins, the "usd" will always be the same but the "bitcoin" will change when other coins.
How can I echo only the number?
I have tried lots of variations of echo but cannot get it? Is it possible to do something like:
echo $data['bitcoin']['usd'];
but rather than bitcoin use * ?
As in anything can be there?
You can access the usd value by decoding the JSON to an array instead of an object like this
$data = json_decode($output, true);
$usd = current($data)['usd'];

Need help passing session using header redirect

I am trying to create a 3rd party app for a game I like (EVE Online) which requires oauth.
I have decided to do the oauth handling in it's own script and once resolved, put an associative array into the session based on the CharacterID retrieved from oauth.
I am able to successfully output the desired contents of the session array from the /callback/index.php' that handles the oauth requests at the end of the script. However, I want to keep this script "in the background" and somewhat secret, and redirect most of the activity to a '../main.php' in the directory just below.
However, when I finally get to main.php, printing the session returns an empty array. What am I doing wrong? I have searched all day for solutions and have implemented every one of them.
Below are the relevant files:
session.php
<?php
if (!empty($_GET['ID'])) {
session_id($_GET['ID']);
}
if (session_status() == PHP_SESSION_NONE) {
session_start();
} else {
$sLocation="http://eve.oriigen.com/eClt";
header("Location: ".$sLocation);
exit();
}
?>
/callback/index.php
<?php require_once '../src/session.php' ?>
<?php require_once 'secret.php' ?>
<?php
function auth_error($error_message)
{
print "There's been an error";
error_log($error_message);
exit();
}
$sUserAgent = "EVE Contact List Toolkit [eClt]";
$post_url = "https://login.eveonline.com/oauth/token";
$get_url = "https://login.eveonline.com/oauth/verify";
$client_id="Basic ".base64_encode($sClientId.":".$sSecretKey);
$content_type = "application/x-www-form-urlencoded";
$host_url = "login.eveonline.com";
$aHeaders = array("Authorization: ".$client_id,
"Content-type: ".$content_type,
"Host: ".$host_url);
$aPostFields = array("grant_type"=>"authorization_code",
"code"=>$_GET["code"]);
$oCurlRequest = curl_init();
curl_setopt($oCurlRequest, CURLOPT_URL, $post_url);
curl_setopt($oCurlRequest, CURLOPT_USERAGENT, $sUserAgent);
curl_setopt($oCurlRequest, CURLOPT_HTTPHEADER, $aHeaders);
curl_setopt($oCurlRequest, CURLOPT_POST, count($aPostFields));
curl_setopt($oCurlRequest, CURLOPT_POSTFIELDS, http_build_query($aPostFields));
curl_setopt($oCurlRequest, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($oCurlRequest, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($oCurlRequest, CURLOPT_SSL_VERIFYHOST, 2);
$oResult = curl_exec($oCurlRequest);
if ($oResult===false) {
auth_error(curl_error($oCurlRequest));
}
curl_close($oCurlRequest);
$aResponse=json_decode($oResult);
unset($oCurlRequest);
unset($oResult);
$sTokenType=$aResponse->token_type;
$sAuthToken=$aResponse->access_token;
$iAuthTokenExpire=$aResponse->expires_in;
$sRefreshToken=$aResponse->refresh_token;
$sGetHeader="Authorization: ".$sTokenType." ".$sAuthToken;
$oCurlRequest = curl_init();
curl_setopt($oCurlRequest, CURLOPT_URL, $get_url);
curl_setopt($oCurlRequest, CURLOPT_USERAGENT, $sUserAgent);
curl_setopt($oCurlRequest, CURLOPT_HTTPHEADER, array($sGetHeader));
curl_setopt($oCurlRequest, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($oCurlRequest, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($oCurlRequest, CURLOPT_SSL_VERIFYHOST, 2);
$oResult = curl_exec($oCurlRequest);
if ($oResult===false) {
auth_error(curl_error($oCurlRequest));
}
curl_close($oCurlRequest);
$aResponse=json_decode($oResult);
unset($oCurlRequest);
unset($oResult);
$sCharId=(string)$aResponse->CharacterID;
$sCharacterName=$aResponse->CharacterName;
$sExpiresOn=$aResponse->ExpiresOn;
$sTokenType=$aResponse->TokenType;
$sCharacterOwnerHash=$aResponse->CharacterOwnerHash;
$sIntellectualProperty=$aResponse->IntellectualProperty;
/* $aCharInfo=array("CharID"=>(int)$sCharId,
"CharName"=>$sCharacterName,
"CharOwnerHash"=>$sCharacterOwnerHash,
"ExpiresOn"=>$sExpiresOn,
"AuthToken"=>$sAuthToken,
"AuthTokenExpIn"=>$iAuthTokenExpire,
"RefreshToken"=>$sRefreshToken);*/
if (!isset($_SESSION[(string)$sCharId])) {
$_SESSION[(string)$sCharId]=array("CharID"=>(int)$sCharId,
"CharName"=>$sCharacterName,
"CharOwnerHash"=>$sCharacterOwnerHash,
"ExpiresOn"=>$sExpiresOn,
"AuthToken"=>$sAuthToken,
"AuthTokenExpIn"=>$iAuthTokenExpire,
"RefreshToken"=>$sRefreshToken);
} else {
$_SESSION["moo"]=0;
}
session_write_close();
$sRedirect="../main.php?ID=".session_id();
header("Location: ".$sRedirect);
exit();
/* echo "<pre>";
print_r($_SESSION);
echo "</pre>";
echo "<hr />";
echo gettype($iCharId);
echo "<hr />";
echo "<pre>";
print_r($aCharInfo);
echo "</pre>";*/
?>
../main.php
<?php require_once './src/session.php' ?>
<?php
//echo "SessionId: ".session_id()."<br />";
//echo "<hr/>";
//echo "<pre>";
print_r($_SESSION);
//echo "</pre>";
?>
[ Logout ]
As you can see from the commented sections, I have tried every diagnostic printout I can think of. So, where am I going wrong?
Solved it - per a related question I found only after posting this question:
from here:
The PHP session storage mechanism was originally built around "registering" variables, so the keys in $_SESSION must be names that could be treated as variables in their own right. This means that $_SESSION[10] is invalid, because $10 wouldn't be a valid variable name, and since $foo[10] and $foo['10'] refer to the same thing, $_SESSION['10'] is invalid as well.
CharacterID was either and int of a string version of an int, apparently PHP sessions don't like numbers in their array keys...

Mulitple Instagram feeds on one page

I have successfully put an Instagram feed for a specific user on my website, but having very little experience with PHP I cannot figure out how to simply repeat the process. I'm looking to showcase two different users, side by side in one div.
<?php
// http://jelled.com/instagram/lookup-user-id/
$userid = "userid";
// http://instagram.com/developer/
$clientid = "clientid";
// http://jelled.com/instagram/access-token/
$accessToken = "token";
// number of photos to return
$count = "4";
// Gets our data
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// Pulls and parses data.
$result = fetchData("https://api.instagram.com/v1/users/{$userid}/media/recent/?access_token={$accessToken}&count={$count}");
$result = json_decode($result);
// cycles through the json tree and uses the low res url in the img tag
echo "<ul>";
foreach ($result->data as $photo) {
$img = $photo->images->{$display_size="thumbnail"};
echo "<li><a href='{$photo->link}'><img src='{$img->url}' /></a></li>";
}
echo "</ul>";
?>
If I just paste the code in again, the whole page stops working. I'm guessing this is something simple, but I don't know exactly what I'm looking for! Should this code be in a separate file that is linked into my website- rather than throwing some PHP inside an HTML Bootstrap site?
Thanks in advance.
EDIT
I was able to get this working by using the answer below. I wanted each account to have it's own div, and the only way I know how to do that is in the html file- which would mean I still need to link to two different files. I created one file with the correct code, and another with this:
<?php
// Set User ID here for different profile
//$userid = "idHere";
$userid = "296517730";
$result = fetchData("https://api.instagram.com/v1/users/{$userid}/media/recent/?client_id={$clientid}&count={$count}");
$result = json_decode($result);
// cycles through the json tree and uses the low res url in the img tag
echo "<ul>";
foreach ($result->data as $photo) {
$img = $photo->images->{$display_size="thumbnail"};
echo "<li><a href='{$photo->link}'><img src='{$img->url}' /></a></li>";
}
echo "</ul>";
?>
It was working just fine on my domain, but when I moved it to my client's domain I'm getting this error: Warning: Invalid argument supplied for foreach() in /home/savenors/savenorsmarket.com/bostoninsta.php on line 53
What happened? I'm guessing whatever I did to get this to work wasn't really working.. but it looked fine to me. Any ideas? This is the website: http://www.savenorsmarket.com
Here's code that is working on my machine pulling in twice. It pulls the same user pictures twice, but to fix this just reset the user id variable before making a second call to fetchData();
<?php
$userid = "idHere";
// http://instagram.com/developer/
$clientid = "IDhere";
// number of photos to return
$count = "4";
// Gets our data
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// Pulls and parses data.
$result = fetchData("https://api.instagram.com/v1/users/{$userid}/media/recent/?client_id={$clientid}&count={$count}");
$result = json_decode($result);
// cycles through the json tree and uses the low res url in the img tag
echo "<ul>";
foreach ($result->data as $photo) {
$img = $photo->images->{$display_size="thumbnail"};
echo "<li><a href='{$photo->link}'><img src='{$img->url}' /></a></li>";
}
echo "</ul>";
// Set User ID here for different profile
//$userid = "idHere";
$result = fetchData("https://api.instagram.com/v1/users/{$userid}/media/recent/?client_id={$clientid}&count={$count}");
$result = json_decode($result);
// cycles through the json tree and uses the low res url in the img tag
echo "<ul>";
foreach ($result->data as $photo) {
$img = $photo->images->{$display_size="thumbnail"};
echo "<li><a href='{$photo->link}'><img src='{$img->url}' /></a></li>";
}
echo "</ul>";
?>
Also note that I'm using the client_id over the access_token. It should work either way though.

Gotomeeting php api(oauth) implementation

I am trying to create a php gotomeating api implementation. I successfully got the access_token but for any other requests I get error responses. This is my code:
<?php
session_start();
$key = '#';
$secret = '#';
$domain = $_SERVER['HTTP_HOST'];
$base = "/oauth/index.php";
$base_url = urlencode("http://$domain$base");
$OAuth_url = "https://api.citrixonline.com/oauth/authorize?client_id=$key&redirect_uri=$base_url";
$OAuth_exchange_keys_url = "http://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code={responseKey}&client_id=$key";
if($_SESSION['access_token']) CreateForm();else
if($_GET['send']) OAuth_Authentication($OAuth_url);
elseif($_GET['code']) OAuth_Exchanging_Response_Key($_GET['code'],$OAuth_exchange_keys_url);
function OAuth_Authentication ($url){
$_SESSION['access_token'] = false;
header("Location: $url");
}
function CreateForm(){
$data = getURL('https://api.citrixonline.com/G2M/rest/meetings?oauth_token='.$_SESSION['access_token'],false);
}
function OAuth_Exchanging_Response_Key($code,$url){
if($_SESSION['access_token']){
CreateForm();
return true;
}
$data = getURL(str_replace('{responseKey}',$code,$url));
if(IsJsonString($data)){
$data = json_decode($data);
$_SESSION['access_token'] = $data->access_token;
CreateForm();
}else{
echo 'error';
}
}
/*
* Helper functions
*/
/*
* checks if a string is json
*/
function IsJsonString($str){
try{
$jObject = json_decode($str);
}catch(Exception $e){
return false;
}
return (is_object($jObject)) ? true : false;
}
/*
* CURL function to get url
*/
function getURL($url,$auth_token = false,$data=false){
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if($auth_token){
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: OAuth oauth_token='.$auth_token));
}
if($data){
curl_setopt($ch, CURLOPT_POST,true);
$d = json_encode('{ "subject":"test", "starttime":"2011-12-01T09:00:00Z", "endtime":"2011-12-01T10:00:00Z", "passwordrequired":false, "conferencecallinfo":"test", "timezonekey":"", "meetingtype":"Scheduled" }');
echo implode('&', array_map('urlify',array_keys($data),$data));
echo ';';
curl_setopt($ch, CURLOPT_POSTFIELDS,
implode('&', array_map('urlify',array_keys($data),$data))
);
}
// Get the response and close the channel.
$response = curl_exec($ch);
/*
* if redirect, redirect
*/
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/<a href="(.*?)">/', $response, $matches);
$newurl = str_replace('&','&',trim(array_pop($matches)));
$response = getURL($newurl);
} else {
$code = 0;
}
curl_close($ch);
return $response;
}
function urlify($key, $val) {
return urlencode($key).'='.urlencode($val);
}
to start the connect process you need to make a request to the php file fith send=1. I tryed diffrent atempts to get the list of meetings but could not get a good response.
Did anybody had prev problems with this or know of a solution for this?
Edit:
This is not a curl error, the server responds with error messages, in the forums from citrix they say it should work, no further details on why it dosen't work, if I have a problem with the way I implemented the oauth or the request code. The most comon error I get is: "error code:31305" that is not documented on the forum.
[I also posted this on the Citrix Developer Forums, but for completeness will mention it here as well.]
We are still finalizing the documentation for these interfaces and some parameters which are written as optional are actually required.
Compared to your example above, changes needed are:
set timezonekey to 67 (Pacific time)
set passwordrequired to false
set conferencecallinfo to Hybrid (meaning: both PSTN and VOIP will be provided)
Taking those changes into account, your sample data would look more like the following:
{"subject":"test meeting", "starttime":"2012-02-01T08:00:00",
"endtime":"2012-02-01T09:00:00", "timezonekey":"67",
"meetingtype":"Scheduled", "passwordrequired":"false",
"conferencecallinfo":"Hybrid"}
You can also check out a working PHP sample app I created: http://pastebin.com/zE77qzAz

PHP: Check if URL redirects?

I have implemented a function that runs on each page that I want to restrict from non-logged in users. The function automatically redirects the visitor to the login page in the case of he or she is not logged in.
I would like to make a PHP function that is run from a exernal server and iterates through a number of set URLs (array with URLs that is for each protected site) to see if they are redirected or not. Thereby I could easily make sure if protection is up and running on every page.
How could this be done?
Thanks.
$urls = array(
'http://www.apple.com/imac',
'http://www.google.com/'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
foreach($urls as $url) {
curl_setopt($ch, CURLOPT_URL, $url);
$out = curl_exec($ch);
// line endings is the wonkiest piece of this whole thing
$out = str_replace("\r", "", $out);
// only look at the headers
$headers_end = strpos($out, "\n\n");
if( $headers_end !== false ) {
$out = substr($out, 0, $headers_end);
}
$headers = explode("\n", $out);
foreach($headers as $header) {
if( substr($header, 0, 10) == "Location: " ) {
$target = substr($header, 10);
echo "[$url] redirects to [$target]<br>";
continue 2;
}
}
echo "[$url] does not redirect<br>";
}
I use curl and only take headers, after I compare my url and url from header curl:
$url="http://google.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, '60'); // in seconds
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
if(curl_getinfo($ch)['url'] == $url){
echo "not redirect";
}else {
echo "redirect";
}
You could always try adding:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
since 302 means it moved, allow the curl call to follow it and return whatever the moved url returns.
Getting the headers with get_headers() and checking if Location is set is much simpler.
$urls = [
"https://example-1.com",
"https://example-2.com"
];
foreach ($urls as $key => $url) {
$is_redirect = does_url_redirect($url) ? 'yes' : 'no';
echo $url . ' is redirected: ' . $is_redirect . PHP_EOL;
}
function does_url_redirect($url){
$headers = get_headers($url, 1);
if (!empty($headers['Location'])) {
return true;
} else {
return false;
}
}
I'm not sure whether this really makes sense as a security check.
If you are worried about files getting called directly without your "is the user logged in?" checks being run, you could do what many big PHP projects do: In the central include file (where the security check is being done) define a constant BOOTSTRAP_LOADED or whatever, and in every file, check for whether that constant is set.
Testing is great and security testing is even better, but I'm not sure what kind of flaw you are looking to uncover with this? To me, this idea feels like a waste of time that will not bring any real additional security.
Just make sure your script die() s after the header("Location:...") redirect. That is essential to stop additional content from being displayed after the header command (a missing die() wouldn't be caught by your idea by the way, as the redirect header would still be issued...)
If you really want to do this, you could also use a tool like wget and feed it a list of URLs. Have it fetch the results into a directory, and check (e.g. by looking at the file sizes that should be identical) whether every page contains the login dialog. Just to add another option...
Do you want to check the HTTP code to see if it's a redirect?
$params = array('http' => array(
'method' => 'HEAD',
'ignore_errors' => true
));
$context = stream_context_create($params);
foreach(array('http://google.com', 'http://stackoverflow.com') as $url) {
$fp = fopen($url, 'rb', false, $context);
$result = stream_get_contents($fp);
if ($result === false) {
throw new Exception("Could not read data from {$url}");
} else if (! strstr($http_response_header[0], '301')) {
// Do something here
}
}
I hope it will help you:
function checkRedirect($url)
{
$headers = get_headers($url);
if ($headers) {
if (isset($headers[0])) {
if ($headers[0] == 'HTTP/1.1 302 Found') {
//this is the URL where it's redirecting
return str_replace("Location: ", "", $headers[9]);
}
}
}
return false;
}
$isRedirect = checkRedirect($url);
if(!$isRedirect )
{
echo "URL Not Redirected";
}else{
echo "URL Redirected to: ".$isRedirect;
}
You can use session,if the session array is not set ,the url redirected to a login page.
.
I modified Adam Backstrom answer and implemented chiborg suggestion. (Download only HEAD). It have one thing more: It will check if redirection is in a page of the same server or is out. Example: terra.com.br redirects to terra.com.br/portal. PHP will considerate it like redirect, and it is correct. But i only wanted to list that url that redirect to another URL. My English is not good, so, if someone found something really difficult to understand and can edit this, you're welcome.
function RedirectURL() {
$urls = array('http://www.terra.com.br/','http://www.areiaebrita.com.br/');
foreach ($urls as $url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// chiborg suggestion
curl_setopt($ch, CURLOPT_NOBODY, true);
// ================================
// READ URL
// ================================
curl_setopt($ch, CURLOPT_URL, $url);
$out = curl_exec($ch);
// line endings is the wonkiest piece of this whole thing
$out = str_replace("\r", "", $out);
echo $out;
$headers = explode("\n", $out);
foreach($headers as $header) {
if(substr(strtolower($header), 0, 9) == "location:") {
// read URL to check if redirect to somepage on the server or another one.
// terra.com.br redirect to terra.com.br/portal. it is valid.
// but areiaebrita.com.br redirect to bwnet.com.br, and this is invalid.
// what we want is to check if the address continues being terra.com.br or changes. if changes, prints on page.
// if contains http, we will check if changes url or not.
// some servers, to redirect to a folder available on it, redirect only citting the folder. Example: net11.com.br redirect only to /heiden
// only execute if have http on location
if ( strpos(strtolower($header), "http") !== false) {
$address = explode("/", $header);
print_r($address);
// $address['0'] = http
// $address['1'] =
// $address['2'] = www.terra.com.br
// $address['3'] = portal
echo "url (address from array) = " . $url . "<br>";
echo "address[2] = " . $address['2'] . "<br><br>";
// url: terra.com.br
// address['2'] = www.terra.com.br
// check if string terra.com.br is still available in www.terra.com.br. It indicates that server did not redirect to some page away from here.
if(strpos(strtolower($address['2']), strtolower($url)) !== false) {
echo "URL NOT REDIRECT";
} else {
// not the same. (areiaebrita)
echo "SORRY, URL REDIRECT WAS FOUND: " . $url;
}
}
}
}
}
}
function unshorten_url($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$out = curl_exec($ch);
$real_url = $url;//default.. (if no redirect)
if (preg_match("/location: (.*)/i", $out, $redirect))
$real_url = $redirect[1];
if (strstr($real_url, "bit.ly"))//the redirect is another shortened url
$real_url = unshorten_url($real_url);
return $real_url;
}
I have just made a function that checks if a URL exists or not
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
function url_exists($url, $ch) {
curl_setopt($ch, CURLOPT_URL, $url);
$out = curl_exec($ch);
// line endings is the wonkiest piece of this whole thing
$out = str_replace("\r", "", $out);
// only look at the headers
$headers_end = strpos($out, "\n\n");
if( $headers_end !== false ) {
$out = substr($out, 0, $headers_end);
}
//echo $out."====<br>";
$headers = explode("\n", $out);
//echo "<pre>";
//print_r($headers);
foreach($headers as $header) {
//echo $header."---<br>";
if( strpos($header, 'HTTP/1.1 200 OK') !== false ) {
return true;
break;
}
}
}
Now I have used an array of URLs to check if a URL exists as following:
$my_url_array = array('http://howtocode.pk/result', 'http://google.com/jobssss', 'https://howtocode.pk/javascript-tutorial/', 'https://www.google.com/');
for($j = 0; $j < count($my_url_array); $j++){
if(url_exists($my_url_array[$j], $ch)){
echo 'This URL "'.$my_url_array[$j].'" exists. <br>';
}
}
I can't understand your question.
You have an array with URLs and you want to know if user is from one of the listed URLs?
If I'm right in understanding your quest:
$urls = array('http://url1.com','http://url2.ru','http://url3.org');
if(in_array($_SERVER['HTTP_REFERER'],$urls))
{
echo 'FROM ARRAY';
} else {
echo 'NOT FROM ARR';
}

Categories