/** * Created by kongltn on 12/25/2015. */ $(document).ready(function () { $("#backButtonInheaderBar").click(function () { if (sessionStorage.backURL !== undefined) { sessionStorage.backIsClick = 1; var curArray = JSON.parse(sessionStorage.backURL); if (curArray.length > 1) curArray.pop(); sessionStorage.backURL = JSON.stringify(curArray); window.location.replace(curArray[curArray.length - 1]); } }); if (!sessionStorage.backURL || sessionStorage.backURL === undefined) { sessionStorage.backURL = JSON.stringify([window.location.origin]); } var curUrlHref = window.location.href; if (sessionStorage.backIsClick && sessionStorage.backIsClick === "1") { sessionStorage.backIsClick = 0; } else { var urlArray = JSON.parse(sessionStorage.backURL); if (curUrlHref != urlArray[urlArray.length - 1]) { urlArray.push(curUrlHref); } sessionStorage.backURL = JSON.stringify(urlArray); } //console.log(sessionStorage.backURL); //console.log(sessionStorage.backIsClick); });
Search
Dec 18, 2015
Back link URL by Javascript
Dec 16, 2015
Action download file in PHP
/** * Action Download file * @return undefined */ public function actionDownload() { $file = Yii::app()->request->getParam('file'); $modelArchives = Archives::model()->find('path=:path', array(':path' => $file)); header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-type:application/octet-stream"); header('Content-Disposition: attachment; filename="' . $modelArchives->fileName . '"'); $contentArchive = Yii::getPathOfAlias('webroot') . Yii::app()->params["archiveFolderPath"] . '/' . $file; echo file_get_contents($contentArchive); exit; }
Dec 9, 2015
CSS trick: Sort String and add 3 dot at last point of string
.sortTitle { width: calc(100% - 20px); display: inline; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; }
Dec 7, 2015
Create thumbnail image in PHP
Image.php
ImageTool.php
Using function createThumbnail
<?php /** * Class Image * @author UTC.HuyTD */ class Image { private $file; private $image; private $info; /** * @param $file */ public function __construct($file) { if (file_exists($file)) { $this->file = $file; $info = getimagesize($file); $this->info = array( 'width' => $info[0], 'height' => $info[1], 'bits' => $info['bits'], 'mime' => $info['mime'], ); $this->image = $this->create($file); } else { exit('Error: Could not load image ' . $file . '!'); } } /** * @param $image * @return bool|resource */ private function create($image) { $mime = $this->info['mime']; if ($mime == 'image/gif') { return imagecreatefromgif($image); } elseif ($mime == 'image/png') { return imagecreatefrompng($image); } elseif ($mime == 'image/jpeg') { return imagecreatefromjpeg($image); } return false; } /** * @param $file * @param int $quality */ public function save($file, $quality = 90) { $info = pathinfo($file); $extension = strtolower($info['extension']); if (is_resource($this->image)) { if ($extension == 'jpeg' || $extension == 'jpg') { imagejpeg($this->image, $file, $quality); } elseif ($extension == 'png') { imagepng($this->image, $file); } elseif ($extension == 'gif') { imagegif($this->image, $file); } imagedestroy($this->image); } } /** * Resize function * @param int $width * @param int $height * @param string $default char [default, w, h] * default = scale with white space, * w = fill according to width, * h = fill according to height */ public function resize($width = 0, $height = 0, $default = '') { if (!$this->info['width'] || !$this->info['height']) { return; } $positionX = 0; $positionY = 0; $scale = 1; $scale_w = $width / $this->info['width']; $scale_h = $height / $this->info['height']; if ($default == 'w') { $scale = $scale_w; } elseif ($default == 'h') { $scale = $scale_h; } else { $scale = min($scale_w, $scale_h); } if ($scale == 1 && $scale_h == $scale_w && $this->info['mime'] != 'image/png') { return; } $new_width = (int)($this->info['width'] * $scale); $new_height = (int)($this->info['height'] * $scale); $positionX = (int)(($width - $new_width) / 2); $positionY = (int)(($height - $new_height) / 2); $image_old = $this->image; $width = $width === 0 ? $this->info['width'] : $width; $height = $height === 0 ? $this->info['height'] : $height; $this->image = imagecreatetruecolor($width, $height); if (isset($this->info['mime']) && $this->info['mime'] == 'image/png') { imagealphablending($this->image, false); imagesavealpha($this->image, true); $background = imagecolorallocatealpha($this->image, 255, 255, 255, 127); imagecolortransparent($this->image, $background); } else { $background = imagecolorallocate($this->image, 255, 255, 255); } imagefilledrectangle($this->image, 0, 0, $width, $height, $background); imagecopyresampled($this->image, $image_old, $positionX, $positionY, 0, 0, $new_width, $new_height, $this->info['width'], $this->info['height']); imagedestroy($image_old); $this->info['width'] = $width; $this->info['height'] = $height; } /** * @param $file * @param string $position */ public function watermark($file, $position = 'bottomright') { $watermark = $this->create($file); $watermark_width = imagesx($watermark); $watermark_height = imagesy($watermark); $watermark_pos_x = null; $watermark_pos_y = null; switch ($position) { case 'topleft': $watermark_pos_x = 0; $watermark_pos_y = 0; break; case 'topright': $watermark_pos_x = $this->info['width'] - $watermark_width; $watermark_pos_y = 0; break; case 'bottomleft': $watermark_pos_x = 0; $watermark_pos_y = $this->info['height'] - $watermark_height; break; case 'bottomright': $watermark_pos_x = $this->info['width'] - $watermark_width; $watermark_pos_y = $this->info['height'] - $watermark_height; break; } imagecopy($this->image, $watermark, $watermark_pos_x, $watermark_pos_y, 0, 0, 120, 40); imagedestroy($watermark); } /** * Crop function * @param $top_x * @param $top_y * @param $bottom_x * @param $bottom_y */ public function crop($top_x, $top_y, $bottom_x, $bottom_y) { $image_old = $this->image; $this->image = imagecreatetruecolor($bottom_x - $top_x, $bottom_y - $top_y); imagecopy($this->image, $image_old, 0, 0, $top_x, $top_y, $this->info['width'], $this->info['height']); imagedestroy($image_old); $this->info['width'] = $bottom_x - $top_x; $this->info['height'] = $bottom_y - $top_y; } /** * Rotate function * @param $degree * @param string $color */ public function rotate($degree, $color = 'FFFFFF') { $rgb = $this->html2rgb($color); $this->image = imagerotate($this->image, $degree, imagecolorallocate($this->image, $rgb[0], $rgb[1], $rgb[2])); $this->info['width'] = imagesx($this->image); $this->info['height'] = imagesy($this->image); } /** * @param $filter */ private function filter($filter) { imagefilter($this->image, $filter); } /** * Text function * @param $text * @param int $x * @param int $y * @param int $size * @param string $color */ private function text($text, $x = 0, $y = 0, $size = 5, $color = '000000') { $rgb = $this->html2rgb($color); imagestring($this->image, $size, $x, $y, $text, imagecolorallocate($this->image, $rgb[0], $rgb[1], $rgb[2])); } /** * Merge function * @param $file * @param int $x * @param int $y * @param int $opacity */ private function merge($file, $x = 0, $y = 0, $opacity = 100) { $merge = $this->create($file); $merge_width = imagesx($this->$image); $merge_height = imagesy($this->$image); imagecopymerge($this->image, $merge, $x, $y, 0, 0, $merge_width, $merge_height, $opacity); } /** * @param $color * @return array|bool */ private function html2rgb($color) { if ($color[0] == '#') { $color = substr($color, 1); } if (strlen($color) == 6) { list($r, $g, $b) = array($color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5]); } elseif (strlen($color) == 3) { list($r, $g, $b) = array($color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2]); } else { return false; } $r = hexdec($r); $g = hexdec($g); $b = hexdec($b); return array($r, $g, $b); } }
ImageTool.php
<?php /** * Class ImageTool * @author UTC.HuyTD */ class ImageTool { /** * Resize thumbnail Image * @param $folderPathOfThumbnail * @param $filename * @param int $width * @param int $height * @return string */ public static function resizeThumbnailImage($folderPathOfThumbnail, $filename, $width = 0, $height = 0) { try { if (file_exists($filename)) { $fileInfo = pathinfo($filename); $fileExtension = $fileInfo['extension']; $thumbnailFileName = $fileInfo['filename'] . "_thumbnail." . $fileExtension; // Create image with width & height $image = new Image($filename); $image->resize($width, $height); $image->save($folderPathOfThumbnail . "/" . $thumbnailFileName); return $folderPathOfThumbnail . "/" . $thumbnailFileName; } } catch (Exception $e) { echo $e->getMessage(); } return ""; } }
Using function createThumbnail
/** * Create thumbnail image * @param $folderPathOfThumbnail * @param string $directImage * @param int $defaultWidth * @return string */ public static function createThumbnailImage($folderPathOfThumbnail, $directImage = 'images/no_image.jpg', $defaultWidth = 150) { $thumbnailPathCreated = ""; if ($defaultWidth == "") { return $directImage; } if (file_exists($directImage)) { $size = getimagesize($directImage); // Get image width & height $imgWidth = $size[0]; $imgHeight = $size[1]; if ($imgHeight > $imgWidth) { if ($imgHeight != $defaultWidth) { $imgHeightNew = $defaultWidth; $scaleHeight = round($imgHeightNew / $imgHeight, 2); $imgWidthNew = $imgWidth * $scaleHeight; // Create thumbnail image $thumbnailPathCreated = ImageTool::resizeThumbnailImage($folderPathOfThumbnail, $directImage, $imgWidthNew, $imgHeightNew); } } else { if ($imgWidth != $defaultWidth) { $scale = round($defaultWidth / $imgWidth, 2); // Create thumbnail image $thumbnailPathCreated = ImageTool::resizeThumbnailImage($folderPathOfThumbnail, $directImage, $imgWidth*$scale, $imgHeight*$scale); } } } if ($thumbnailPathCreated != "") { if (substr($thumbnailPathCreated, 0, 1) == "/") $thumbnailPathCreated = substr($thumbnailPathCreated, 1); } return $thumbnailPathCreated; }
$thumbFolder = Yii::getPathOfAlias('webroot').'/upload/thumbnails'; $img = Yii::getPathOfAlias('webroot') . '/upload/avatars/Tulips.jpg' ; $this->createThumbnailImage($thumbFolder, $img , 50);
Dec 4, 2015
Convert UTC Time to Client Time by moment JS
/** * Javascript for convert time (using moment JS) * @author UTC.KongLtn * Last Update: 4/12/2015 */ var clientTimeId = { getArchiveClientTime: ".getArchiveClientTime" }; /** * Client Time Object * @type {{init: Function, convertInArchive: Function, toArchiveTime: Function, getDiffTime: Function, getDateYYMMDD: Function}} */ var clientTime = { init: function(){ this.convertInArchive(); }, /** * Convert to client time in archive page */ convertInArchive : function(){ var archiveArray = $(clientTimeId.getArchiveClientTime); $.each(archiveArray, function(index, val) { var createDateToUTCSeconds = moment.utc(val.textContent).unix(); $(this).text(clientTime.getArchiveTime(createDateToUTCSeconds)); }) }, /** * Get client Time in archive page * @param seconds * @returns string */ getArchiveTime : function(seconds){ var createDate = moment.utc(seconds * 1000); var nowDate = moment.utc(); var diff = nowDate.diff(createDate, "minutes"); var firstText = ""; if (diff < 1440) { firstText = "Today "; } else if (diff < 2880) { firstText = "Yesterday "; } else if (diff >= 2880) { return (createDate.local().format("DD.MM.YYYY HH:mm")); } return firstText+ " "+ createDate.local().format("HH:mm"); }, /** * Get the different past time and current time * @param seconds * @returns string */ getDiffTime: function(seconds) { var createDate = moment.utc(seconds * 1000); var nowDate = moment.utc(); var diff = nowDate.diff(createDate, "seconds"); diff = (diff == 0 || diff == 1) ? 2 : diff; if (2 <= diff && diff <= 45) { return diff + " seconds ago"; } else if ( 86400 < diff ) { return createDate.local().format("DD.MM.YYYY HH:mm"); } else { return createDate.fromNow(); } }, /** * Get date by format YY.MM.DD * @param seconds * @returns string */ getDateYYMMDD : function(seconds) { return moment.utc(seconds*1000).local().format("YY.MM.DD"); } }; $(document).ready(function(){ 'use strict'; if (isGuestId > 0) { //console.log("start"); clientTime.init(); } });
Dec 3, 2015
Setup Yii with WAMPP
SETUP YII with WAMPP
1/ copy file from http://www.yiiframework.com/download to c:\wamp\www folder
rename yii-1.1.13.... folder to yii
(c:\wamp\www\yii and the framework itself will be into c:\wamp\www\yii\framework)
2/ on c:\wamp\www creates a file with the extension 'bat' (for example myrun.bat),
then open it and put below code:
set PATH=%PATH%;C:\wamp\bin\php\php5.4.3
cmd
3/ Run myrun.bat file and type (or you can cd to ..wamp/www/ folder and type)
php yii/framework/yiic.php webapp myfirst
4/ Config databases
Create database MySQL and fix file
protected/config/database.php
5/ CRUD Create-Read-Update-Delete
Edit file protected/config/main.php
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'1',
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters'=>array('127.0.0.1','::1'),
)
Go to http://localhost/myfirst/index.php?r=gii
1/ copy file from http://www.yiiframework.com/download to c:\wamp\www folder
rename yii-1.1.13.... folder to yii
(c:\wamp\www\yii and the framework itself will be into c:\wamp\www\yii\framework)
2/ on c:\wamp\www creates a file with the extension 'bat' (for example myrun.bat),
then open it and put below code:
set PATH=%PATH%;C:\wamp\bin\php\php5.4.3
cmd
3/ Run myrun.bat file and type (or you can cd to ..wamp/www/ folder and type)
php yii/framework/yiic.php webapp myfirst
4/ Config databases
Create database MySQL and fix file
protected/config/database.php
5/ CRUD Create-Read-Update-Delete
Edit file protected/config/main.php
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'1',
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters'=>array('127.0.0.1','::1'),
)
Go to http://localhost/myfirst/index.php?r=gii
Nov 25, 2015
Install JWT (JSON Web Token) - PHP
JWT.php
Demo Example:
<?php //namespace Firebase\JWT; //use \DomainException; //use \InvalidArgumentException; //use \UnexpectedValueException; //use \DateTime; /** * JSON Web Token implementation, based on this spec: * http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06 * * PHP version 5 * * @category Authentication * @package Authentication_JWT * @author Neuman Vong <neuman@twilio.com> * @author Anant Narayanan <anant@php.net> * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD * @link https://github.com/firebase/php-jwt */ class JWT { /** * When checking nbf, iat or expiration times, * we want to provide some extra leeway time to * account for clock skew. */ public static $leeway = 0; public static $supported_algs = array( 'HS256' => array('hash_hmac', 'SHA256'), 'HS512' => array('hash_hmac', 'SHA512'), 'HS384' => array('hash_hmac', 'SHA384'), 'RS256' => array('openssl', 'SHA256'), ); /** * Decodes a JWT string into a PHP object. * * @param string $jwt The JWT * @param string|array|null $key The key, or map of keys. * If the algorithm used is asymmetric, this is the public key * @param array $allowed_algs List of supported verification algorithms * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256' * * @return object The JWT's payload as a PHP object * * @throws DomainException Algorithm was not provided * @throws UnexpectedValueException Provided JWT was invalid * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf' * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat' * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim * * @uses jsonDecode * @uses urlsafeB64Decode */ public static function decode($jwt, $key, $allowed_algs = array()) { if (empty($key)) { throw new InvalidArgumentException('Key may not be empty'); } $tks = explode('.', $jwt); if (count($tks) != 3) { throw new UnexpectedValueException('Wrong number of segments'); } list($headb64, $bodyb64, $cryptob64) = $tks; if (null === ($header = JWT::jsonDecode(JWT::urlsafeB64Decode($headb64)))) { throw new UnexpectedValueException('Invalid header encoding'); } if (null === $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64))) { throw new UnexpectedValueException('Invalid claims encoding'); } $sig = JWT::urlsafeB64Decode($cryptob64); if (empty($header->alg)) { throw new DomainException('Empty algorithm'); } if (empty(self::$supported_algs[$header->alg])) { throw new DomainException('Algorithm not supported'); } if (!is_array($allowed_algs) || !in_array($header->alg, $allowed_algs)) { throw new DomainException('Algorithm not allowed'); } if (is_array($key) || $key instanceof \ArrayAccess) { if (isset($header->kid)) { $key = $key[$header->kid]; } else { throw new DomainException('"kid" empty, unable to lookup correct key'); } } // Check the signature if (!JWT::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) { throw new SignatureInvalidException('Signature verification failed'); } // Check if the nbf if it is defined. This is the time that the // token can actually be used. If it's not yet that time, abort. if (isset($payload->nbf) && $payload->nbf > (time() + self::$leeway)) { throw new BeforeValidException( 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf) ); } // Check that this token has been created before 'now'. This prevents // using tokens that have been created for later use (and haven't // correctly used the nbf claim). if (isset($payload->iat) && $payload->iat > (time() + self::$leeway)) { throw new BeforeValidException( 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat) ); } // Check if this token has expired. if (isset($payload->exp) && (time() - self::$leeway) >= $payload->exp) { throw new ExpiredException('Expired token'); } return $payload; } /** * Converts and signs a PHP object or array into a JWT string. * * @param object|array $payload PHP object or array * @param string $key The secret key. * If the algorithm used is asymmetric, this is the private key * @param string $alg The signing algorithm. * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256' * @param array $head An array with header elements to attach * * @return string A signed JWT * * @uses jsonEncode * @uses urlsafeB64Encode */ public static function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null) { $header = array('typ' => 'JWT', 'alg' => $alg); if ($keyId !== null) { $header['kid'] = $keyId; } if ( isset($head) && is_array($head) ) { $header = array_merge($head, $header); } $segments = array(); $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($header)); $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($payload)); $signing_input = implode('.', $segments); $signature = JWT::sign($signing_input, $key, $alg); $segments[] = JWT::urlsafeB64Encode($signature); return implode('.', $segments); } /** * Sign a string with a given key and algorithm. * * @param string $msg The message to sign * @param string|resource $key The secret key * @param string $alg The signing algorithm. * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256' * * @return string An encrypted message * * @throws DomainException Unsupported algorithm was specified */ public static function sign($msg, $key, $alg = 'HS256') { if (empty(self::$supported_algs[$alg])) { throw new DomainException('Algorithm not supported'); } list($function, $algorithm) = self::$supported_algs[$alg]; switch($function) { case 'hash_hmac': return hash_hmac($algorithm, $msg, $key, true); case 'openssl': $signature = ''; $success = openssl_sign($msg, $signature, $key, $algorithm); if (!$success) { throw new DomainException("OpenSSL unable to sign data"); } else { return $signature; } } } /** * Verify a signature with the message, key and method. Not all methods * are symmetric, so we must have a separate verify and sign method. * * @param string $msg The original message (header and body) * @param string $signature The original signature * @param string|resource $key For HS*, a string key works. for RS*, must be a resource of an openssl public key * @param string $alg The algorithm * * @return bool * * @throws DomainException Invalid Algorithm or OpenSSL failure */ private static function verify($msg, $signature, $key, $alg) { if (empty(self::$supported_algs[$alg])) { throw new DomainException('Algorithm not supported'); } list($function, $algorithm) = self::$supported_algs[$alg]; switch($function) { case 'openssl': $success = openssl_verify($msg, $signature, $key, $algorithm); if (!$success) { throw new DomainException("OpenSSL unable to verify data: " . openssl_error_string()); } else { return $signature; } case 'hash_hmac': default: $hash = hash_hmac($algorithm, $msg, $key, true); if (function_exists('hash_equals')) { return hash_equals($signature, $hash); } $len = min(self::safeStrlen($signature), self::safeStrlen($hash)); $status = 0; for ($i = 0; $i < $len; $i++) { $status |= (ord($signature[$i]) ^ ord($hash[$i])); } $status |= (self::safeStrlen($signature) ^ self::safeStrlen($hash)); return ($status === 0); } } /** * Decode a JSON string into a PHP object. * * @param string $input JSON string * * @return object Object representation of JSON string * * @throws DomainException Provided string was invalid JSON */ public static function jsonDecode($input) { if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) { /** In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you * to specify that large ints (like Steam Transaction IDs) should be treated as * strings, rather than the PHP default behaviour of converting them to floats. */ $obj = json_decode($input, false, 512, JSON_BIGINT_AS_STRING); } else { /** Not all servers will support that, however, so for older versions we must * manually detect large ints in the JSON string and quote them (thus converting *them to strings) before decoding, hence the preg_replace() call. */ $max_int_length = strlen((string) PHP_INT_MAX) - 1; $json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input); $obj = json_decode($json_without_bigints); } if (function_exists('json_last_error') && $errno = json_last_error()) { JWT::handleJsonError($errno); } elseif ($obj === null && $input !== 'null') { throw new DomainException('Null result with non-null input'); } return $obj; } /** * Encode a PHP object into a JSON string. * * @param object|array $input A PHP object or array * * @return string JSON representation of the PHP object or array * * @throws DomainException Provided object could not be encoded to valid JSON */ public static function jsonEncode($input) { $json = json_encode($input); if (function_exists('json_last_error') && $errno = json_last_error()) { JWT::handleJsonError($errno); } elseif ($json === 'null' && $input !== null) { throw new DomainException('Null result with non-null input'); } return $json; } /** * Decode a string with URL-safe Base64. * * @param string $input A Base64 encoded string * * @return string A decoded string */ public static function urlsafeB64Decode($input) { $remainder = strlen($input) % 4; if ($remainder) { $padlen = 4 - $remainder; $input .= str_repeat('=', $padlen); } return base64_decode(strtr($input, '-_', '+/')); } /** * Encode a string with URL-safe Base64. * * @param string $input The string you want encoded * * @return string The base64 encode of what you passed in */ public static function urlsafeB64Encode($input) { return str_replace('=', '', strtr(base64_encode($input), '+/', '-_')); } /** * Helper method to create a JSON error. * * @param int $errno An error number from json_last_error() * * @return void */ private static function handleJsonError($errno) { $messages = array( JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON' ); throw new DomainException( isset($messages[$errno]) ? $messages[$errno] : 'Unknown JSON error: ' . $errno ); } /** * Get the number of bytes in cryptographic strings. * * @param string * * @return int */ private static function safeStrlen($str) { if (function_exists('mb_strlen')) { return mb_strlen($str, '8bit'); } return strlen($str); } }
Demo Example:
<?php use \Firebase\JWT\JWT; $key = "example_key"; $token = array( "iss" => "http://example.org", "aud" => "http://example.com", "iat" => 1356999524, "nbf" => 1357000000 ); /** * IMPORTANT: * You must specify supported algorithms for your application. See * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40 * for a list of spec-compliant algorithms. */ $jwt = JWT::encode($token, $key); $decoded = JWT::decode($jwt, $key, array('HS256')); print_r($decoded); /* NOTE: This will now be an object instead of an associative array. To get an associative array, you will need to cast it as such: */ $decoded_array = (array) $decoded; /** * You can add a leeway to account for when there is a clock skew times between * the signing and verifying servers. It is recommended that this leeway should * not be bigger than a few minutes. * * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef */ JWT::$leeway = 60; // $leeway in seconds $decoded = JWT::decode($jwt, $key, array('HS256')); ?>
Subscribe to:
Posts (Atom)