Simple Captcha in PHP

This captcha is simple and can use for any website ^^

<?php
require_once BASE_PATH . '/Code/claviska/simple-php-captcha.php';
class Captcha {
    /**
     * Document: https://github.com/claviska/simple-php-captcha
     */
    public static function checkCaptcha () {
        $isSuccess = FALSE;
        if (
            empty($_POST['simple_captcha_client']) === FALSE &&
            empty($_SESSION['simpleCaptcha']['code']) === FALSE &&
            strtolower($_POST['simple_captcha_client']) == strtolower($_SESSION['simpleCaptcha']['code'])
        ) {
            $isSuccess = TRUE;
        }
        return $isSuccess;
    }
    public static function generateCaptcha () {
        $_SESSION['simpleCaptcha'] = simple_php_captcha([
            'min_length' => 6,
            'max_length' => 6,
            'characters' => '123456789'
        ]);
        return $_SESSION['simpleCaptcha']['image_src'];
    }
    public static function showCaptcha ($class = NULL) {
        return '<div class="captcha-holder ' . $class . '"><img src="' . Captcha::generateCaptcha() . '" class="captcha-img" /><input type="text" name="simple_captcha_client" placeholder="' . convertCase(trans('validation.enter_captcha'), 3) . '" /><a data-href="' . BASE_URL . '/captcha/reset" class="captcha-refresh"><i class="icons fi-refresh"></i></a></div>';
    }
}
class Default_CaptchaController {
    function resetAction() {
        require_once BASE_PATH . '/Code/Captcha.php';
        echo Captcha::generateCaptcha();
    }
}
$('.captcha-refresh').on('click', function () {
	var $me = $(this);
	$.ajax({
		url: $(this).data('href')
	})
	.done(function(src) {
		$me.closest('.captcha-holder').find('.captcha-img').attr('src', src);
	});
});
.captcha-holder {
    &> * {
        display: inline-block;
        width: auto;
        height: 39px;
    }
    &> input {
        width: 125px;
    }
    .captcha-refresh {
        cursor: pointer;
        .icons {
            @include font-size(22px);
            margin-left: 5px;
            position: relative;
            top: 3px;
        }
    }
}

Continue reading Simple Captcha in PHP

Login bằng php-jwt thay cho session, cookie truyền thống

install:

composer require firebase/php-jwt:dev-master
composer require zendframework/zend-config:~2.3
composer require zendframework/zend-http:~2.3

Tham khảo: sitepoint Continue reading Login bằng php-jwt thay cho session, cookie truyền thống

Gulp run as series of tasks

// task cleanDist
gulp.task('cleanDist', function(cb) {
  return del([
    './www/js/configuration.js'
  ]);
});
// task copy-local-files: require 'cleanDist' task
gulp.task('copy-local-files', ['cleanDist'], function(cb) {
  return gulp.src('./../config/local/**/*').pipe(gulp.dest('./www'));
});
// task lint: require 'copy-local-file' task
gulp.task('lint', ['copy-local-files'], function() {
  return gulp.src(paths.js)
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('jshint-stylish'));
});

Bonus: Ionic run task before server and after serve: config in ionic.project file

{
  "name": "songpham",
  "app_id": "20002005",
  "gulpDependantTasks": [ // before serve
    "lint"
  ],
  "gulpStartupTasks": [ // after serve
    "watch"
  ],
  "watchPatterns": [
    "www/**/*",
    "!www/lib/**/*"
  ]
}

Fix bug MSBUILD : error MSB3428: Could not load the Visual C++ component “VCBuild.exe” …

So here it is. I have tested these steps multiple times on (each time) newly created Windows 7 SP1 VMs with IE8.

Scenario: I have a brand new Windows system, what to do?

[Only if it is Windows 7 then and you don’t already] Download .NET Framework 4.5.1 and run the installer.
Download Build Tools 2015, run the build installer.
Download Visual C Build Tools 2015 Preview, run the installer, select Custom, click Next and check both SDKs (8 and 10), click Next and then Install.
Launch regedit Navigator to HKLM\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0. Add string key VCTargetsPath key, set VCTargetsPath=C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\v140
npm config set GYP_MSVS_VERSION 2015
Download and install latest node.js.
Download and install Python 2.7.x.
Open cmd and run npm config set msvs_version 2015 –global.

Hopefully it is a temporary registry fix and they will fix it before Build Tools get out of Technical Preview status. Out of 4 times it created that registry value once.

Start > Run > cmd (and press Ctrl+Shift+Enter to Run as Administrator):
For 64-bit Windows

:: copy paste this command and press enter
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\SxS\VS7 /v 14.0 /t REG_EXPAND_SZ /d ^%programfiles(x86)^%"\Microsoft Visual Studio 14.0\\"

For 32-bit Windows

:: copy paste this command and press enter
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\SxS\VS7 /v 14.0 /t REG_EXPAND_SZ /d ^%programfiles^%"\Microsoft Visual Studio 14.0\\"

Now install the package like npm install selenium-webdriver and it should work!

My installation is not brand new, I had some related stuff installed and now I am getting MSB4019 or MSB8020.

This means somehow you have incorrect version of msbuild in PATH. To fix that, put C:\Program Files (x86)\MSBuild\14.0\Bin; at the beginning of PATH under System Environment Variables. To do it quickly (without making permanent change), run SET PATH=%ProgramFiles(x86)%\MSBuild\14.0\Bin;%PATH% in command prompt in case of 64-bit Windows or %ProgramFiles%\MSBuild\14.0\Bin; in case of 32-bit Windows. Then run your intended npm install command.

