Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Sunday, March 10, 2019

facebook instant game custom server communication Nodejs, PHP

game.js

const BACKEND_URL = "https://localhost/quizbattle";
const BACKEND_URL_API = BACKEND_URL + "/api";
var game = {};
var gameData = {};
var gameOptions = {
    width: 0,
    height: 0,
    backgroundColor: 0xFFFFFF,
    localStorageName: "__ab__"
};
var gameStuff = {
    playerId: "",
    playerName: "",
    playerPic: "",
    locale: ""
};

window.onload = function () {
    $('#home-section').hide();

    FBInstant.initializeAsync().then(function () {
        FBInstant.startGameAsync().then(function () {
            gameStuff.playerId = FBInstant.player.getID();
            gameStuff.playerName = FBInstant.player.getName();
            gameStuff.playerPic = FBInstant.player.getPhoto();
            gameStuff.locale = FBInstant.getLocale();
            gameStuff.contextType = FBInstant.context.getType();

            gameOptions.height = window.innerHeight;
            gameOptions.width = window.innerWidth / 2;

            $('#u-photo-field').attr('src', gameStuff.playerPic);
            $('#u-name-field').html(gameStuff.playerName);
            $('#context-type').html(gameStuff.contextType);

            $('#home-section').show();
           
            loadingInitialData();
        });
    });
};

function getOrCreateContextId() {
    var contextType = FBInstant.context.getType();
    var contextId = FBInstant.context.getID();
   
    console.log(contextType);
    if (contextType == 'SOLO') {
        contextId = FBInstant.player.getID() + '_SOLO';
    }
    return contextId;
}

function showMessage(div, message) {
    document.getElementById(div).innerHTML = message;
}

function loadingInitialData() {
    var contextId = getOrCreateContextId();

    FBInstant.player.getSignedPlayerInfoAsync(contextId)
            .then(function (signedPlayerInfo) {
                // Requesting data from backend passing the signature as an argument
                // The backend APP can retrieve contextId from the signature
                var signature = signedPlayerInfo.getSignature();
                return new backendClient(BACKEND_URL_API).load(contextId, signature);
            })
            .then(function (response) {
                // Got successful response from backend
                console.log('Loaded from backend', response);
                if (response.empty) {
                    showMessage('test', 'No data');
                } else {
                    showMessage('test', JSON.stringify(response.data));
                }
            }.bind(this))
            .catch(function (error) {
                // Got error response from backend
                console.error('Not loaded from backend', error);
                showMessage('error-messages', 'Error loading backend data:' + error.message);
            }.bind(this));
}

function singlePlayBoot() {

}

function multiPlayBoot() {

}

function leaderBoardBoot() {

}

function helpBoot() {

}


node.js server side


var pg = require('pg');
var crypto = require('crypto-js');

module.exports = function(app) {

app.post('/get-match', function(request, response) {
        var signature = request.body.signature;
       
        var isValid = validate(signature);
       
        if (isValid) {
            var contextId = getEncodedData(signature);
            loadMatchDataAsync(contextId)
            .then(function(result){
                if (result) {
                    response.json({'success':true, 'contextId':contextId, 'empty': false, 'data':result});
                } else {
                    response.json({'success':true, 'contextId':contextId, 'empty': true});
                }
            })
            .catch(function(err){
                response.json({'success':false, 'error':err});
            });
        } else {
            console.log('encoded data', getEncodedData(signature));
            response.json({'success':false, 'error':'invalid signature'});
        }
       
    })

loadMatchDataAsync = function(contextId) {
        return new Promise(function(resolve, reject){
            pg.connect(process.env.DATABASE_URL, function(err, client, done) {
                client.query('SELECT * FROM matches WHERE context = $1::text', [contextId], function(err, result) {
                    done();
                    if (err) {
                        reject(err);
                    }
                    if (result.rows.length > 0) {
                        resolve(result.rows[0].data);
                    } else {
                        resolve();
                    }
                });
            });
        });
    };
   
    validate = function(signedRequest) {
        try{
           
            var firstpart = signedRequest.split('.')[0];
            var replaced = firstpart.replace(/-/g, '+').replace(/_/g, '/');
            var signature = crypto.enc.Base64.parse(replaced).toString();
            const dataHash = crypto.HmacSHA256(signedRequest.split('.')[1], process.env.APP_SECRET).toString();
            var isValid = signature === dataHash;
            if (!isValid) {
                console.log('Invalid signature');
                console.log('firstpart', firstpart);
                console.log('replaced ', replaced);
                console.log('Expected', dataHash);
                console.log('Actual', signature);
            }
           
            return isValid;
        } catch (e) {
            return false;
        }
    };
   
    getEncodedData = function(signedRequest) {
        try {
           
            const json = crypto.enc.Base64.parse(signedRequest.split('.')[1]).toString(crypto.enc.Utf8);
            const encodedData = JSON.parse(json);
           
            /*
            Here's an example of encodedData can look like
            {
                algorithm: 'HMAC-SHA256',
                issued_at: 1520009634,
                player_id: '123456789',
                request_payload: 'backend_save'
            }
            */
           
            return encodedData.request_payload;
        } catch (e) {
            return null;
        }
    };
}


