How to get token in php

(PECL OAuth >= 0.99.1)

OAuth::getAccessTokenFetch an access token

Description

public OAuth::getAccessToken(
    string $access_token_url,
    string $auth_session_handle = ?,
    string $verifier_token = ?,
    string $http_method = ?
): array

Parameters

access_token_url

URL to the access token API.

auth_session_handle

Authorization session handle, this parameter does not have any citation in the core OAuth 1.0 specification but may be implemented by large providers. » See ScalableOAuth for more information.

verifier_token

For service providers which support 1.0a, a verifier_token must be passed while exchanging the request token for the access token. If the verifier_token is present in $_GET or $_POST it is passed automatically and the caller does not need to specify a verifier_token (usually if the access token is exchanged at the oauth_callback URL). » See ScalableOAuth for more information.

http_method

HTTP method to use, e.g. GET or POST.

Return Values

Returns an array containing the parsed OAuth response on success or false on failure.

Changelog

VersionDescription
PECL oauth 1.0.0 Previously returned null on failure, instead of false.
PECL oauth 0.99.9 The verifier_token parameter was added

Examples

Example #1 OAuth::getAccessToken() example

try {
    
$oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET);
    
$oauth->setToken($request_token,$request_token_secret);
    
$access_token_info $oauth->getAccessToken("https://example.com/oauth/access_token");
    if(!empty(
$access_token_info)) {
        
print_r($access_token_info);
    } else {
        print 
"Failed fetching access token, response was: " $oauth->getLastResponse();
    }
} catch(
OAuthException $E) {
    echo 
"Response: "$E->lastResponse "\n";
}
?>

The above example will output something similar to:

Array
(
    [oauth_token] => some_token
    [oauth_token_secret] => some_token_secret
)

See Also

  • OAuth::getLastResponse() - Get the last response
  • OAuth::getLastResponseInfo() - Get HTTP information about the last response
  • OAuth::setToken() - Sets the token and secret

There are no user contributed notes for this page.

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

token_get_allSplit given source into PHP tokens

Description

token_get_all(string $code, int $flags = 0): array

For a list of parser tokens, see List of Parser Tokens, or use token_name() to translate a token value into its string representation.

Parameters

code

The PHP source to parse.

flags

Valid flags:

  • TOKEN_PARSE - Recognises the ability to use reserved words in specific contexts.

Return Values

An array of token identifiers. Each individual token identifier is either a single character (i.e.: ;, ., >, !, etc...), or a three element array containing the token index in element 0, the string content of the original token in element 1 and the line number in element 2.

Examples

Example #1 token_get_all() example

$tokens token_get_all('');

foreach (

$tokens as $token) {
    if (
is_array($token)) {
        echo 
"Line {$token[2]}: "token_name($token[0]), " ('{$token[1]}')"PHP_EOL;
    }
}
?>

The above example will output something similar to:

Line 1: T_OPEN_TAG ('')

Example #2 token_get_all() incorrect usage example

$tokens token_get_all('/* comment */');

foreach (

$tokens as $token) {
    if (
is_array($token)) {
        echo 
"Line {$token[2]}: "token_name($token[0]), " ('{$token[1]}')"PHP_EOL;
    }
}
?>

The above example will output something similar to:

Line 1: T_INLINE_HTML ('/* comment */')

Note in the previous example that the string is parsed as T_INLINE_HTML rather than the expected T_COMMENT. This is because no open tag was used in the code provided. This would be equivalent to putting a comment outside of the PHP tags in a normal file.

Example #3 token_get_all() on a class using a reserved word example

$source

= <<<'code'
class A
{
    const PUBLIC = 1;
}

code;$tokens token_get_all($sourceTOKEN_PARSE);

foreach (

$tokens as $token) {
    if (
is_array($token)) {
        echo 
token_name($token[0]) , PHP_EOL;
    }
}
?>

The above example will output something similar to:

T_OPEN_TAG
T_WHITESPACE
T_CLASS
T_WHITESPACE
T_STRING
T_CONST
T_WHITESPACE
T_STRING
T_LNUMBER

Without the TOKEN_PARSE flag, the penultimate token (T_STRING) would have been T_PUBLIC.

See Also

  • PhpToken::tokenize() - Splits given source into PHP tokens, represented by PhpToken objects.
  • token_name() - Get the symbolic name of a given PHP token

gomodo at free dot fr

13 years ago

Yes, some problems (On WAMP, PHP 5.3.0 ) with get_token_all()