Finally, what to expect?

Expect every package which requires C/C++ code compilation at the time of installation to succeed on Windows, exactly as they compile at installation time on Unix-like operating systems, except those which are not supporting Windows at all (yet?) such as node-gd. For such packages, you can find their repository URL on package’s http://npmjs.org/ page and find the Windows support status in their issue tracker.

From issue in “Windows users are not happy”

Creating login middleware in Express Node js

app.js

...
app.use(require('./login')); /* include middleware login */
...

index.js

var express = require('express');
var router = express.Router();
router.all('/', function (req, res) {
  res.render('index', {
    title: 'Express'
  });
});
module.exports = router;

Continue reading Creating login middleware in Express Node js

Khai báo hàm callback gọi lại trong Javascript

[script language=”javascript”]
var http = require(‘http’),
feed = ‘http://www.baomoi.com/&#8217;,
ready = false;
function decide (cb) {
console.log(‘deciding’);
setTimeout(function () {
if (Date.now() % 2) { return console.log(‘rejected’); }
ready = true;
cb();
}, 2000);
}
http.get(feed, function (res) {
res.on(‘readable’, function log () {
if (!ready) { return decide(log); }
console.log(res.read() + ”);
});
});
[/script]
Chú ý hàm log() được gọi lại nhiều lần

Cách xây dựng directive bằng Angular Js 1

Khi tạo 1 directive, đầu tiên ta phải suy nghĩ xem ta viết cái gì? Sau đó ta xem directive của ta hoạt động ra sao? Và cuối cùng là ta truyền vào cái gì để nó hoạt động?

Để mô tả luồng tư duy, mình thử viết 1 modal directive cơ bản nhất:
– Viết cái gì: Modal
– Hoạt động: Modal có tính năng click vào button thì hiện lên, click vào background thì tắt đi.
– Truyền vào: Biến bật/tắt và Content của modal.

Sau khi tư duy xong, ta có thể khái quát được mô hình như sau:
– name directive: modalWindow
– replace: true (dĩ nhiên)
– transclude: true (vì cần truyền content vào modal, sau này cứ khi nào directive cần truyền dynamic content vào thì transclude là true hết)
– biến bật/tắt: show (false là tắt, true là bật) Continue reading Cách xây dựng directive bằng Angular Js 1

Angular Js 1: Auth check when change state

Controller:

...
$stateProvider
  .state('home.contact', {
    url: '/contact',
    resolve: {
      currentAuth: function(AuthFactory) {
        return AuthFactory.authPromise();
      }
    }
  });
...

Service:

...
.factory('AuthFactory', function ($q, $timeout, $rootScope) {
  var factoryObject = {
    authPromise: function () { /* promise to check is login or not */
      // Initialize a new promise
      var deferred = $q.defer();
      $timeout(function () {
        if ($rootScope.isAuthenticated) {
          deferred.resolve();
        } else {
          deferred.reject('AUTH_REQUIRED');
        }
      });
      return deferred.promise;
    }
  };
  return factoryObject;
})
...

Root Controller:

...
$rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
  if (error === 'AUTH_REQUIRED') {
    $state.go('home.dash');
  }
});
...

Use promise in Angular Js 1

// Story: One morning, a father says to his son: "Go and get the weather forecast, son!"
// Every Sunday morning, a father asks his son to go and find out the weather forecast for the afternoon, by using his super-strong telescope to look across the horizon from the tallest hill by their house. The son promises his dad he will go and get the weather forecast. He creates a promise with his dad at the door when he leaves.
// At that point, the dad decides if the weather tomorrow is good, he'll prepare a fishing trip for tomorrow. If it's bad he won't. Also, if the son is unable to get a forecast, he'll stay in as well.
// After 30mins or so, the son comes back. Different things happen from week-to-week
// ---------------------------------------------------------------------------
// can detect the result
var prepareFishingTrip = function (data) {
    console.log('the weather is fine');
    console.log(data);
};
var prepareSundayRoastDinner = function prepareSundayRoastDinner (data) {
    console.log('the weather is bad');
    console.log(data);
};
// can't detect the result
var dontKnowPrepareSundayRoastDinnerOrNot = function prepareSundayRoastDinner (res) {
    console.log('the son can\'t retrieve the weather, he return everything');
    console.log(res);
};
angular.module('myApp', [])
.factory('SonService', function ($http, $q) {
    return {
        getWeather: function() {
            // the $http API is based on the deferred/promise APIs exposed by the $q service
            // so it returns a promise for us by default
            return $http.get('http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=2de143494c0b295cca9337e1e96b00e0')
                .success(function(res) {
                    if (typeof res.data === 'object') {
                        return res.data;
                    } else {
                        // invalid response
                        return $q.reject(res);
                    }
                })
                .error(function(res) {
                    // something went wrong
                    return $q.reject(res);
                });
        }
    };
})
.controller('Ctrl', function($q, SonService) {
    SonService.getWeather()
        // success() called when son gets back
        .success(function(data) {
            // promise fulfilled
            if (data.wind && data.wind.speed > 2) { // if success
                prepareFishingTrip(data);
            } else {
                prepareSundayRoastDinner(data); // if the weather is not good
            }
        })
        .error(function(res) {
            // promise rejected
            dontKnowPrepareSundayRoastDinnerOrNot(res);
        });
});