PHP server side


private function _validate($signedRequest) {
        try {
            list($encoded_signature, $payload) = explode('.', $signedRequest, 2);

            // decode the data
            $signature = base64_url_decode($encoded_signature);
            //$data = json_decode(base64_url_decode($payload), true);
           
            // confirm the signature
            $expected_signature = hash_hmac('sha256', $payload, $this->facebook_config['app_secret'], $raw = true);
            $isValid = $signature === $expected_signature;

            if (!$isValid) {
                error_log('Bad Signed JSON signature!');
                return null;
            }

            return $isValid;
        } catch (Exception $ex) {
            return false;
        }
    }

    private function _getEncodedData($signedRequest) {
        try {
            $encodedData = json_decode(base64_url_decode(explode('.', $signedRequest)[1]), true);
            /*
            $encodedData = {
                "status":true,
                "data":{
                    "algorithm":"HMAC-SHA256",
                    "issued_at":1552157956,
                    "player_id":"2522121991191915",
                    "request_payload":"2522121991191915_SOLO"
                }
            }
             */

            return $encodedData;
        } catch (Exception $ex) {
            return null;
        }
    }


function load_post() {

$signature = $this->post('signature');

            $isValid = $this->_validate($signature);

            if ($isValid) {
                $edata = $this->_getEncodedData($signature);
                $this->success($edata->data);
            } else {
                $this->error('Invalid Request!');
            }
..........................
}

Monday, March 20, 2017

php session start with save_path

<?php
$dr = $_SERVER['DOCUMENT_ROOT'];
echo '$dr is '.$dr.'<br>';
$dn = dirname($dr);
echo '$dn is '.$dn.'<br>';
$sp = $dn . '/../sessions';
echo '$sp is '.$sp.'<br>';
$rp = realpath($sp);/*C:/sessions on windows*/
echo '$rp is '.$rp.'<br>';
ini_set('session.save_path', $rp);
echo 'ini_get is '.ini_get('session.save_path').'<br>';
session_start();
echo 'session is '.$_SESSION['hello'];
$_SESSION['hello'] = 'boroo';

Thursday, January 5, 2017

php detect _SERVER['HTTP_USER_AGENT'] is IE 8, 9, 10, 11

<?php
echo $_SERVER['HTTP_USER_AGENT'];exit;
preg_match('/MSIE (.*?);/', $_SERVER['HTTP_USER_AGENT'], $matches);
if(count($matches)<2){
  preg_match('/Trident\/\d{1,2}.\d{1,2}; rv:([0-9]*)/', $_SERVER['HTTP_USER_AGENT'], $matches);
}

if (count($matches)>1){
  //Then we're using IE
  $version = $matches[1];

  switch(true){
    case ($version<=8):
      //IE 8 or under!
 echo '8';
      break;

    case ($version==9 || $version==10):
      //IE9 & IE10!
 echo '9-10';
      break;

    case ($version==11):
      //Version 11!
 echo '11';
      break;

    default:
echo $version;
      //You get the idea
  }
}

mysqli database engine change to MyISAM using php

<?php
$conn = mysqli_connect('localhost','root','');
$dbs = array();
$dbs[] = $_GET['database'];

foreach($dbs as $v){
    mysqli_select_db($conn, $v);
    $q = mysqli_query($conn, 'show tables');
    $tables = array();
    while($r = mysqli_fetch_row($q)){
        $tables[] = $r[0];
    }
$c=0;
    foreach($tables as $t){
        echo "do $v.$t<br>";
        mysqli_query($conn, 'ALTER TABLE `'.$t.'` ENGINE=MyISAM;');
$c++;
    }
echo $c." tables changed.";
}
mysqli_close($conn);

Wednesday, May 4, 2016

php data array echo to excel file

