Percobaan cloud4pi dengan PHP

<!--?php
// A sample PHP Script to POST data using cURL
// Data in JSON format

$json= '&#91;{"name":"Temperature","type":"numeric"},{"name":"LEDOn","type":"bool"}&#93;';
$arr=json_decode($json, false);

echo '

<pre-->';
print_r($arr);
echo '


';

$employee_object = new stdClass;
$employee_object-&gt;name = "Temperature";
$employee_object-&gt;type = "numeric";
$employee_object1 = new stdClass;
$employee_object1-&gt;name = "LEDOn";
$employee_object1-&gt;type = "bool"; 

$data = array
  (
  $employee_object,
  $employee_object1
);

$payload = json_encode($data);
echo "==&gt;".$payload;

$token = '2HSmdfzsEAXB3puVUTi6ZoirV';

// Prepare new cURL resource
$ch = curl_init('https://cloud4rpi.io/api/devices/'.$token.'/config');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

// Set HTTP Header for POST request
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($payload))
);

// Submit the POST request
$result = curl_exec($ch);

echo $result;
// Close cURL session handle
curl_close($ch);

$json = '{"ts":"date","payload":{"Temperature":24,"LEDOn":true}}';
$arr=json_decode($json, true);

echo '









<pre>';
print_r($arr);
echo '</pre>
';

$dt = date(DateTime::ISO8601);

$carss = array
(
"ts"=&gt;$dt,
"payload"=&gt;array("Temperature"=&gt;22,"LEDOn"=&gt;0)
);

$payload = json_encode($carss);
echo "==&gt;".$payload;

$token = '2HSmdfzsEAXB3puVUTi6ZoirV';

// Prepare new cURL resource
$ch = curl_init('https://cloud4rpi.io/api/devices/'.$token.'/data');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

// Set HTTP Header for POST request
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($payload))
);

// Submit the POST request
$result = curl_exec($ch);

echo $result;
// Close cURL session handle
curl_close($ch);

?&gt;

Menerima paket UDP dan meneruskan ke URL atau website

Gunakan script phyton ini:

import socket, urllib2

UDP_IP = "127.0.0.1"
UDP_PORT = 50000

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
#sock.bind((UDP_IP, UDP_PORT))
sock.bind(("", UDP_PORT)) #bind, receive from any addresss

while True:
 data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
 print "received message:", data
 stringdata = str(data)
 if stringdata[0] == "+":
 value = stringdata[2]
 karakter = ord(loket)
 karakter = karakter + 1;
 value = chr(karakter)
 url = "http://localhost/getUDP.php?var="+value
 print "url:", url
 response = urllib2.urlopen(url)
 headers = response.info()
 data = response.read()
 print data

Autoplay Video pada HTML

bagian html, isikan:

<html>
<head>Video playlist</head>
<body>

<video autoplay id="myVideo" width="480" height="326" style="object-fit: fill;">
Browser tidak mendukung video
</video>

<script src='video/list.php'></script>

<script type="text/javascript">
var videoSource = new Array();
for(var x=0; x<=files.length; x++){
    videoSource[x]='http://localhost/antrian/video/'+files[x]+'.mp4';
}

var videoCount = videoSource.length;

document.getElementById("myVideo").setAttribute("src",videoSource[0]);

function videoPlay(videoNum)
{
    document.getElementById("myVideo").setAttribute("src",videoSource[videoNum]);
    document.getElementById("myVideo").load();
    document.getElementById("myVideo").play();
}

document.getElementById('myVideo').addEventListener('ended',myHandler,false);

var i=0;
function myHandler() {
    i++;
    if(i == (videoCount-1)){
        i = 0;
        videoPlay(i);
    }else{
        videoPlay(i);
    }
}

</body>
</html>

lalu buat file list.php pada direktory video, dengan mengisikan script berikut:

var files = <?php $out = array();
foreach (glob('*.mp4') as $filename) {
$p = pathinfo($filename);
$out[] = $p['filename'];
}
echo json_encode($out); ?>;

