CodeIgniter can not use PHP's namespace - php

I'm trying use firebase/php-jwt in CodeIgniter 3, but I get this error:
Parse error: syntax error, unexpected 'use' (T_USE) in /opt/lampp/htdocs/kpittu_api/application/controllers/User.php on line 23
this is my code:
require('vendor/autoload.php');
use \Firebase\JWT\JWT;
$key = "example_key";
$payload = array(
"iat" => time(),
"exp" => time() + 86400,
"data" => [
"login" => "sii1995",
"fname" => "Salim",
"sname" => "Ibrogimovich",
"lname" => "Ibrogimov"
]
);
$jwt = JWT::encode($payload, $key);
$decoded = JWT::decode($jwt, $key, array('HS256'));
$decoded_array = (array) $decoded;
/*
JWT::$leeway = 60; // $leeway in seconds
$decoded = JWT::decode($jwt, $key, array('HS256'));
*/
echo '<pre>';
print_r($jwt);
echo '<hr>';
print_r($decoded_array);
echo '</pre>';
When I using this code outside CodeIgniter it's work well.
How can Use namespace / use keyword in CodeIgniter?

Dear friends I solve it: I just need to put these two lines above class declarations:
require('vendor/autoload.php');
use \Firebase\JWT\JWT;
class User extends CI_Controller {

Related

keyOrKeyArray must be an instance of Firebase\\JWT\\Key key or an array of Firebase\\JWT\\Key keys", in php ci4

{
"title": "UnexpectedValueException",
"type": "UnexpectedValueException",
"code": 500,
"message": "$keyOrKeyArray must be an instance of Firebase\JWT\Key key or an array of Firebase\JWT\Key keys",
"file": "E:\var\www\html\project\spans\admin\vendor\firebase\php-jwt\src\JWT.php",
"line": 416,
You can use the below example code -
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
class User extends BaseController
{
public function exampleMethod()
{
$issuedAt = time();
$expirationTime = $issuedAt + 60; // jwt valid for 60 seconds from the issued time
$payload = array( // Any random data
'userid' => 'Test_UID',
'name' => 'Sankhnad Mishra',
'iat' => $issuedAt,
'exp' => $expirationTime
);
$key = 'A_JWT_SECRET'; // Any string
$alg = 'HS256'; // This is alg
$token = JWT::encode($payload, $key, $alg); // Encode payload as a JWT Token
$decodedToken = JWT::decode($token, new Key($key, 'HS256')); // Decode token to a payload
$response = [
'token' => $token,
'decodedToken' => $decodedToken
];
print_r($response);
}
}
If you run above then you will get the below response -
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyaWQiOiJUZXN0X1VJRCIsIm5hbWUiOiJTYW5raG5hZCBNaXNocmEiLCJpYXQiOjE2NDU4MTU0OTUsImV4cCI6MTY0NTgxNTU1NX0.0CwT9quW8-teyob3ObRU5KQBfQYWamCSTVCrAk9UX-o",
"decodedToken": {
"userid": "Test_UID",
"name": "Sankhnad Mishra",
"iat": 1645815495,
"exp": 1645815555
}
}
So, just pick those pieces of code from above based on your requirement.
you make use of namespace
Use Firebase\JWT\Key;
// For encode:
$jwt = JWT: encoding ($payload, $key, 'HS256');
// For decoding:
$decodedToken = JWT:: decode ($jwt, new key ($key,'HS256'));

JWT encode error Expected 3 arguments. Found 2

I try to create a restful api with JWT in CI4, when I create token with code below :
$key = getenv('TOKEN_SECRET');
$payload = array(
"iat" => 1356999524,
"nbf" => 1357000000,
"uid" => $user['id'],
"email" => $user['email']
);
$token = JWT::encode($payload, $key);
Why do I get the error:
Expected 3 arguments. Found 2
The third paramter should be the algorithm you are trying to use for encoding.
For Example, HS256 is one of the algorithms.
So in your example it will be :
$token = JWT::encode($payload, $key, 'HS256');
You can refer to the following link for reference:
https://packagist.org/packages/firebase/php-jwt

Firebase JWT: Signature verification failed

I'm trying to use a JWT authentication with Firebase, but I got always this error: "Fatal error: Uncaught Firebase\JWT\SignatureInvalidException: Signature verification failed".
The code is this:
$key = "test";
$tokenId = base64_encode(mcrypt_create_iv(32));
$issuedAt = time();
$notBefore = $issuedAt + 10;
$expire = $notBefore + 60;
$serverName = $_SERVER["SERVER_NAME"];
$data = [
'iat' => $issuedAt,
'jti' => $tokenId,
'iss' => $serverName,
'nbf' => $notBefore,
'exp' => $expire,
"userId" => 1
];
$secretKey = base64_decode($key);
$jwt = \Firebase\JWT\JWT::encode($data, $secretKey, 'HS256');
// and when I decode the tokens, I got that exception
$decoded = \Firebase\JWT\JWT::decode($jwt, $key, array('HS256'));
What I wrong?
You don't need $secretKey or base64_decode the key for that matter, just do:
$jwt = \Firebase\JWT\JWT::encode($data, $key, 'HS256');
$decoded = \Firebase\JWT\JWT::decode($jwt, $key, array('HS256'));

Parse error: syntax error, unexpected '['

i am trying to install a sdk on a public cloud service.The code is shown as follow:
<?php
echo ( '<meta charset="utf-8">');
date_default_timezone_set('PRC');
require_once __DIR__ . '/lib/KdtApiClient.php';
$appId = 'xxx';
$appSecret = 'xxx';
$client = new KdtApiClient($appId, $appSecret);
$method = 'kdt.users.weixin.followers.get';
$params = [
// 'tid' => 'E20150126200526848473',
//'num_iid' => 1005950256201501260011172648,
//'title' => 'api 测试商品 编辑 __ 22',
//'desc' => 'description here',
//'post_fee' => 0.2,
'page_size'=>5000,
];
$files = [
[
'url' => __DIR__ . '/file1.png',
'field' => 'images[]',
],
[
'url' => __DIR__ . '/file2.jpg',
'field' => 'images[]',
],
];
echo '<pre>';
var_dump(
$client->post($method, $params, $files)
);
echo '</pre>';
?>
I got this error:
Parse error: syntax error, unexpected '[' in php-sdk/index.php on line 12
The code works well on local xampp.Is there anyone can tell me what's the problem?
The issue you are encountering is most likely due to different PHP versions.
On line 12 you are using the short array syntax to create an array on the files variable. $files = [...
This syntax was introduced in PHP 5.4 (See second point). However I think the cloud service is not using 5.4, which is why you don't have the short array syntax. The easy solution would be to use $files = array( instead.

Building query string programmatically in Guzzle?

In my PHP Guzzle client code, I have something like
$c = new Client('http://test.com/api/1.0/function');
$request = $c->get('?f=4&l=2&p=3&u=5');
but instead I want to have something like:
$request->set('f', 4);
$request->set('l', 2);
$request->set('p', 3);
$request->set('u', 5);
Is it possible in Guzzle? From the documentation and random googling it would seem it is, but I can't find exactly how.
You can:
$c = new Client('http://test.com/api/1.0/function');
$request = $c->get();
$q = $request->getQuery();
$q->set('f', 4);
$q->set('l', 2);
$q->set('p', 3);
$q->set('u', 5);
Guzzle 6 - you could use query option param
// Send a GET request to /get?foo=bar
$client->request('GET', '/get', ['query' => ['foo' => 'bar']]);
http://docs.guzzlephp.org/en/stable/request-options.html#query
Have a look at Guzzle documentaton https://docs.guzzlephp.org/en/stable/request-options.html
As you can see it has RequestOptions. RequestOptions are constants. They are defined at GuzzleHttp\RequestOptions. You can look at class source code and see all of them right there. Thus, to keep good and professional programming style you can write following source code below, for example
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
class DataClass extends BaseClass
{
const DEFAULT_ACCEPT_HEADER = 'application/json';
const DEFAULT_CACHE_HEADER = 'no-cache';
const HOST = 'http://test.com/';
const ENDPOINT = 'api/1.0/function';
const TIMEOUT = 2.0;
private function getData()
{
$client = new Client([
'base_uri' => self::HTTP_HOST,
'timeout' => self::TIMEOUT
]
);
$response = $client->request('GET', self::ENDPOINT,
[
RequestOptions::HEADERS => [
'Accept' => self::DEFAULT_ACCEPT_HEADER,
'Cache-Control' => self::DEFAULT_CACHE_HEADER,
],
RequestOptions::QUERY => [
'f' => 4,
'l' => 2,
'p' => 3,
'u' => 5
]
]
);
return json_decode($response->getBody(), JSON_OBJECT_AS_ARRAY);
}

Categories