<?PHP
  $data = array(
    array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25),
    array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18),
    array("firstname" => "James", "lastname" => "Brown", "age" => 31),
    array("firstname" => "Patricia", "lastname" => "Williams", "age" => 7),
    array("firstname" => "Michael", "lastname" => "Davis", "age" => 43),
    array("firstname" => "Sarah", "lastname" => "Miller", "age" => 24),
    array("firstname" => "Patrick", "lastname" => "Miller", "age" => 27)
  );

  function cleanData(&$str)
  {
    $str = preg_replace("/\t/", "\\t", $str);
    $str = preg_replace("/\r?\n/", "\\n", $str);
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
  }

  // file name for download
  $filename = "website_data_" . date('Ymd') . ".xls";

  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: application/vnd.ms-excel");

  $flag = false;
  foreach($data as $row) {
    if(!$flag) {
      // display field/column names as first row
      echo implode("\t", array_keys($row)) . "\n";
      $flag = true;
    }
    array_walk($row, 'cleanData');
    echo implode("\t", array_values($row)) . "\n";
  }

  exit;
?>

Saturday, December 26, 2015

codeigniter login controller with facebook login methods

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

// Skip these two lines if you're using Composer
define('FACEBOOK_SDK_V4_SRC_DIR', APPPATH . 'libraries/facebook-php-sdk-v4/src/Facebook/');
require APPPATH . 'libraries/facebook-php-sdk-v4/autoload.php';

use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\GraphUser;

class login extends HO_Site {

    public function __construct() {
        parent::__construct();

        $this->load->config('facebook');
        $this->load->library('session');

        $this->lang->load('user');
        $this->load->library('validation/UserValidation', array($this), 'validation');

        FacebookSession::setDefaultApplication(
                $this->config->item('api_id', 'facebook'), $this->config->item('app_secret', 'facebook'));
    }

    public function fbs() {
        $helper = new FacebookRedirectLoginHelper($this->config->item('redirect_url', 'facebook'));
        $loginUrl = $helper->getLoginUrl($this->config->item('permissions', 'facebook'));
        redirect($loginUrl);
    }

    public function fbe() {
        $helper = new FacebookRedirectLoginHelper($this->config->item('redirect_url', 'facebook'));
        $session = FALSE;
        try {
            if ($session === FALSE) {
                $session = $helper->getSessionFromRedirect();
            }
        } catch (FacebookRequestException $ex) {
            log_message('error', $ex->getMessage());
        } catch (\Exception $ex) {
            log_message('error', $ex->getMessage());
        }
        if ($session) {
            try {
                $me = (new FacebookRequest(
                        $session, 'GET', '/me'
                        ))->execute()->getGraphObject(GraphUser::className());

                $firstname = $me->getFirstName();
                $lastname = $me->getLastName();
                $email = $me->getEmail();

                if (!User()->logged_in()) {
                    $user = $this->user_model->find_user($email);

                    if (empty($user) || !isset($user['id'])) {

                        $new_password = User()->get_random_password();

                        $posted['firstname'] = $firstname;
                        $posted['lastname'] = $lastname;
                        $posted['username'] = $email;
                        $posted['email'] = $email;
                        $posted['salt'] = User()->get_salt();
                        $posted['password'] = User()->get_hashed_password($posted, $new_password);
                        $posted['createddate'] = utc_datetime();

                        $role = $this->role_model->get(array('code' => 'user'));
                        $posted['role_id'] = $role['id'];
                        $posted['id'] = $this->user_model->save($posted);
                       
                    } else {
                        if (User()->login($email, $user['password'], true, true)) {
                            redirect(site_url());
                        } else {
                            redirect(site_url('login'));
                        }
                    }
                } else {
                    redirect(site_url());
                }
            } catch (FacebookRequestException $e) {
                // The Graph API returned an error
                $this->error($ex->getMessage());
            } catch (\Exception $e) {
                // Some other error occurred
                $this->error($ex->getMessage());
            }
        } else {
            redirect(site_url('login'));
        }
    }

    public function index($error = '') {
        if (User()->logged_in()) {
            redirect(site_url());
        } else {
            $loginUrl = site_url('login/fbs');
            $this->view('index', array('loginUrl' => $loginUrl, 'error' => $error));
        }
    }