selanjutnya taruh file video dengan format mp4 ke direktori video

Koneksi MySQL dengan C++ pada Linux

Pasang libmysql++ dengan cara

sudo apt-get install libmysql++ libmysql++-dev

tambahkan kode berikut pada file test.cpp

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 
#include <string.h>


#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h>  


#include <mysql.h>


using namespace std;
using namespace cgicc;


#define SERVER "localhost"
#define USER "root"
#define PASSWORD "winda1984"
#define DATABASE "user"


int main()
{


   Cgicc formData;
   
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Using GET Methods</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";


   form_iterator t = formData.getElement("t");  
   if( !t->isEmpty() && t != (*formData).end()) {  
      cout << "Table: " << **t << endl;  
 
      MYSQL *connect;
      connect=mysql_init(NULL);
      if (!connect)
      {
         cout<<"Koneksi MySQL gagal";
         return 1;
      }
      connect=mysql_real_connect
         (connect, "localhost", "user", "password" , "database", 0, NULL, 0);
      if (connect)
      {
         cout<<"connection Succeeded\n";
      }else{
         cout<<"connection failed\n";
      }

      MYSQL_RES *res_set;
      MYSQL_ROW row;
      string str =  "select * from " + **t;

      mysql_query (connect,str.data());
      unsigned int i =0;
      res_set = mysql_store_result(connect);
      unsigned int numrows = mysql_num_rows(res_set);
      while (((row= mysql_fetch_row(res_set)) !=NULL ))
      { 
         cout << "| \t" <<  row[i] <<  "\t |"<< endl;
      }
      mysql_close (connect);
   } else {
      cout << "No text entered for table" << endl;  
   }
   
   cout << "<br/>\n";
   cout << "</body>\n";
   cout << "</html>\n";

   return 0;
}

compile dengan perintah

g++ -o test test.cpp -L/usr/include/mysql -lmysqlclient -lcgicc -I/usr/include/mysql

sumber: https://sandeepghai.wordpress.com/2011/08/07/linking-of-mysql-database-with-c-on-linux-machine/

Mengaktifkan modul mod_rewrite pada Apache2

Pasang symbolic link di /etc/apache2/mods-enabled untuk file rewrite.load
cd /etc/apache2/mods-enabled
sudo ln -s ../mods-available/rewrite.load
atau cara cepat dengan aktifkan melalui
sudo a2enmod rewrite
buat file konfigurasi rewrite
sudo leafpad /etc/apache2/conf-available/rewrite.conf
isikan dengan
<IfModule mod_rewrite.c>
<Directory /var/www/html>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
</IfModule>
buat symbolic link di /etc/apache2/conf-enabled
cd /etc/apache2/conf-enabled
sudo ln -s ../conf-available/rewrite.conf
jalankan ulang atau set baca ulang konfigurasi apache2
sudo service apache2 reload

buat file .htaccess

sudo nano /var/www/html/.htaccess

isikan contoh rule

<IfModule mod_rewrite.c>
RewriteEngine on

RewriteRule ^beranda$ main.php?page=beranda [L]

ErrorDocument 404 http://localhost/error-404.html
ErrorDocument 403 http://localhost/error-403.html

Options All -Indexes
</IfModule>

Dari rule di atas, setiap mengarah ke http://localhost/beranda maka akan membuka http://localhost/main.php?page=beranda dan jika ada error, maka akan mengarah ke halaman error yang ditunjuk

^beranda$ adalah kalimat yang akan dicocokan.

  • ^ menyatakan awal dari URL, dimana localhost/ diabaikan.
  • $ menyatakan akhir dari URL
  • beranda string yang dicocokkan

main.php?page=beranda adalah tujuan dari file sesungguhnya.

[NC] ignores capitalization dan [L] menyatakan lowercase

set permision dari .htaccess ke mode read only

sudo chmod 644 /var/www/html/.htaccess

CGI menggunakan C++