1 : bug line numbers
Since PHP 5.2.2 token_get_all()  should return Line numbers in element 2..
.. but for instance (5.3.0 on WAMP), it work perfectly only with PHP code (not HMTL miwed), but if you have some T_INLINE_HTML detected by token_get_all() ,  sometimes you find wrongs line numbers  (return next line)... :(

2: bug warning message can impact loops
Warning with php code uncompleted (ex : php code line by line) :
for example if a comment tag is not closed  token_get_all()  can block loops on this  warning :
Warning: Unterminated comment starting line

This problem seem not occur in CLI mod (php command line), but only in web mod.

Waiting more stability, used token_get_all()  only on PHP code (not HMTL miwed) :
First extract entirely PHP code (with open et close php tag),
Second use token_get_all()  on the pure PHP code.

3 : Why there not function to extract PHP code (to extract HTML, we have Tidy..)?

Waiting, I used a function :

The code at end this post :
http://www.developpez.net/forums/d786381/php/langage/
fonctions/analyser-fichier-php-token_get_all/

This function not support :
- Old notation :  "" and "<% %>"
- heredoc syntax
- nowdoc syntax (since PHP 5.3.0)

Dennis Robinson from basnetworks dot net

13 years ago

I wanted to use the tokenizer functions to count source lines of code, including counting comments.  Attempting to do this with regular expressions does not work well because of situations where /* appears in a string, or other situations.  The token_get_all() function makes this task easy by detecting all the comments properly.  However, it does not tokenize newline characters.  I wrote the below set of functions to also tokenize newline characters as T_NEW_LINE.

define

('T_NEW_LINE', -1);

function

token_get_all_nl($source)
{
   
$new_tokens = array();// Get the tokens
   
$tokens = token_get_all($source);// Split newlines into their own tokens
   
foreach ($tokens as $token)
    {
       
$token_name = is_array($token) ? $token[0] : null;
       
$token_data = is_array($token) ? $token[1] : $token;// Do not split encapsed strings or multiline comments
       
if ($token_name == T_CONSTANT_ENCAPSED_STRING || substr($token_data, 0, 2) == '/*')
        {
           
$new_tokens[] = array($token_name, $token_data);
            continue;
        }
// Split the data up by newlines
       
$split_data = preg_split('#(\r\n|\n)#', $token_data, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

        foreach (

$split_data as $data)
        {
            if (
$data == "\r\n" || $data == "\n")
            {
               
// This is a new line token
               
$new_tokens[] = array(T_NEW_LINE, $data);
            }
            else
            {
               
// Add the token under the original token name
               
$new_tokens[] = is_array($token) ? array($token_name, $data) : $data;
            }
        }
    }

    return

$new_tokens;
}

function

token_name_nl($token)
{
    if (
$token === T_NEW_LINE)
    {
        return
'T_NEW_LINE';
    }

    return

token_name($token);
}
?>

Example usage:

$tokens

= token_get_all_nl(file_get_contents('somecode.php'));

foreach (

$tokens as $token)
{
    if (
is_array($token))
    {
        echo (
token_name_nl($token[0]) . ': "' . $token[1] . '"
'
);
    }
    else
    {
        echo (
'"' . $token . '"
'
);
    }
}
?>

I'm sure you can figure out how to count the lines of code, and lines of comments with these functions.  This was a huge improvement on my previous attempt at counting lines of code with regular expressions.  I hope this helps someone, as many of the user contributed examples on this website have helped me in the past.

Ivan Ustanin

4 years ago

As a caution: when using TOKEN_PARSE with an invalid php-file, one can get an error like this:
Parse error: syntax error, unexpected '__construct' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in  on line 15
Notice the missing filename as this function accepts a string, not a filename and thus has no idea of the latter.
However an exception would be more appreciated.

bart

5 years ago

Not all tokens are returned as an array. The rule appears to be that if a token is not variable, but instead it is one particular constant string, it is returned as a string instead. You don't get a line number. This is the case for braces( "{", "}"), parentheses ("(", ")"), brackets ("[", "]"), comma (","), semi-colon (";"), and a whole slew of operator signs ("!", "=", "+", "*", "/", ".", "+=", ...).

Theriault

6 years ago

The T_OPEN_TAG token will include the first trailing newline (\r, \n, or \r\n), tab (\t), or space. Any additional space after this token will be in a T_WHITESPACE token.

The T_CLOSE_TAG token will include the first trailing newline (\r, \n, or \r\n; as described here http://php.net/manual/en/language.basic-syntax.instruction-separation.php). Any additional space after this token will be in a T_INLINE_HTML token.

kevin at metalaxe dot com

14 years ago

Rogier, thanks for that fix. This bug still exists in php 5.2.5. I did notice though that it is possible for a notice to pop up from your code. Changing this line:

            $temp[] = $tokens[0][2];

To read this:

            $temp[] = isset($tokens[0][2])?$tokens[0][2]:'unknown';

fixes this notice.

rogier

14 years ago

Complementary note to code below:
Note that only the FIRST 2 (or 3, if needed) array elements will be updated.

Since I only encountered incorrect results on the FIRST occurence of T_OPEN_TAG, I wrote this quick fix.
Any other following T_OPEN_TAG are, on my testing system (Apache 2.0.52, PHP 5.0.3), parsed correctly.

So, This function assumes only a possibly incorrect first T_OPEN_TAG.
Also, this function assumes the very first element (and ONLY the first element) of the token array to be the possibly incorrect token.
This effectively translates to the first character of the tokenized source to be the start of a php script opening tag '<', followed by either 'php' OR '%' (ASP_style)

How do I generate a token?

Creating a token.
Verify your email address, if it hasn't been verified yet..
In the upper-right corner of any page, click your profile photo, then click Settings..
In the left sidebar, click Developer settings..
In the left sidebar, click Personal access tokens..
Click Generate new token..
Give your token a descriptive name..

How can I get bearer token in PHP?

To send a GET request with a Bearer Token authorization header using PHP, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.

How do I use Getaccesstoken?

Basic steps.
Obtain OAuth 2.0 credentials from the Google API Console. ... .
Obtain an access token from the Google Authorization Server. ... .
Examine scopes of access granted by the user. ... .
Send the access token to an API. ... .
Refresh the access token, if necessary..

How do I find my access token?

What to Check When Validating an Access Token.
Retrieve and parse your Okta JSON Web Keys (JWK), which should be checked periodically and cached by your application..
Decode the access token, which is in JSON Web Token format..
Verify the signature used to sign the access token..