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
Related
ers
I'm attempting to learn how to create a registration and authentication for a website using the slim framework. My objective is to make a handler for POST and when properly authenticated, the website will save and the username and the name. So that the next time the user goes to the page, the website will greet them by stating their name. I will be doing this through two separate PHP files, however I believe the issue is in this PHP file.
Here is what I currently have:
$app->post('/users', function (Request $request, Response $response, array $args) {
$user = array('username'=> $_POST['username'], 'password' => $_POST['password'], 'name' => $_POST['name']);
$res = saveUser($user);
if($result === true) { return $response->withRedirect('login.html', 302); }
return $response->withRedirect('registration.html#',$result,302); });
$app->post('/auth', function (Request $request, Response $response, array $args) {
if(isset($_POST['username']) {
return $response->withRedirect('welcome.php', 302);
}
if(authUser($_POST['username'], $_POST['password']) === true) {
$_SESSION["username"] = $_POST['username'];
$_SESSION["name"] = $_POST['name'];
return $response->withRedirect('welcome.php', 302);
}
else { //authentication doesn't work, destroy session and go to login page
session_destroy();
return $response->withRedirect('login.html',302);
}
To my understanding, the username, password, and the user's actual name should be saved in _POST. However, when I use:
var_dump($_POST);
The password and the username are the only ones that show up when they are being called. Which leads me to believe that this is why my "welcome.php" does not greet the user.
Here is the contents of my welcome.php:
<?php session_start(); ?>
!DOCTYPE html
<title> Welcome! </title>
<h1> Welcome Page </h1>
<section>
<p>
<?php
if(isset($_SESSION['name'])) { echo "Grettings " . $_SESSION['name']. "! ";}
?> Click here to login OR here for registration.
</p>
</section>
I think my error must be how I am trying to call it or within the isset function, but again, I do not know why name has not been properly saved.
It's mostly considered bad form to access the globals this way. As you're running slim, they've a request object available for you to use that you're already passing in:
$myArgs = $request->getQueryParams();
foreach($myArgs as $key => $value){
echo $key . '=>' . $value . PHP_EOL;
}
That said, the cause of your problem is this:
$response->withRedirect(..)
This returns to the browser a http 302 redirect to a new url. This is a second hit. The first hit is a POST to /auth, the second hit is a GET request to /welcome.php
Another thing that jumps out at me is your logic path on /auth. If 'username' is set in $_POST, then you're sending them to welcome.php first thing, the other code (like the call to the authUser(..) function) never get executed. As you are never setting $_SESSION['username'] to anything, it's still blank.
Last thing I'll say is just a style point; I personally try to use single quotes(') for strings whenever possible and avoid double quotes("), as double quotes tell PHP that the string may have special tokens in it that may need parsed. If you're not parsing tokens, just use single quotes. Other than that, welcome to PHP and I'm excited to see what you make!
I am new to PHP and even newer to SESSIONS
I am working with the Instagram API and I am successfully able to authorize an app, and redirect to a page to display content.
My main folder is called Monkey and it has a sub folder called Instagram.
MY callback url for instagram is success.php located in the instagram folder. When I successfully retrieve an access token from Instagram it redirects to the index file in the Monkey folder.
On my success page, I am creating an array full of data called instaArray. I am trying to pass the array from the success.php in the instagram folder, to the index.php in the monkey folder.
My redirect is simply
header( 'Location: ../index.php' );
Because I am new with sessions, I guess I am doing something wrong. I figured it was straight forward, but I suppose not ha.
On the success.php page, after I build the array I have this
session_start();
$_SESSION['instagram'] = $instaArray;
I thought that should create a session that holds my array InstaArray.
Then, on the index.php page in Monkey, I have this
<?php
session_start();
$get_instagram = $_SESSION['instagram'];
print_r($get_instagram);
?>
But absolutely nothing happens. I've even tried to set the session instagram to a simple numerical value or 1, $_SESSION['instagram'] = 1; and get that on the index page, and it doesn't work either.
Am I doing something horribly, terribly wrong? I've read up on sessions, but because it's new, it's still a little confusing.
Thanks for the help, and I hope I was able to explain everything properly.
EDIT: Here is my success.php page in full
<?php
require 'src/db.php';
require 'src/instagram.class.php';
require 'src/instagram.config.php';
// Receive OAuth code parameter
$code = $_GET['code'];
// Check whether the user has granted access
if (true === isset($code)) {
// Receive OAuth token object
$data = $instagram->getOAuthToken($code);
// Take a look at the API response
$username = $data->user->username;
$fullname = $data->user->full_name;
$id = $data->user->id;
$token = $data->access_token;
$user_id = mysql_query("select instagram_id from users where instagram_id='$id'");
if(mysql_num_rows($user_id) == 0) {
mysql_query("insert into users(instagram_username,instagram_name,instagram_id,instagram_access_token) values('$username','$fullname','$id','$token')");
}
//Set Cookie
$Month = 2592000 + time();
setcookie(instagram, $id, $Month);
// Set user access token
$instagram->setAccessToken($token);
// Retrive Data
$instaData = $instagram->getUserFeed();
// Create Instagram Array
$instaArray = array();
$count = 0;
// For each Instagram Post
foreach ($instaData->data as $post) {
$instaArray[$count]['post_id'] = $post->id;
$instaArray[$count]['name'] = $post->user->username;
$instaArray[$count]['profile_img'] = $post->user->profile-picture;
$instaArray[$count]['img_url'] = $post->images->standard_resolution->url;
$instaArray[$count]['caption'] = $post->caption->text;
$instaArray[$count]['like_count'] = $post->likes->count;
$instaArray[$count]['comment_count'] = $post->comments->count;
$instaArray[$count]['created_time'] = $post->created_time; //Unix Format
$count++;
}
// Start Session For Array
session_start();
$_SESSION['instagram'] = serialize($instaArray);
header( 'Location: ../index.php' ) ;
} else {
// Check whether an error occurred
if (true === isset($_GET['error'])) {
echo 'An error occurred: '.$_GET['error_description'];
}
}
?>
Why not use an ID and then cookies rather than sessions + data (which are usually store on the server in text files in a temporary directory)? And keep all data within a database than allow the client to be accessible to the data. Sessions are also temporary.
Note, do you know if you have "globals" on?!
"Please note when working with sessions that a record of a session is not created until a variable has been registered using the session_register() function or by adding a new key to the $_SESSION superglobal array. This holds true regardless of if a session has been started using the session_start() function."
Reference:
http://www.php.net/manual/en/function.session-register.php
make session_start() first line after php
<?php
session_start();
and remove it from anywhere ele on page.
session_start() should be your first line in index.php also as in success.php
Note: The session_start() function must appear BEFORE the tag:
REF : http://www.w3schools.com/php/php_sessions.asp
I think you need to unserialize() your array in index.php.
$get_instagram = unserialize($_SESSION['instagram']);
This has to do with routing. So for getting parameters via url, you basically pass the data to the url following the route format you set.
This is working with links. I created the route, passed the data into the url, and used the request method to get the parameter for use in the controller. like URL::site("site/$color/$size")
What if I am constructing the url by form submission? For example, if I want to create a basic search query.
How do I get my form submission to look like this search/orange/large and not like this search.php?color=orange&size=large when I submit a form via get method.
By definition, the GET method puts the submitted information as URL parameters. If you specifically want to end up with a URL like site/$color/$size, you can use the POST-REDIRECT-GET pattern.
A partial example, from a controller on one of my sites (there is a submit button on the page named clear_cache_button):
public function action_index()
{
$session = Session::instance();
$is_post = (Request::current()->post('submit_button') !== NULL);
$is_clear_cache = (Request::current()->post('clear_cache_button') !== NULL);
$p = Database::instance()->table_prefix();
$people = DB::query(Database::SELECT, "
SELECT *
FROM `".$p."Tabe`;
")->cached(600, $is_clear_cache)->execute()->as_array('RegID');
if ($is_clear_cache)
{
HTTP::redirect(Request::current()->uri());
}
...
...
...
}
You can use Route filters (v3.3) or callbacks (3.1, 3.2) and set route params manually.
You can do it this way...
public function action_index()
{
// this will only be executed if you submmitted a form in your page
if(Arr::get($_POST,'search')){
$errors = '';
$data = Arr::extract($_POST,array('color','size'));
// you can now access data through the $data array:
// $data['color'], $data['size']
// perform validations here
if($data['color']=='') $error = 'Color is required';
elseif($data['size']=='') $error = 'Size is required';
if($error==''){
$this->request->redirect('search/'.$data['color'].'/'.$data['size']);
}
}
// load your search page view here
echo 'this is the search page';
}
Hope this helps you out.
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
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");