    public function auth() {
        if ($this->validation->validate_login()) {
            $posted = $this->input->post();
            $email = $posted['username'];
            $password = $posted['password'];

            try {
                if (!User()->logged_in()) {
                    $user = $this->user_model->find_user($email);

                    if (empty($user) || !isset($user['id'])) {
                        $posted['username'] = $email;
                        $posted['email'] = $email;
                        $posted['salt'] = User()->get_salt();
                        $posted['password'] = User()->get_hashed_password($posted, $password);
                        $posted['createddate'] = utc_datetime();

                        $role = $this->role_model->get(array('code' => 'user'));
                        $posted['role_id'] = $role['id'];
                        $posted['id'] = $this->user_model->save($posted);
                    } else {
                        if (User()->login($email, $password, true)) {
                            redirect(site_url());
                        } else {
                            $this->index('Нэр эсвэл нууц үг буруу байна!');
                        }
                    }
                } else {
                    redirect(site_url());
                }
            } catch (Exception $ex) {
                //500 Internal Server Error
                log_message('error', $ex->getMessage());
                $this->index('Нэвтрэх үед алдаа гарлаа!');
            }
        } else {
            //400 Bad Request
            $this->index('Нэр эсвэл нууц үг буруу байна!');
        }
    }

    public function reset() {
        if ($this->validation->validate_reset()) {
            try {
                $posted = $this->input->post('email');
                if (User()->reset($posted)) {
                    $this->success('Нууц үгийг сэргээлээ!');
                } else {
                    $this->error('Нууц үгийг сэргээлээ!');
                }
            } catch (Exception $ex) {
                log_message('error', $ex->getMessage());
                $this->error($ex->getMessage());
            }
        } else {
            $this->error('Хүсэлт буруу байна!');
        }
    }

}

Monday, June 22, 2015

Facebook libraries using example for Codeigniter

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

// Skip these two lines if you're using Composer
define('FACEBOOK_SDK_V4_SRC_DIR', APPPATH . 'libraries/facebook-php-sdk-v4/src/Facebook/');
require APPPATH . 'libraries/facebook-php-sdk-v4/autoload.php';

use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\GraphUser;

class login extends HO_Site {

    public function __construct() {
        parent::__construct();

        $this->load->config('facebook');
        $this->load->library('session');

        $this->lang->load('user');
        $this->load->library('validation/UserValidation', array($this), 'validation');

        FacebookSession::setDefaultApplication(config_item('facebook_app_id'), config_item('facebook_app_secret'));
    }

    public function fbs() {
        $helper = new FacebookRedirectLoginHelper($this->config->item('redirect_url', 'facebook'));
        $loginUrl = $helper->getLoginUrl(); //($this->config->item('permissions', 'facebook'));
        redirect($loginUrl);
    }

    public function fbe() {
        $helper = new FacebookRedirectLoginHelper($this->config->item('redirect_url', 'facebook'));
        $session = FALSE;
        try {
            if ($session === FALSE) {
                $session = $helper->getSessionFromRedirect();
            }
        } catch (FacebookRequestException $ex) {
            log_message('error', $ex->getMessage());
        } catch (\Exception $ex) {
            log_message('error', $ex->getMessage());
        }
        if ($session) {
            try {
                $me = (new FacebookRequest(
                        $session, 'GET', '/me'
                        ))->execute()->getGraphObject(GraphUser::className());

                $firstname = $me->getFirstName();
                $lastname = $me->getLastName();
                $email = $me->getEmail();

                if (!User()->logged_in()) {
                    $user = $this->user_model->find_user($email);

                    if (empty($user) || !isset($user['id'])) {

                        $new_password = User()->get_random_password();

                        $posted['firstname'] = $firstname;
                        $posted['lastname'] = $lastname;
                        $posted['username'] = $email;
                        $posted['email'] = $email;
                        $posted['salt'] = User()->get_salt();
                        $posted['password'] = User()->get_hashed_password($posted, $new_password);
                        $posted['createddate'] = utc_datetime();

                        $role = $this->role_model->get(array('code' => 'user'));
                        $posted['role_id'] = $role['id'];
                        $posted['id'] = $this->user_model->save($posted);
                       
                    } else {
                        if (User()->login($email, $user['password'], true, true)) {
                            redirect(site_url());
                        } else {
                            redirect(site_url('login'));
                        }
                    }
                } else {
                    redirect(site_url());
                }
            } catch (FacebookRequestException $e) {
                // The Graph API returned an error
                $this->error($ex->getMessage());
            } catch (\Exception $e) {
                // Some other error occurred
                $this->error($ex->getMessage());
            }
        } else {
            redirect(site_url('login'));
        }
    }

    public function index($error = '') {
        if (User()->logged_in()) {
            redirect(site_url());
        } else {
            $loginUrl = site_url('login/fbs');
            $this->view('index', array('loginUrl' => $loginUrl, 'error' => $error));
        }
    }

