Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Dec 19, 2016

How to install Composer, PHPUnit in Ubuntu

Composer and PHPUnit packed with phar, so we need only append these lines into ~/.bashrc:

# change location to your phpunit.phar
alias composer=~/bin/composer/composer.phar
alias phpunit=~/bin/phpunit/phpunit.phar
We also install composer this way:

sudo curl -sS http://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
Check them installed or not?
phpunit --version
composer --version

Dec 6, 2016

Data structures in Python and PHP

Remember that PHP use the array language for all list, hash, set, tuple... types.

1. List

In Python, to create a list, we put a number of expressions in square brackets. In PHP we usually use the array language construct.
For example the Python code snippet:

a = ['Python', 'PHP']
is equivalent to following PHP

$a = array('Python', 'PHP');
Note that PHP 5.3 introduces declaring PHP list with using square bracket syntax:

$a = ['Python', 'PHP'];

2. Hastable

Some times called associative arrays, dictionaries, or maps. A hash is an un-ordered group of key-value pairs. The keys are usually unique strings.

In Python we use brace bracket to declare a hastable type.


a = {}
For example:

a = {1: 'hello', 'lang': 'Python'}
In PHP we declare:

$a = array(1 => 'hello', 'lang' => 'Python'); // or $a = [1 => 'hello', 'lang' => 'Python']

3. Set

We use PHP array key to represent a set item because the key is unique. For example:

$_set = array();
$_set['java'] = 1;
$_set['python'] = 2;
$_set['php'] = 3;

In Python we use curly braces to initialize set. For example:

my_set = {'java', 'python', 'php'} #since 2.7
or

my_set = set(['java', 'python', 'php'])

Nov 14, 2016

CLI programming with PHP

Basically, to write cli program with PHP we just use $argv ($argv is enough, $argc - if necessary). $argv contains an array of all the arguments passed to the script when running from the command line.


for($i = 1; $i < $argc; ++$i) {
    echo $argv[$i]. "\n";
}
In addition, if we 'd expect to get arguments passed like option1=value1

$ php cli_program.php opt1=val1 opt2=val2

we can parse the command line arguments into $_GET by using parse_str() function. <!--php parse_str( implode( '&', array_slice($argv, 1) ), $_GET ); foreach($_GET as $k =--> $v) { echo sprintf("[$k]=$v\n"); } for($i = 1; $i < $argc; ++$i) { echo $argv[$i]. "\n"; } ?> Example:

Oct 27, 2016

Enhance PHP source code by using heredoc

Heredoc helps our code easily mantainable. It is really useful for multi-line strings.
We will write our code like:

instead of using concatenation-dot syntax such as:

$db->query(
 "CREATE TABLE IF NOT EXISTS `users ` ( "
 . "`id`   int NOT NULL AUTO_INCREMENT, "
 . "`email`  varchar(255) COLLATE utf8_unicode_ci NOT NULL, "
 . "`usr`   varchar(255) COLLATE utf8_unicode_ci NOT NULL, "
 . "`pwd`   varchar(255) COLLATE utf8_unicode_ci NOT NULL, "
 . "PRIMARY KEY (`id`) "
 .");"
);
Related topic StackOverflow
Heredoc reference here

Oct 13, 2016

Create PHP/Laravel authentication APIs with Firebase PHP-JWT

On all PHP/Laravel projects (SPA apps) I always use Firebase/PHP-JWT to create our authentication APIs for mobile apps or javascript apps.
Firstly, we include Firebase/PHP-JWT to our projects by adding & downloading dependencies:
composer require firebase/php-jwt
When user login via AJAX call, we need response to client a token (jwt).

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use Config;
use Hash;
use Log;
use App\User;
use \Firebase\JWT\JWT;
use \Firebase\JWT\ExpiredException;

class AuthController extends Controller
{
    protected function jwt(User $user)
    {
        $payload = array(
            'sub'   => $user->id,
            'iat'   => time(),
            'exp'   => time() + 60*60
        );
        return JWT::encode($payload, Config::get('app.jwt-secret-key'));
    }

