bit.ly php api - chopping off querystring parameter after '&' symbol? - php

I've got a Flash app that includes a twitter share for a customized mini application.
I'm achieving this very simply using flashvars passed in via a php querystring so your custom colour and message are passed to the mini-app.
The problem of course is url length for twitter so i'm looking to use the bit.ly api for php to shorten the dynamic url and pass that hashed url back to flash.
I've written a function to do this which works fine however it is chopping off the second querystring parameter after the first '&' symbol?
So for example, the following function running the url 'http://s46264.gridserver.com/apps/soundgirl/fbwall.php?colour=red&message=twittertest'
Gets shortened to http://bit.ly/i4kfj0 which, when parsed becomes http://s46264.gridserver.com/apps/soundgirl/fbwall.php?colour=red
It's chopping off the second querystring parameter. Anyone know of a way I can stop this from happening?
Thanks.
<?php
function bitly_shorten($url)
{
$username = "modernenglish";
$apikey = "myapikey";
$response = file_get_contents("http://api.bit.ly/v3/shorten?login=$username&apiKey=$apikey&longUrl=$url&format=json");
$response = json_decode($response);
if ($response->status_code == 200 && $response->status_txt == "OK")
{
return $response->data->url;
} else
{
return null;
}
}
$link = urldecode("http://s46264.gridserver.com/apps/soundgirl/fbwall.php?colour=red&message=twittertest");
echo bitly_shorten($link);
?>

Maybe try:
No urldecode() before calling bitly_shorten():
$link = "http://s46264.gridserver.com/apps/soundgirl/fbwall.php?colour=red&message=twittertest";
Add urlencode() on the URL into your bitly_shorten() function:
$response = file_get_contents("http://api.bit.ly/v3/shorten?login=$username&apiKey=$apikey&longUrl=".urlencode($url)."&format=json");

Related

How to get values of URL parameters in Laravel?