    public function auth() {
        if ($this->validation->validate_login()) {
            $posted = $this->input->post();
            $email = $posted['username'];
            $password = $posted['password'];

            try {
                if (!User()->logged_in()) {
                    $user = $this->user_model->find_user($email);

                    if (empty($user) || !isset($user['id'])) {
                        $posted['username'] = $email;
                        $posted['email'] = $email;
                        $posted['salt'] = User()->get_salt();
                        $posted['password'] = User()->get_hashed_password($posted, $password);
                        $posted['createddate'] = utc_datetime();

                        $role = $this->role_model->get(array('code' => 'user'));
                        $posted['role_id'] = $role['id'];
                        $posted['id'] = $this->user_model->save($posted);
                    } else {
                        if (User()->login($email, $password, true)) {
                            redirect(site_url());
                        } else {
                            $this->index('Нэр эсвэл нууц үг буруу байна!');
                        }
                    }
                } else {
                    redirect(site_url());
                }
            } catch (Exception $ex) {
                //500 Internal Server Error
                log_message('error', $ex->getMessage());
                $this->index('Нэвтрэх үед алдаа гарлаа!');
            }
        } else {
            //400 Bad Request
            $this->index('Нэр эсвэл нууц үг буруу байна!');
        }
    }

    public function reset() {
        if ($this->validation->validate_reset()) {
            try {
                $posted = $this->input->post('email');
                if (User()->reset($posted)) {
                    $this->success('Нууц үгийг сэргээлээ!');
                } else {
                    $this->error('Нууц үгийг сэргээлээ!');
                }
            } catch (Exception $ex) {
                log_message('error', $ex->getMessage());
                $this->error($ex->getMessage());
            }
        } else {
            $this->error('Хүсэлт буруу байна!');
        }
    }

}

PHPExcel libraries using example for Codeigniter

public function export() {
        $this->load->library('PHPExcel');

        $where = array(
            'role.code' => 'user',
            'user_meta.key' => 'winner',
            'user_meta.value' => 'OK');
        $joins = array('user.role_id=role.id', 'user.id=user_meta.user_id');
        $fields = 'user.id,user.email,user.username,user.firstname,user.lastname';

        $winner_users = $this->user_model->get_list($where, null, $fields, $joins);

        $winner_list = array();
        foreach ($winner_users as $winner_user) {
            $user_meta = $this->user_model->get(
                    array('user_id' => $winner_user['id'], 'key' => 'article_name'), 'user_meta');
            $winner_user['article_name'] = $user_meta['value'];
            $winner_list[] = $winner_user;
        }

        $heading = array('ID', 'И-Мэйл', 'Хэрэглэгч', 'Нэр', 'Овог', 'Урамшуулал');

        //Create a new PHPExcel Object
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle("Ялагч болсон хэрэглэгчид");

        //Loop Heading
        $rowNumberH = 1;
        $colH = 'A';
        foreach ($heading as $h) {
            $cell_name = $colH . $rowNumberH;
            $objPHPExcel->getActiveSheet()->setCellValue($cell_name, $h);
            // Make bold cells
            $objPHPExcel->getActiveSheet()->getStyle($cell_name)->getFont()->setBold(true);
            $colH++;
        }

        //Loop Result
        $no = 2;
        foreach ($winner_list as $winner) {
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $no, $winner['id']);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $no, $winner['email']);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $no, $winner['username']);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $no, $winner['firstname']);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $no, $winner['lastname']);
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $no, $winner['article_name']);
            $no++;
        }

        //Columns size by auto
        foreach (array('B', 'C', 'D', 'E', 'F') as $colname) {
            $col = $objPHPExcel->getActiveSheet()->getColumnDimension($colname);
            $col->setAutoSize(true);
        }
        $objPHPExcel->getActiveSheet()->calculateColumnWidths();

        //Freeze pane
        $objPHPExcel->getActiveSheet()->freezePane('A1');

        //Save as an Excel BIFF (xls) file
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

        $filename = "winners_" . date('Ymd') . ".xls";
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$filename\"");
        header('Cache-Control: max-age=0');

        $objWriter->save('php://output');
        exit;
    }

Wednesday, June 17, 2015

php codeigniter facebook javascript sdk example

