Find us on facebook

Nov 25, 2018

PHP + Curl + HTTP POST

This summary is not available. Please click here to view the post.

Tail last few lines

tail -n 100 logfilename

Move laravel models to Models folder

1. Move the files to the Models folder

2. Change the namespace of the models

Change :

namespace App;

to

namespace App\Models;

3. Change the other files

Search for app\User and change

    app/Http/Controllers/Auth/RegisterController.php
    config/auth.php
    config/services.php
    database/factories/ModelFactory.php
    database/factories/UserFactory.php
    All Controllers

And change App/ModelTest to App/Models/ModelTest

4. Run composer dump-autoload

Feb 18, 2018

Install and configure mongo db on Ubuntu

1) Find ubuntu version
lsb_release -a

2) Import the public key used by the package management system
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5

3) Create a list file for MongoDB (16.04 LTS ubuntu)
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list

4) sudo apt-get update

5) Install latest mongodb packages
sudo apt-get install -y mongodb-org

Refference : https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/

Set user and give read write access to db

use admin

db.createUser({
    user: 'test',
    pwd: 'testpassword',
    roles: [{ role: 'readWrite', db:'admin'}]
})


6) Edit your MongoDB config file. On Ubuntu:
sudo vim /etc/mongod.conf

7) open MongoDB to all IPs
#  bindIp: 127.0.0.1  <- comment out this line

8) Find #security: section and add following
security:
  authorization: 'enabled'

Feb 4, 2018

On npm install @angular/cli - error

error command "/usr/bin/nodejs" "/usr/bin/npm" "install" "-g" "angular-cli"
2041 error cwd /var/www/html/angular
2042 error node -v v0.10.25
2043 error npm -v 1.3.10

rm node

/usr/local/lib
/usr/local/include
/usr/local/bin
/usr/bin




sh: 1: node: Permission denied - on angular cli npm install -g @angular/cli

Short fix


Run this as root

npm config set user 0
npm config set unsafe-perm true
npm install -g @angular/cli

Feb 3, 2018

Setup Redis - Ubuntu

sudo apt-get update
sudo apt-get install build-essential (download a compiler with build essential)
sudo apt-get install tcl8.5 (download tcl)
wget http://download.redis.io/releases/redis-stable.tar.gz (Download the latest stable release tarball from Redis.io.)
tar xzf redis-stable.tar.gz
cd redis-stable
make
make test
sudo make install
cd utils
sudo ./install_server.sh (run ubuntu install script)
sudo service redis_6379 start
sudo service redis_6379 stop
redis-cli
To edit config file
sudo nano /etc/redis/6379.conf
un comment bind 127.0.0.1

Error: listen EADDRINUSE - Fix

Check PID using following command
lsof -i tcp:<port>
Then kill the process that runs on port
kill -9 <PID>

Setup a Mosquitto MQTT Server - Ubuntu

adduser mosquitto (Mosquitto wants to run as user mosquitto)
apt-get update
apt-get install build-essential libwrap0-dev libssl-dev libc-ares-dev uuid-dev xsltproc (Install mosquitto dependencies)
cd /home/mosquitto
wget http://mosquitto.org/files/source/mosquitto-1.4.8.tar.gz
tar xvzf mosquitto-1.4.8.tar.gz
cd mosquitto-1.4.8
make
make install


Or Install you can install it in following way

wget http://repo.mosquitto.org/debian/mosquitto-repo.gpg.key
sudo apt-key add mosquitto-repo.gpg.key
cd /etc/apt/sources.list.d/
sudo wget http://repo.mosquitto.org/debian/mosquitto-wheezy.list
sudo apt-get update
sudo apt-get install mosquitto
sudo stop mosquitto
sudo mosquitto_passwd -c /etc/mosquitto/passwd <user_name>(Create new password file)
sudo gedit /etc/mosquitto/mosquitto.conf (Give the location of the password file to the Mosquitto broker config file)
Add following two lines to config file
password_file /etc/mosquitto/passwd
allow_anonymous false (prevent, clients without username and password connecting to the broker)
mosquitto -c /etc/mosquitto/mosquitto.conf (start broker)
mosquitto_sub -h localhost -p 1883 -t myTopic -u <user_name> -P <password> (verify authentication)
mosquitto_sub -t 'greetings/#' (View published messages live)

Node MQTT Simple example

pusher.js
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var redis = require('redis');
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://localhost');