    public function login(Request $req)
    {
        $validator = Validator::make($req->all(), array(
            'email' => 'required|email|min:4|max:255',
            'password'  => 'required|min:8|max:80'
        ));

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 400);
        }

        $user = User::where('email', '=', $req->input('email'))->first();

        if (!$user) {
            return response()->json(['error' => 'Your email not exists'], 401);
        }

        if (Hash::check($req->input('password'), $user->password)) {
            return response()->json(['jwt' => $this->jwt($user)], 200);
        } else {
            return response()->json(['error' => 'Wrong passwd'], 401);
        }
    }
}
Method jwt(User $user) return a string called token. Basically on authentication we create and store a token locally on client (browser, smart phone device). Then every time we make a call to the server, we check that token and ensure the user is who they say they are.

The routes:

Route::group(array('prefix' => 'api'), function() {
    Route::post('auth/register', 'AuthController@register');
    Route::post('auth/login', 'AuthController@login');
    Route::post('auth/user', 'AuthController@user'); // response returns logged user
});

Corresponding user() method:

    /**
     * return authenticated user
     * return NULL if not authenticated
    **/
    public function user(Request $req, $nullOnFail = false)
    {
        try {
            list($jwtType, $jwt) = explode(' ', $req->header('Authorization'));
        } catch(\ErrorException $e) {
            if ($nullOnFail)
                return null;
            return response()->json(['error' => 'Can not parse Authorization header'], 400);
        }
        if ($jwt) {
            try {
                $credentials = JWT::decode($jwt, Config::get('app.jwt-secret-key'), ['HS256']);
            } catch(ExpiredException $e) {
                if ($nullOnFail)
                    return $nullOnFail;
                return response()->json(['error' => 'jwt_expired'], 400);
            } catch(\Exception $e) {
                if ($nullOnFail)
                    return $nullOnFail;
                return response()->json(['error' => 'An error while decoding jwt'], 400);
            }

            $user = User::where('id', '=', get_object_vars($credentials)['sub'])->first();
            if ($nullOnFail)
                return $user;
            return response()->json(['user' => $user], 200);
        }
        return response()->json(['error' => 'No jwt attached'], 401);
    }

How to write an internet forum based on Laravel and AngularJs? (part 1)

Oct 11, 2016

How to write RESTful APIs in "Vanilla" PHP?

PHP supports them native. In a certain PHP, I have to code in "pure PHP", no RESTful APIs library/engine provided. So I decided to write a file called api.php to handle all API request. I used this pattern
if ($grabber->method() === 'GET') {
    // define your APIs here
    echo json_encode(array('Appl RESTful APIs'), JSON_UNESCAPED_UNICODE);
    exit(0);

} else if ($grabber->method() === 'POST') {
    // define your APIs here

} else if ($grabber->method() === 'PUT') {
    // define your APIs here

} else if ($grabber->method() === 'DELETE') {
    // define your APIs here

}
You can see the api.php at Github

A simple way to debug php apps

In certain PHP project, I have to work with a "hand made" framework (by other). There are many variables I want to know its value (for debugging). I really do not want to embed 3rd logging frameworks such as monolog. I use error_log (a built-in PHP function) for this task.
$str = "our message";
error_log(__FILE__. $str);
And we see result in /var/log/apache2/error.log (by default).
Reference: error_log PHP reference

May 16, 2016

How to use Bower as frontend dependencies manager for web project based on Laravel 5.x?

1. Install bower globally
$ npm install -g bower
2. We need a bower.json file to get started. The following command will create a file called bower.json.
$ bower init
Or we can create manually in the root of your directory with the following content:
{
  "name": "your-project"
}
3. Add .bowerrc
By default Bower installs into /bower_components, but we want our dependencies in public directory. Create a file named .bowerrc in our root directory with following content:
{
  "directory": "public/bower"
} 
4. Install our front-end dependencies. For example:
$ bower install angular --save
$ bower install jquery --save
Some Related topics:
https://laracasts.com/discuss/channels/laravel/assets-not-accessible-laravel-51