sudo apt-get install m4 autoconf perl
cd ~
mkdir cgicc
wget ftp://ftp.gnu.org/gnu/cgicc/cgicc-3.2.16.tar.gz
tar xvf cgicc-3.2.16.tar.gz
cd cgicc-3.2.16
./configure --prefix=/usr
make
sudo make install
cd /usr/lib
ls libcgi*

source: http://derekmolloy.ie/beaglebone-cgicc/

sudo apt-get install libmysql++ libmysql++-dev

source: https://sandeepghai.wordpress.com/2011/08/07/linking-of-mysql-database-with-c-on-linux-machine/

buat file cgi dengan nama test.cpp  dan isikan kode berikut:

#include <iostream>
#include <vector> 
#include <string> 
#include <stdio.h> 
#include <stdlib.h>

#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h>

using namespace std;
using namespace cgicc;

int main () {
Cgicc formData;

cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Menggunakan GET</title>\n";
cout << "</head>\n";
cout << "<body>\n";

form_iterator nama = formData.getElement("nama"); 
if( !nama->isEmpty() && nama != (*formData).end()) { 
cout << "Halo " << **nama << endl; 
} else {
cout << "Nama tidak diisikan" << endl; 
}

cout << "<br/>\n";
cout << "</body>\n";
cout << "</html>\n";

return 0;
}

lalu compile dengan perintah

g++ -o test test.cpp -lcgicc

coba buka dengan

test?nama=latiful

sumber: https://www.tutorialspoint.com/cplusplus/cpp_web_programming.htm

Mengaktifkan CGI pada Apache

Konfigurasi apache pada linux ada di direktori /etc/apache2. Konfigurasi CGI dapat ditemukan di /etc/apache2/conf-available/serve-cgi-bin.conf yang merupakan symbolic link dari /etc/apache2/conf-enabled/serve-cgi-bin.conf. Terdapat bagian yang memetakan /cgi-bin pada URL ke direktori /usr/lib/cgi-bin/ dan memungkinkan untuk mengeksekusi CGI pada direktori ini.

Ganti bagian /cgi-bin/ menjadi path URL untuk CGI dan ganti  /usr/lib/cgi-bin untuk disesuaikan pada direktori tempat menyimpan script CGI:

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">

Modul yang sudah terpasang pada Apache dapat ditemukan di direktori /etc/apache2/mods-available. Script  untuk menjalankan CGI ada di script pada file cgi.load

Untuk mengaktifkan modul ini, buat symbolic link pada /etc/apache2/mods-enabled, karena modul CGI secara default tidak aktif.

$ cd /etc/apache2/mods-enabled
$ sudo ln -s ../mods-available/cgi.load

Load kembali konfigurasi Apache dengan:

$ sudo service apache2 reload

source: https://code-maven.com/set-up-cgi-with-apache

Aktifkan Webserver pada Raspberry

Pemasangan Apache

sudo apt update
sudo apt upgrade
sudo apt update
sudo apt install apache2
sudo chown -R pi:www-data /var/www/html/
sudo chmod -R 770 /var/www/html/

Cek hasilnya di localhost (127.0.0.1)

 

Pemasangan PHP

sudo apt install php php-mbstring
sudo rm /var/www/html/index.html
echo "<?php phpinfo ();?>" > /var/www/html/index.php

Pemasangan MySQL

sudo apt install mysql-server php-mysql
sudo mysql --user=root

Buat user baru dengan perintah (ganti password dengan kata kunci yang baru):

DROP USER 'root'@'localhost';
CREATE USER 'root'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost'
CREATE USER 'phpmyadmin'@'localhost' IDENTIFIED BY 'password';

Selanjutnya untuk masuk ke client gunakan mysql --user=root --password lalu isikan kata kunci yang baru.

Pemasangan PHPMyAdmin

sudo apt install phpmyadmin

Saat pada proses dbconfig-common ada pertanyaan untuk setting database. Cukup pilih <Tidak> karena telah dikonfigurasi saat pemasangan MySQL. Isikan kata kunci sesuai saat setting MySQL. Buka alamat localhost diikuti phpmyadmin, contoh:  http://127.0.0.1/phpmyadmin