I'm facing difficulty in fetching URL parameters from redirect URL of Fitbit I'm here trying to integrate Fitbit without using socialite or any other package.
I have the following URL:
http://localhost/abc/public/portal/fitbit/fitbitIntegration#access_token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1WjVLUzUiLCJhdWQiOiIyMjhMNjUiLCJpc3MiOiJGaXRiaXQiLCJ0eXAiOiJhY2Nlc3NfdG9rZW4iLCJzY29wZXMiOiJ3aHIgd251dCB3cHJvIHdzbGUgd3dlaSB3c29jIHdzZXQgd2FjdCB3bG9jIiwiZXhwIjoxNTA1NDU5MTM2LCJpYXQiOjE1MDQ4NzE1MjF9.iQ9nxbzmvar2DlG_848b3MTefq7q0wxyXByTb1Bb2o4&user_id=5Z5KS5&scope=sleep+settings+nutrition+activity+social+heartrate+profile+weight+location&token_type=Bearer&expires_in=587615
All I want to fetch all the information after the # like I want to get user_id here
I have tried this to accomplish
public function fitbitIntegration(Request $request)
{
try{
$authId = Auth::user()->id;
$fitbit = new FitbitMaster();
$fitbit->user_id = $authId;
$fitbit->fitbit_client_id = $request->user_id;
$fitbit->save();
flash('Connected', 'success');
return redirect()->back();
}
catch (QueryException $exception)
{
echo $exception->getMessage();
}
}
Route
Route::get('fitbitIntegration', 'BackEnd\fitbit#fitbitIntegration');
But I'm not getting the user_id here which got me Integrity constraint error
How to get user_id here in my case?
Demo_Link: http://phpfiddle.org/main/code/hdcu-3axu
Store Your Dynamic Url in any variable, in your controller and Do Like This.
<?php
//store your dynamic url in any variable
$url = "http://localhost/abc/public/portal/fitbit/fitbitIntegration#access_token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1WjVLUzUiLCJhdWQiOiIyMjhMNjUiLCJpc3MiOiJGaXRiaXQiLCJ0eXAiOiJhY2Nlc3NfdG9rZW4iLCJzY29wZXMiOiJ3aHIgd251dCB3cHJvIHdzbGUgd3dlaSB3c29jIHdzZXQgd2FjdCB3bG9jIiwiZXhwIjoxNTA1NDU5MTM2LCJpYXQiOjE1MDQ4NzE1MjF9.iQ9nxbzmvar2DlG_848b3MTefq7q0wxyXByTb1Bb2o4&user_id=5Z5KS5&scope=sleep+settings+nutrition+activity+social+heartrate+profile+weight+location&token_type=Bearer&expires_in=587615";
$access_token = substr($url, strpos($url, "#") + 1);
echo $access_token; // get the string of acess token with parametes
?>
UPDATED
NOTE: fragment part of url after the # It's never sent to the server side, So.. its not possible to get the that using any $_SERVER[..] in php but we can read it. So Now we can use JAVA SCRIPT MAGIC do this:
-------------------------------------------------------------------------------
<?php
//Here you Can See save.php page inside an $url where its redirect with your access_token after clicking on `Click Here` link (in your case its redirect routes `fitbitIntegration` as you mentioned ). So i try to create the situation as your routes after its redirect with token, Fine !!
$url = "http://localhost/save.php/fitbitIntegration#access_token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1WjVLUzUiLCJhdWQiOiIyMjhMNjUiLCJpc3MiOiJGaXRiaXQiLCJ0eXAiOiJhY2Nlc3NfdG9rZW4iLCJzY29wZXMiOiJ3aHIgd251dCB3cHJvIHdzbGUgd3dlaSB3c29jIHdzZXQgd2FjdCB3bG9jIiwiZXhwIjoxNTA1NDU5MTM2LCJpYXQiOjE1MDQ4NzE1MjF9.iQ9nxbzmvar2DlG_848b3MTefq7q0wxyXByTb1Bb2o4&user_id=5Z5KS5&scope=sleep+settings+nutrition+activity+social+heartrate+profile+weight+location&token_type=Bearer&expires_in=587615";
?>
<a target="_blank" href="<?php echo $url; ?>"> Click Here </a>
<?php
echo '<br><br><br>';
?>
<!-- Now after redirect you have to use an javascript inside controller or inside an routes directly to aceess the url an getting an access_token, here i try to store inside the cookies of using js and retrieve it using php and echo -->
<?php
echo "<script language='javascript'>
token = window.location.hash.split('#')
document.cookie='access_token='+token[1];
document.cookie='token[1]';
alert(token[1]);
document.cookie='token[1]';
if (token[1] != '') {
//window.location.reload()
//location.reload(true);
}
else{
//document.cookie='token[1]';
}
</script>";
//token_name=$_COOKIE['access_token'];
// Here We get the access token inside the $_COOKIE['access_token'];
if(isset($_COOKIE['access_token'])){
echo $_COOKIE['access_token'];
}
?>
Output:
If you want to get the value after the hash mark or anchor as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in $_SERVER["REQUEST_URI"] or similar predefined variables). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter.
That part is called "fragment". If you have any static url then you can get it in this way:
$url=parse_url("http://localhost/abc/public/portal/fitbit/fitbitIntegration#access_token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1WjVLUzUiLCJhdWQiOiIyMjhMNjUiLCJpc3MiOiJGaXRiaXQiLCJ0eXAiOiJhY2Nlc3NfdG9rZW4iLCJzY29wZXMiOiJ3aHIgd251dCB3cHJvIHdzbGUgd3dlaSB3c29jIHdzZXQgd2FjdCB3bG9jIiwiZXhwIjoxNTA1NDU5MTM2LCJpYXQiOjE1MDQ4NzE1MjF9.iQ9nxbzmvar2DlG_848b3MTefq7q0wxyXByTb1Bb2o4&user_id=5Z5KS5&scope=sleep+settings+nutrition+activity+social+heartrate+profile+weight+location&token_type=Bearer&expires_in=587615");
echo $url["fragment"]; //This variable contains the fragment
you can define a route like fitbitIntegration/{param} and in your function fitbitIntegration, you add param like fitbitIntegration ( Request $req, $param); then you can use regex on your params to get want you want

PHP URL Variable Redirect

I have a login page that submits to another page while adding a string to the end of the url. Would look something like this 'http://example.com?klc' I know I can use $_SERVER["QUERY_STRING"] to get the string, but now I need to use it in a function to direct the user to a different page, based on the string. This is what I have written in the target file
<?php
$access = $_SERVER["QUERY_STRING"];
function user_admin_redirect($access){
if ($access = "ppl"){
redirect_to("ppl_admin.html");}
else ($access = "klc"){
redirect_to("klc_admin.html");}
}
}
user_admin_redirect($access);
but for some reason the script dies. Any tips would be welcomed. Also, I have the system setup on my website, contact me if you are willing to help I can give you a test login.
$access = $_SERVER["QUERY_STRING"];
function user_admin_redirect($access){
if ($access == "ppl"){
redirect_to("ppl_admin.html");}
else if($access == "klc"){
redirect_to("klc_admin.html");}
}
}
user_admin_redirect($access);
You need to use == and not = when using if
You need to use else if and not just else
I am assuming redirect_to is some custom function that you have written which will redirect you to the mentioned page. If not, you should use header('Location: ' . $location);
I don't think redirect_to is a built-in PHP function.
You might need to use
header("Location:".$myPhpScript);
or you could define redirect_to, like:
function redirect_to($location){
header("Location:".$location);
}
See more here:
php redirect_to() function undefined
How to make a redirect in PHP?

CakePHP - sending POST requests in cakephp API and data handling