<script>

        window.fbAsyncInit = function () {
            FB.init({
                appId: '<?php echo config_item('facebook_app_id'); ?>',
                cookie: true, // enable cookies to allow the server to access
                // the session
                xfbml: true, // parse social plugins on this page
                version: 'v2.2' // use version 2.2
            });
            FB.getLoginStatus(function (response) {
                statusChangeCallback(response);
            });
        };

        // Load the SDK asynchronously
        (function (d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id))
                return;
            js = d.createElement(s);
            js.id = id;
            js.src = "//connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));

        function statusChangeCallback(response) {
            console.log('statusChangeCallback');
            console.log(response);

            if (response.status === 'connected') {
                // Logged into your app and Facebook.
                getFbUserInfo(response);
            } else if (response.status === 'not_authorized') {
                // The person is logged into Facebook, but not your app.
                document.getElementById('fbstatus').innerHTML = 'Please log ' +
                        'into this app.';
            } else {
                // The person is not logged into Facebook, so we're not sure if
                // they are logged into this app or not.
                if (response.status !== 'unknown') {
                    document.getElementById('fbstatus').innerHTML = 'Please log ' +
                            'into Facebook.';
                }
            }
        }

        function getFbUserInfo(auth) {
            console.log('Welcome!  Fetching your information.... ');
            FB.api('/me', function (me) {
                console.log('Successful login for: ' + me.name);

                $('#fbstatus').text('Үйлчлүүлсэнд баярлалаа, ' + me.name + '!').show();

                $.ajax({
                    type: "post",
                    url: "<?php echo site_url('api/auth/login'); ?>",
                    data: 'email=' + me.email + "&name=" + me.name + "&access=" + auth.authResponse.accessToken,
                    beforeSend: function () {
                        $('#loading').show();
                        alert(auth.authResponse.accessToken);
                    }
                }).done(function (data) {
                    $('#loading').hide('slow');
                    alert(data);
                });
            });
        }

        $(document).ready(function () {
//            setTimeout(function () {
//                $('.fb-login-button').show();
//            }, 2000);
        });
    </script>

Thursday, April 16, 2015

How to send an xml from a c# desktop application to a php server script and parse it?

c#

public partial class frmSending : Form
    {
        public frmSending(string url, string file, XmlDocument xml)
        {
            InitializeComponent();

            this.Url = url;
            this.XmlFile = file;
            this.Xml = xml;
            this.Sent += frmSending_Sent;
        }

        void frmSending_Sent(object sender, EventArgs e)
        {
            if (this.Ex != null)
            {
                MessageBox.Show(Ex.Message, "Алдаа", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                MessageBox.Show("Амжилттай илгээлээ!", "Мэдэгдэл", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            this.Close();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            thread = new Thread(post_to_internet);
            thread.Start();
        }

        private void post_to_internet()
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.ContentType = "application/xml";
                request.Accept = "application/xml";

                StringWriter stringWriter = new StringWriter();
                XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
                Xml.WriteTo(xmlTextWriter);
                byte[] bytes = Encoding.UTF8.GetBytes(stringWriter.ToString());

                request.ContentLength = bytes.Length;

                using (Stream putStream = request.GetRequestStream())
                {
                    putStream.Write(bytes, 0, bytes.Length);
                }

                // Log the response from Redmine RESTful service
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    this.Invoke(Sent, new object[] { reader.ReadLine(), EventArgs.Empty });
                }

                //using (WebClient request = new WebClient())
                //{
                //    request.UploadFile(Url, "POST", XmlFile);
                //}
            }
            catch (Exception ex)
            {
                this.Ex = ex;
                this.Invoke(Sent, new object[] { ex, EventArgs.Empty });
            }
        }

        public string Url { get; set; }
        public string XmlFile { get; set; }
        public XmlDocument Xml { get; set; }
        private Thread thread { get; set; }
        private event EventHandler Sent;
        public Exception Ex { get; set; }

        private void frmSending_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape || e.KeyCode == Keys.F1)
            {
                thread.Abort();
            }
        }
    }
<?php

include "db.config.php";
debug_log('uploaded ' . $fp);
$fp = fopen('php://input', 'rb');
file_put_contents('report.xml', $fp);

//$upload = isset($_FILES) ? reset($_FILES) : null;
//debug_log('uploaded ' . $upload['tmp_name']);
//move_uploaded_file($upload['tmp_name'], $upload['name']);
afterwards the file test.dat on the server contains
<?xml version="1.0" encoding="utf-8"?>
<Foo>
  <bar>
    <type>System.String</type>
    <value>Stackoverflow</value>
  </bar>
  <bar>
    <type>System.Boolean</type>
    <value>True</value>
  </bar>
  <bar>
    <type>System.Char</type>
    <value>x</value>
  </bar>
  <bar>
    <type>System.Int32</type>
    <value>42</value>
  </bar>