server.listen(8080);
io.on("connection", function (socket) {
    console.log("new client connected");

    // socket connection indicates what mqtt topic to subscribe to in data.topic
    socket.on('subscribe', function (data) {
        console.log('Subscribing to '+data.topic);
        socket.join(data.topic);
        client.subscribe(data.topic);
    });
    // when socket connection publishes a message, forward that message
    // the the mqtt broker
    socket.on('publish', function (data) {
        console.log('Publishing to '+data.topic);
        client.publish(data.topic,data.payload);
    });

   
  
});

// listen to messages coming from the mqtt broker
client.on('message', function (topic, payload, packet) {
    console.log(topic+'='+payload);
    io.sockets.emit('mqtt',{'topic':String(topic),
                            'payload':String(payload)});
});




receiver.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<h1>Real Time</h1>
<style>
body {
    background-color: #666;
    margin: 10px;
}

/*! Light */
#light {
    background-color: #000;
    box-shadow: 0 0 5px rgba(0,0,0, .8);
    overflow: hidden;
    padding: 0 0 4px;
    width: 40px;
}

#light span {
    border-radius: 50px;
    display: block;
    height: 30px;
    margin: 4px auto 0;
    opacity: .5;
    width: 30px;
}

/*! Light colours */
#red    { background-color: red; }
#orange { background-color: orange; }
#green  { background-color: green; }

/*! Active states */
#light span.active    { opacity: 1; }
#light #red.active    { box-shadow: 0 0 10px red; }
#light #orange.active { box-shadow: 0 0 10px orange; }
#light #green.active  { box-shadow: 0 0 10px green; }


#bulb    { background-color: red; }

/*! Active states */
#light span.On    { opacity: 1; }
#light #bulb.On    { box-shadow: 0 0 10px red; }


/*! Toggle button */
button {
    margin-top: 10px;
}

</style>
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script>
  $(document).ready(function() {
        var id_sl;

        $('#btn_sl').on('click', function() {

            var self_sl = $('.active');

            //Check if another element exists after the currently active one otherwise
            //find the parent and start again
            if (self_sl.next().length) {
                id_sl = self_sl.next().attr('id');
            } else {
                id_sl = self_sl.parent().find('span:first').attr('id');
            }

            socket.emit('publish', {topic:"led",payload:id_sl});
        });
       
        $('#btn_chng').on('click', function() {

            var state = $(this).val();           
            socket.emit('publish', {topic:"state",payload:state});

        });

    });
</script>
<script>
  var socket = io.connect('http://localhost:8080');
  socket.on('connect', function () {
    socket.on('mqtt', function (msg) {

      console.log(msg.topic+' '+msg.payload);

      if(msg.topic == 'led'){

        var self = $('.active');
        self.removeClass('active');
        $('#'+msg.payload).addClass('active');
       
      }
      if(msg.topic == 'state'){

        if(msg.payload == 'On'){

          $('#bulb').removeClass('On');
          $('#btn_chng').val('Off');

        } else if(msg.payload == 'Off'){

          $('#bulb').addClass('On');
          $('#btn_chng').val('On');

        }
       
      }
    
     
    });
    socket.emit('subscribe',{topic:'led'});
    socket.emit('subscribe',{topic:'state'});
  });
</script>
</head>

<body>
  <div class='table'>
    <div id="light">
        <span class="active" id="red"></span>
        <span id="orange"></span>
        <span id="green"></span>
        </div>
    <button id="btn_sl">Switch Light</button>
  </div>
  <div class='table'>
   
    <div id="light">
        <span class="On" id="bulb"></span>       
    </div>
    <button id="btn_chng" value="On">Change State</button>
  </div>
</body>

</html>










Node Redis Socket.io PHP Simple example to publish a message

pusher.php

<?php

//Load the Predis autoloader
require("Predis/autoload.php");

//Register all classes
Predis\Autoloader::register();

//Create a redis client to publish event
$redis = new Predis\Client(array(
    "scheme" => "tcp",
    "host" => "127.0.0.1",
    "port" => 6379
));

//Publish the event
$redis->publish("mychannel", "Woooow there !!!");
?>

pusher.js

var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var redis = require('redis');

server.listen(8080);
io.on("connection", function (socket) {
    console.log("new client connected");

    var redisClient = redis.createClient();
    redisClient.subscribe('mychannel');

    redisClient.on("message", function(channel, message) {
      console.log("mew message in queue channel");
      socket.emit("schannel", message);
    });

    socket.on('disconnect', function() {
      redisClient.quit();
    });
  
});


receiver.html

<!doctype html>
<html>
<head>
    <title>Test</title>