Kadang phpmyadmin tidak berada pada /var/www/html/ maka perlu buat link. Misalnya:

sudo ln -s /usr/share/phpmyadmin /var/www/html/phpmyadmin

Setelah berhasil masuk ke phpmyadmin, buat data default dan cek warning dan errornya.

Enkripsi: Rfc2898DeriveBytes di C# dan hash_pbkdf2 di php

C#

    public string DecryptText(string input, string password)
    {
        String[] tempAry = input.Split('-');

        byte[] bytesToBeDecrypted = new byte[tempAry.Length];
        for (int i = 0; i < tempAry.Length; i++)
            bytesToBeDecrypted[i] = Convert.ToByte(tempAry[i], 16);

        byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
        passwordBytes = SHA256.Create().ComputeHash(passwordBytes);

        byte[] bytesDecrypted = Decrypt(bytesToBeDecrypted, passwordBytes);

        return Encoding.UTF8.GetString(bytesDecrypted);

    }
    public byte[] Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
    {
        byte[] decryptedBytes = null;
        byte[] saltBytes = new byte[] { 5, 7, 3, 5, 2, 6, 7, 8 };
        using (MemoryStream ms = new MemoryStream())
        {
            using (RijndaelManaged AES = new RijndaelManaged())
            {
                AES.KeySize = 256;
                AES.BlockSize = 128;
                var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
                AES.Key = key.GetBytes(AES.KeySize / 8);
                AES.IV = key.GetBytes(AES.BlockSize / 8);
                AES.Mode = CipherMode.CBC;
                using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), 
                                                 CryptoStreamMode.Write))
                {
                    cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                    cs.Close();
                }
                decryptedBytes = ms.ToArray();
            }
        }
        return decryptedBytes;
    }

PHP

function DecryptText ($input, $password){
    $tempAry = str_replace("-", "", $input);

    $bytesToBeDecryptedbin = hex2bin($tempAry); 
    $bytesToBeDecrypted = unpack('C*', $bytesToBeDecryptedbin);
    $bytesToBeDecryptedbinstring = "";
    for($i=0;$i<count($bytesToBeDecrypted);$i++){
        $bytesToBeDecryptedbinstring=$bytesToBeDecryptedbinstring.chr($bytesToBeDecrypted[$i+1]);
    }


    $passwordhash = hash('sha256', $password); 
    $passwordbin = hex2bin($passwordhash); 
    $passwordBytes = unpack('C*', $passwordbin);
    $passwordBytesstring = "";
    for($i=0;$i<count($passwordBytes);$i++){
        $passwordBytesstring=$passwordBytesstring.chr($passwordBytes[$i+1]);
    }

    $saltBytes = array(5,7,3,5,2,6,7,8);
    $saltBytesstring = "";
    for($i=0;$i<count($saltBytes);$i++){
        $saltBytesstring=$saltBytesstring.chr($saltBytes[$i]);
    }
    
    $keySize = 256; $blockSize = 128;

    $key = hash_pbkdf2("sha1", $passwordBytesstring, $saltBytesstring, 1000, 48, true); 
    $aeskey = (  substr($key,0,$keySize/8) );
    $aesiv =  (  substr($key,$keySize/8,$blockSize/8) );

    $decrypted = mcrypt_decrypt
          (
              MCRYPT_RIJNDAEL_128,
              $aeskey,
              $bytesToBeDecryptedbinstring,
              MCRYPT_MODE_CBC,
              $aesiv
           );        

    $result = "";
    for($i=0;$i<strlen($decrypted);$i++){
        if($decrypted[$i]==chr(7)) break;
        $result = $result . $decrypted[$i];
    }
           
    $decryptedarr = unpack('C*', $result);
    return $result;
}

sumber:

http://stackoverflow.com/questions/43011612/porting-c-sharp-rfc2898derivebytes-in-php-using-hash-pbkdf2