</Foo>

php SimpleXMLElement tutorial

<?php
$xmlString = '<?xml version="1.0" encoding="utf-8"?>
<Foo>
  <bar>
    <type>System.String</type>
    <value>Stackoverflow</value>
  </bar>
  <bar>
    <type>System.Boolean</type>
    <value>True</value>
  </bar>
  <bar>
    <type>System.Char</type>
    <value>x</value>
  </bar>
  <bar>
    <type>System.Int32</type>
    <value>42</value>
  </bar>
</Foo>';
//header('Content-Type: application/xml');
//echo $xmlString;exit;

$xml = new SimpleXMLElement($xmlString);
foreach ($xml->bar as $element) {
echo $element->type."<br>";
echo $element->value."<br>";
// or...........
//foreach($element as $key => $val) {
//echo "{$key}: {$val}<br>";
//}
}
?>

Thursday, February 5, 2015

php codeigniter html pivot table example

IN CONTROLLER

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class home extends HO_Site {

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        $this->load->model('article_model');
        $where = array();
        $where['limit'] = 5;
        $where['offset'] = 0;
        $model = $this->article_model->get_list($where, null, array('id,title,createddate'));
        $this->view(array('data' => $model));
    }

}

IN VIEW

<?php
header('Content-Type: text/html; charset=utf-8');
echo 'processing...<br>';
print_r($data);
?>
<table style="border:1px solid #000;padding:5px;">
    <thead>
        <tr>
            <?php
            echo '<th>Талбар:</th>';
            for ($i = 0; $i < count($data); $i++) {
                echo '<th>Хэрэглэгч-' . $i . '</th>';
            }
            ?>
        </tr>
    </thead>
    <tbody>
        <?php
        $fieldNames = array_keys($data[0]);
        for ($i = 0; $i < count($fieldNames); $i++) {
            echo '<tr>';
            for ($j = 0; $j < count($data); $j++) {
                $item = $data[$j];
                if ($j == 0) {
                    echo '<th>' . $fieldNames[$i] . '</th>';
                }
                echo '<td>' . $item[$fieldNames[$i]] . '</td>';
            }
            echo '</tr>';
        }
        ?>
    </tbody>
</table>

RESULT





Wednesday, October 22, 2014

php дээр том жижиг үсэг ялгалгүй текст солих арга

$text = "while Машин. Wear socks машин их МАШ NOW";
$context = preg_replace_callback("/(маш)+/iu", function($a) {
    return '<b>' . $a[1] . '</b>';
}, $text);
echo $context;

Sunday, August 31, 2014

how can use protected CI_DB_active_record->_compile_select() method as public get_compile_select()

1. copy system/core/Loader.php to application/core/Loader.php

2. copy system/database/DB.php to application/database/DB.php

3. open application/core/Loader.php, change method like this below


public function database($params = '', $return = FALSE, $active_record = NULL)
    {
        // Grab the super object
        $CI =& get_instance();
       
        // Do we even need to load the database class?
        if (class_exists('CI_DB') AND $return == FALSE AND $active_record == NULL AND isset($CI->db) AND is_object($CI->db))
        {
            return FALSE;
        }

        // BOROO edited this code [start]
        // _compile_select удамших функцийг ашиглахын тулд өөрчлөлт хийв
        //require_once(BASEPATH.'database/DB.php');
        require_once(APPPATH.'database/DB.php');
        // BOROO edited this code [start]

        if ($return === TRUE)
        {
            return DB($params, $active_record);
        }

        // Initialize the db variable.  Needed to prevent
        // reference errors with some configurations
        $CI->db = '';

        // Load the DB class
        $CI->db =& DB($params, $active_record);
    }


4. open application/database/DB.php, edit method like this below


require_once(BASEPATH . 'database/DB_driver.php');

    if (!isset($active_record) OR $active_record == TRUE) {
        require_once(BASEPATH . 'database/DB_active_rec.php');

        if (!class_exists('CI_DB')) {
            // BOROO edited this code [start]
            if(CI_VERSION == '2.1.4') {
                eval('class CI_DB extends CI_DB_active_record {
                    public function get_compile_select() {
                        return $this->_compile_select();
                    }
                }');
            } else {
                eval('class CI_DB extends CI_DB_active_record { }');
            }
            // BOROO edited this code [end]
        }
    } else {
        if (!class_exists('CI_DB')) {
            eval('class CI_DB extends CI_DB_driver { }');
        }
    }