</head>
<body>
 <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2" >
              <div id="messages" >ss</div>
            </div>
        </div>
    </div>
  
    <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script src="http://localhost:8080/socket.io/socket.io.js"></script>
    <script>
            var socket = io.connect('http://localhost:8080');
            socket.on("schannel", function(message) {
                $( "#messages" ).append( "<p>"+message+"</p>" );
                console.log("tweet from", message);
                console.log("contents:", message);
            });
    </script>

</body>
</html>

That's all. You are done....

You can monitor redis messages using following command
redis-cli monitor





Feb 1, 2018

SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes (S QL: alter table `users` add unique `users_email_unique`(`email`)) laravel

namespace App\Providers;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }

Jan 31, 2018

Retrieve nearest drivers - query- laravel mysql

$results = \DB::select(DB::raw('SELECT id, ( 3959 * acos( cos( radians(' . $order->delivery_lattitude . ') ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(' . $order->delivery_logitude . ') ) + sin( radians(' . $order->delivery_lattitude . ') ) * sin( radians(lat) ) ) ) AS distance FROM rider_location HAVING distance < ' . $distance . ' ORDER BY distance'));

Laravel permissions for setup project ubuntu

sudo chgrp -R www-data /var/www/html/project

sudo chmod -R 775 /var/www/html/project/storage

serverless setup for cloned project

  • Install node
  • Install serverless (npm install -g serverless)
  • clone the repository
  • cd to repository folder
  • npm install
  • Login to AWS console → go to IAM→ security credentials→create access key
  • serverless config credentials --provider aws --key testkeyforaws --secret secretforaws
  • serverless deploy --aws-profile devProfile(didn't use - may be useful)
  • serverless login – (create github account to access code)
  • serverless invoke -f functionname

Restrict ssh to git

 cat /etc/shells
# /etc/shells: valid login shells
/bin/sh
/bin/dash
/bin/bash
/bin/rbash
/usr/bin/tmux
/usr/bin/screen
 
$ which git-shell
/usr/bin/git-shell
 
$ sudo nano /etc/shells (add  /usr/bin/git-shell)
$ sudo chsh git -s /usr/bin/git-shell

setup git server

su -
sudo useradd git
  === Enter new UNIX password:
  === Retype new UNIX password:
  === passwd: password updated successfully

 sudo apt-get install git
 
 su git
 sudo mkdir git (create git folder on home)
 move id_rsa.pub to /home/git
 mkdir ~/.ssh && chmod 700 ~/.ssh
 touch ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys
 
 cat ~/id_rsa.pub >> ~/.ssh/authorized_keys
 cat ~/.ssh/authorized_keys

 mkdir project.git
 cd project.git
 git init --bare

solve access denied issue to mysql server from remote machine

netstat -l --tcp -n -p


tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      -

sudo nano /etc/mysql/mysql.conf.d and comment "bind  127.0.0.1:3306"
 
netstat -l --tcp -n -p
 
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      17043/apache2

On git push , publish files to live

git init --bare
cd project.git
cd hooks

cat > post-receive

#!/bin/sh
git --work-tree=/var/www/html/project --git-dir=/home/ishara/git/project.git checkout -f

CTRL+D to exit

chmod +x post-receive
 

When deploying files, you need to give permission to /var/www/html/project 
add system user group permission to /var/www/html/project using following command.

chown -R user:group projectfolder
 

In local git repo add remote
 
local .git/config
[remote "live"]
        url = ssh://ishara@111.111.11.11/home/ishara/git/project.git
        fetch = +refs/heads/*:refs/remotes/live/*
[remote "repo"]
        url = git@222.222.22.222:project.git
        fetch = +refs/heads/*:refs/remotes/repo/*

 
push command from local machine
git push live master (deploy live)
git push repo master (deploy to git server repo)
 

LDAP Simple bind in PHP

<?php
$ldaphost = "ldap.xxx.yyy"; 
$ldapport = 389; 

$ds = ldap_connect($ldaphost, $ldapport) or die("Could not connect to $ldaphost"); 
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
if ($ds) { 
 $username = "test"; 
 $upasswd = "password"; 
 $binddn = "cn=admin,dc=xxx,dc=yyy"; 
 $binddnt = "ou=mathematicians,dc=xxx,dc=yyy"; 
 $ldapbind = ldap_bind($ds,$binddn, $upasswd); 

 //check if ldap was sucessfull 
 if ($ldapbind) {
    $filter = "(uniqueMember=*)";
    $result = ldap_search($ds, $binddnt, $filter) or exit("Unable to search LDAP server");
 $entries = ldap_get_entries($ds, $result);
 var_dump($entries);
 } else {
    echo "LDAP bind failed...";
 }
}


?>