I have created a CakePHP app and after already set the routes.php files,i can send JSON requests,in order to use my app as an API. For testing,i have created a function which goes like this:
public function api() {
if($this->request->is('post')) {
$data1 = (string)$this->request->data['Model']['data1'];
$data2 = (string)$this->request->data['Model']['data2'];
//logic goes here,it does stuff and $result is the variable where the result of the login is saved
//$data1 and $data2 are used in the logic
$result = 'result';
$this->set('results',$result);
$this->set('_serialize',array('results'));
}
}
I have also created the exact same function with another name,which is meant to be used via a web form and that works correctly. BUT,this code,at this function here,when i POST data (i use Dev HTTP Client chrome extension),it returns the $results variable empty,like it does not receive what i send :/
I send the data as follows via the chrome extension i use:
data1='stuff1'&data2='stuff2'
and it returns me just
{
"results":""
}
(while the same code works perfectly when used without json).
Did i miss something?Does it seem to do something wrong? Please help me a bit around here..
ps:if you need more info,just tell me and i'll post it.
Thank you in advance!
The correct way to access that post would be
$this->request->data['data1'];
to verify what data is being sent do this:
public function api() {
//if($this->request->is('post')) {
$data1 = (string)$this->request->data['Model']['data1'];
$data2 = (string)$this->request->data['Model']['data2'];
//logic goes here,it does stuff and $result is the variable where the result of the login is saved
//$data1 and $data2 are used in the logic
$result = 'result';
//$this->set('results',$result);
$this->set('results',array('root'=>$this->request);
$this->set('_serialize',array('results'));
//}
}

remove GET parameter in URL after processing is finished(not using POST), PHP

I have url like this http://localhost/join/prog/ex.php
When i use GET method the url address like this http://localhost/join/prog/ex.php?name=MEMORY+2+GB&price=20&quantity=2&code=1&search=add
My question is :
so, I still use the GET method but I want to after processing in GET method is finished, I want to the url back(remove parameter) into http://localhost/join/prog/ex.php, as previously (not using POST method). How can i do it?
Put this in your HTML file (HTML5).
<script>
if(typeof window.history.pushState == 'function') {
window.history.pushState({}, "Hide", "http://localhost/join/prog/ex.php");
}
</script>
Or using a backend solution using a session for instance;
<?php
session_start();
if (!empty($_GET)) {
$_SESSION['got'] = $_GET;
header('Location: http://localhost/join/prog/ex.php');
die;
} else{
if (!empty($_SESSION['got'])) {
$_GET = $_SESSION['got'];
unset($_SESSION['got']);
}
//use the $_GET vars here..
}
SIMPLE ANSWER
Just place this in the top of the file you need to make the GET querys disappear from the browser's URL bar after loading.
<script>
if(typeof window.history.pushState == 'function') {
window.history.pushState({}, "Hide", '<?php echo $_SERVER['PHP_SELF'];?>');
}
</script>
i guess after calling the url you want to redirect to the file ex.php , but this time without any parameters.
for that try using the following code in ex.php
<?
if($_GET['name']!='' || $_GET['price']!='' ||$_GET['quantity']!='' ||$_GET['code']!='' || $_GET['search']!=''){
/* here the code checks whether the url contains any parameters or not, if yes it will execute parameters stuffs and it will get redirected to the page http://localhost/join/prog/ex.php without any parameters*/
/* do what ever you wish to do, when the parameters are present. */
echo $name;
print $price;
//etc....
$location="http://localhost/join/prog/ex.php";
echo '<META HTTP-EQUIV="refresh" CONTENT="0;URL='.$location.'">';
exit;
}
else{
/* here rest of the body i.e the codes to be executed after redirecting or without parameters.*/
echo "Hi no parameters present!";
}
?>
here what u did id just redirect redirect to the same page without checking if any parameter is there in the query string. the code intelligently checks for the presence of parameters, id any parameters are there it will redirect to ex.php else it will print "Hi no parameters present!" string!
If you're using apache, consider using a .htaccess file with mod_rewirte.
Here a quickstart. I think this result can be obtained on iis as well with web.config file
You can use removable_query_args filter for that.
add_filter( 'removable_query_args', function( $vars ) {
$vars[] = 'name';
$vars[] = 'price';
$vars[] = 'quantity';
$vars[] = 'code';
$vars[] = 'search';
return $vars;
} );
But you should add specific conditions for your case, otherwise, it will remove these Get-parameters from all other URLs on your site as well.
More info here

How to validate the google video code?

In my project, users insert a Google Video code into a textbox - I'd like to certify that the video being referenced does indeed exist. I'm presently using the YouTube API to do something similar with YouTube references, but I'm not sure what would be the best method with Google Video. Any direction would be appreciated.
Can you request the URL and see if it 404s or not?
function googleVideoExist($id) {
// Validate id however you need to
$id = (int) $id;
$headers = get_headers('http://video.google.com/videoplay?docid=' . $id, TRUE);
// get_headers() follows Location: headers,
// and they are all sent back in sequential order
foreach(array_reverse($headers) as $header => $value) {
if (strstr($value, '200')) {
return TRUE;
}
}
return FALSE;
}
URL above is a guide only - adapt it to suit. Also, you can use cURL if you are more comfortable with that.

Categories