5. now you can use get_compile_select()


in base_model extends CI_Model {

public function get_compile_select() {
        $this->{$this->db_group}->select('*');
        $this->{$this->db_group}->from($this->table);
        $this->{$this->db_group}->order_by("title", "asc");
        $this->{$this->db_group}->limit(100, 0);
        $subQuery = $this->{$this->db_group}->get_compile_select();
        return $subQuery;
    }
.................................
}

public category_model extends base_model {
..................................
}


in controller


echo "<hr>";
        echo $this->category_model->get_compile_select();
        echo "<hr>";
        exit;


result

SELECT * FROM (`category`) ORDER BY `title` asc LIMIT 100

//now u can get generate sql query without running or last_query()

Saturday, August 30, 2014

AngularJs Simple Example: Post Data to PHP page

HTML
 
<!DOCTYPE html>
<html ng-app>
    <head>
        <title>AngularJs Post Example: DevZone.co.in </title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
        <style>
            #dv1{
                border:1px solid #DBDCE9; margin-left:auto;
                margin-right:auto;width:220px;
                border-radius:7px;padding: 25px;
            }
 
            .info{
                border: 1px solid;margin: 10px 0px;
                padding:10px;color: #00529B;
                background-color: #BDE5F8;list-style: none;
            }
            .err{
                border: 1px solid;  margin: 10px 0px;
                padding:10px;  color: #D8000C;
                background-color: #FFBABA;   list-style: none;
            }
        </style>
    </head>
    <body>
        <div id='dv1'>
            <form ng-controller="FrmController">
                <ul>
                    <li class="err" ng-repeat="error in errors"> {{ error}} </li>
                </ul>
                <ul>
                    <li class="info" ng-repeat="msg in msgs"> {{ msg}} </li>
                </ul>
                <h2>Sigup Form</h2>
                <div>
                    <label>Name</label>
                    <input type="text" ng-model="username" placeholder="User Name" style='margin-left: 22px;'>
                </div>
                <div>
                    <label>Email</label>
                    <input type="text" ng-model="useremail" placeholder="Email" style='margin-left: 22px;'>
                </div>
                <div>
                    <label>Password</label>
                    <input type="password" ng-model="userpassword" placeholder="Password">
                </div>
                <button ng-click='SignUp();' style='margin-left: 63px;margin-top:10px'>SignUp</button>
            </form>
        </div>
 
        <script type="text/javascript">
            function FrmController($scope, $http) {
                $scope.errors = [];
                $scope.msgs = [];
 
                $scope.SignUp = function() {
 
                    $scope.errors.splice(0, $scope.errors.length); // remove all error messages
                    $scope.msgs.splice(0, $scope.msgs.length);
 
                    $http.post('post_es.php', {'uname': $scope.username, 'pswd': $scope.userpassword, 'email': $scope.useremail}
                    ).success(function(data, status, headers, config) {
                        if (data.msg != '')
                        {
                            $scope.msgs.push(data.msg);
                        }
                        else
                        {
                            $scope.errors.push(data.error);
                        }
                    }).error(function(data, status) { // called asynchronously if an error occurs
// or server returns response with an error status.
                        $scope.errors.push(status);
                    });
                }
            }
        </script>
        <a href='http://devzone.co.in'>Devzone.co.in</a>
    </body>
</html>
 
 
PHP
 
<?php
 
$data = json_decode(file_get_contents("php://input"));
$usrname = mysql_real_escape_string($data->uname);
$upswd = mysql_real_escape_string($data->pswd);
$uemail = mysql_real_escape_string($data->email);
 
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('test', $con);
 
$qry_em = 'select count(*) as cnt from users where email ="' . $uemail . '"';
$qry_res = mysql_query($qry_em);
$res = mysql_fetch_assoc($qry_res);
 
if ($res['cnt'] == 0) {
    $qry = 'INSERT INTO users (name,pass,email) values ("' . $usrname . '","' . $upswd . '","' . $uemail . '")';
    $qry_res = mysql_query($qry);
    if ($qry_res) {
        $arr = array('msg' => "User Created Successfully!!!", 'error' => '');
        $jsn = json_encode($arr);
        print_r($jsn);
    } else {
        $arr = array('msg' => "", 'error' => 'Error In inserting record');
        $jsn = json_encode($arr);
        print_r($jsn);
    }
} else {
    $arr = array('msg' => "", 'error' => 'User Already exists with same email');
    $jsn = json_encode($arr);
    print_r($jsn);
}
?>