Printer POS USB menggunakan PHP

<?php  
$tmpdir = sys_get_temp_dir();   # ambil direktori temporary untuk simpan file.
$file =  tempnam($tmpdir, 'ctk');  # nama file temporary yang akan dicetak (Windows, samba)

$handle = fopen($file, 'w');


//Printer parameter (ESC POS Command)
$initialized = chr(27).chr(64);

$justify = Chr(27) . Chr(97);
$left = Chr(0); $center = Chr(1);$right = Chr(2);

$fontwidth = Chr(27).Chr(87);
$doublewidth = Chr(1); $normalwidth = Chr(0);

$LF = Chr(10);

//Start making data
$Data  = $initialized;
$Data .= $fontwidth.$doublewidth;
$Data .= $justify.$center;
$Data .= "NAMA TOKO"."\n";
$Data .= $fontwidth.$normalwidth;
$Data .= "Alamat Toko"."\n";
$Data .= $LF.$LF;

//Write data to temporary file
fwrite($handle, $Data);
fclose($handle);

//WIN: send temporary file to nerwork shared printer (share your printer)
//LINUX: send data directly to device
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'){ //Win
    copy($file, "//localhost/POS-58");  # Shared Printer as POS-58
}else if (strtoupper(substr(PHP_OS, 0, 3)) === 'LIN'){ //Linux    
    $device = "/dev/usb/lp0";           # Print at lp0, find it using lsusb! Use udev for managing user access
    if (is_writable($device)) {
        $fp =fopen($device, "w");
        if($fp) {
            fwrite($fp, $Data);
            fclose($fp);
        }
    }
}

unlink($file);
//echo $Data;

?>

Cara mencetak ke printer POS menggunakan PHP. Skrip ini mencontohkan jika menggunakan Windows maupun Linux.

Untuk menggunakan Windows maupun Linux, printer dibuat menjadi akses bersama (shared printer) terlebih dahulu lalu beri nama, misalnya: POS-58. Pastikan bisa diakses di //ALAMAT_IP/NAMA_PRINTER. Untuk skrip ini, menggunakan //localhost/POS-58 Untuk di Windows, buka di Control Panel, pastikan printer yang di-share sudah tersedia dan online.

Sedangkan jika menggunakan Linux, cari nama device dengan perintah:

ls /dev/usb

alamat device printer akan diawali dengan lpx, dimana x bisa 0,1,2 atau angka yang lain. Bagaimana bisa memastikan mana alamat device yang benar? gunakan perintah berikut:

echo "Test Printer" >> /dev/usb/lp0 

Jika printer bisa mencetak, berarti alamat printer adalah benar, yaitu /dev/usb/lp0 jika salah ganti angka 0 dengan angka 1 atau 2 atau angka lain hingga printer bisa mencetak. Pada skrip ini, alamat device perinter adalah /dev/usb/lp0

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

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

 

Contoh bridging BPJS dengan PHP (Contoh Formulir request dan response)

Berikut contoh bridging BPJS dengan PHP, mencakup:

Referensi
Kode atau Nama Diagnosa
Pencarian data poli
Fasilitas Kesehatan

Kepesertaan
Berdasar NIK
Berdasar No. Kartu

SEP
Detail SEP Peserta
Monitoring Verifikasi Klaim
Data Kunjungan Peserta
Data Riwayat Pelayanan Peserta
Integrasi SEP dengan Inacbg 4.1

Pada contoh ini terdiri dari 2 file, yaitu getform.php sebagai contoh formulir dan getresponse.php sebagai skrip untuk request ke server BPJS

File form (contoh formulir): getform.php

<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<script>
  $( function() {
      
    $( "#tglMasuk" ).datepicker({
        dateFormat: "yy-mm-dd"
    });
    $( "#tglKeluar" ).datepicker({
        dateFormat: "yy-mm-dd"
    });
    
  });
</script>
  
<script>

$(document).ready(function(){

    
    $("#DIAG").click(function(){
        var parameter = $('#paramDIAG').val();
        if (parameter==""){alert ("Diagnosa harus diisi"); return;}
        $("#div1").load("getresponse.php?parameter="+parameter+"&cat=/diagnosa/ref/diagnosa/&arr=1", 
        function(responseTxt, statusTxt, xhr){
        if(statusTxt == "error")
            alert("Error: " + xhr.status + ": " + xhr.statusText);
        });
    });

     $("#POLI").click(function(){
        var parameter = '';
        $("#div1").load("getresponse.php?parameter="+parameter+"&cat=/poli/ref/poli&arr=1", 
        function(responseTxt, statusTxt, xhr){
        if(statusTxt == "error")
            alert("Error: " + xhr.status + ": " + xhr.statusText);
        });
    });

    $("#FASKES").click(function(){
        var parameter = $('#paramFASKES').val();
        var mulai = $('#mulaiFASKES').val();
        var limit = $('#limitFASKES').val();
        var uri = "&start="+mulai+"&limit="+limit;
        var url="getresponse.php?parameter="+parameter+encodeURIComponent(uri)+"&arr=1&cat=/provider/ref/provider/query%3Fnama=";  //tanda ? --> url encode mjd %3F
        if (parameter==""){alert ("FASKES harus diisi"); return;}
        $("#div1").load(url, 
        function(responseTxt, statusTxt, xhr){
        if(statusTxt == "error")
            alert("Error: " + xhr.status + ": " + xhr.statusText);
        });
    });


    $("#NIK").click(function(){
        var parameter = $('#paramNIK').val();
        if (parameter==""){alert ("NIK harus diisi"); return;}
        $("#div1").load("getresponse.php?parameter="+parameter+"&cat=/Peserta/Peserta/nik/&arr=1", 
        function(responseTxt, statusTxt, xhr){
       if(statusTxt == "error")
            alert("Error: " + xhr.status + ": " + xhr.statusText);
        });
    });
    
    $("#NO").click(function(){
        var parameter = $('#paramNO').val();
        if (parameter==""){alert ("No. Kartu harus diisi"); return;}
        $("#div1").load("getresponse.php?parameter="+parameter+"&cat=/Peserta/Peserta/&arr=1", 
        function(responseTxt, statusTxt, xhr){
        if(statusTxt == "error")
            alert("Error: " + xhr.status + ": " + xhr.statusText);
        });
    });    
    
     $("#DETSEP").click(function(){
        var parameter = $('#paramDETSEP').val();
        if (parameter==""){alert ("SEP harus diisi"); return;}
        $("#div1").load("getresponse.php?parameter="+parameter+"&cat=/SEP/&arr=1", 
        function(responseTxt, statusTxt, xhr){
        if(statusTxt == "error")
            alert("Error: " + xhr.status + ": " + xhr.statusText);
        });
    });
    
    
    
     $("#VERSEP").click(function(){
        var parameter = "tglMasuk/" + $('#tglMasuk').val() + "/tglKeluar/" + $('#tglKeluar').val() + "/KlsRawat/" + $('#kelas').val() + "/Kasus/" + $('#kasus').val() + "/Cari/" + $('#cari').val() + "/status/" + $('#status').val();    
        if (parameter==""){alert ("SEP harus diisi"); return;}
        $("#div1").load("getresponse.php?parameter="+parameter+"&cat=/sep/integrated/Kunjungan/&arr=1", 
        function(responseTxt, statusTxt, xhr){
        if(statusTxt == "error")
            alert("Error: " + xhr.status + ": " + xhr.statusText);
        });
    });
    
    
   $("#SEPKUN").click(function(){
        var parameter = $('#paramSEPKUN').val();
        if (parameter==""){alert ("SEP harus diisi"); return;}
        $("#div1").load("getresponse.php?parameter="+parameter+"&cat=/sep/integrated/Kunjungan/sep/&arr=1", 
        function(responseTxt, statusTxt, xhr){
        if(statusTxt == "error")
            alert("Error: " + xhr.status + ": " + xhr.statusText);
        });
    });
    
   $("#NOR").click(function(){
        var parameter = $('#paramNOR').val();
        if (parameter==""){alert ("No Kartu harus diisi"); return;}
        $("#div1").load("getresponse.php?parameter="+parameter+"&cat=/sep/peserta/&arr=1", 
        function(responseTxt, statusTxt, xhr){
        if(statusTxt == "error")
            alert("Error: " + xhr.status + ": " + xhr.statusText);
        });
    });
    
   $("#CBG").click(function(){
        var parameter = $('#paramCBG').val();
        if (parameter==""){alert ("SEP harus diisi"); return;}
        $("#div1").load("getresponse.php?parameter="+parameter+"&cat=/sep/cbg/&arr=1", 
        function(responseTxt, statusTxt, xhr){
        if(statusTxt == "error")
            alert("Error: " + xhr.status + ": " + xhr.statusText);
        });
        
    });
    
    $("button").click(function(){
        $("html, body").animate({ scrollTop: 0 }, "slow");
    });

    
});
</script>
</head>
<body>
<div id="div1"><h2>Hasil akan tampil disini</h2></div>
<hr />

<h2> Referensi</h2>
<h3> Diagnosa</h3>
<p> Kode atau Nama Diagnosa: <input type="text" id="paramDIAG"  value=""/>
<button id="DIAG">Kirim</button></p>

<h3> Poli</h3>
<p> Pencarian data poli: 
<button id="POLI">Kirim</button></p>

<h3> Fasilitas Kesehatan</h3>
<p> Nama atau kode faskes: <input type="text" id="paramFASKES"  value=""/>
<button id="FASKES">Kirim</button><br />
 Mulai: <input type="text" id="mulaiFASKES"  value="0"/><br />
 Limit: <input type="text" id="limitFASKES"  value="7"/>
</p>

<hr />

<h2> Kepesertaan </h2>
<h3> Berdasar NIK </h3>
<p> NIK: <input type="text" id="paramNIK"  value=""/>
<button id="NIK">Kirim</button></p>

<h3> Berdasar No. Kartu </h3>
<p> No.Kartu BPJS: <input type="text" id="paramNO"  value=""/>
<button id="NO">Kirim</button></p>

<hr />
<h2> SEP </h2>

<h3> Detail SEP Peserta </h3>
<p> No.SEP: <input type="text" id="paramDETSEP"  value=""/>
<button id="DETSEP">Kirim</button></p>

<h3> Monitoring Verifikasi Klaim </h3>
<p> 
Tanggal Masuk: <input type="text" id="tglMasuk"  value=""/><br />
Tanggal Keluar: <input type="text" id="tglKeluar"  value=""/><br />
Kelas rawat: <select id="kelas" required>
   <option selected="selected" value="">Pilih</option>
  <option value="1">Kelas 1</option>
  <option value="2">Kelas 2</option>
  <option value="3">Kelas 3</option>
</select><br />
JnsPelayanan : <select id="kasus" required>
   <option selected="selected" value="">Pilih</option>
  <option value="1">Rawat inap</option>
  <option value="2">Rawat jalan</option>
</select><br />
Cari berdasar : <select id="cari" required>
   <option selected="selected" value="">Pilih</option>
  <option value="0">Tanggal masuk</option>
  <option value="1">Tanggal keluar</option>
</select><br />
Status  : <select id="status" required>
   <option selected="selected" value="">Pilih</option>
  <option value="00">Klaim Baru</option>
  <option value="10">Klaim Terima CBG</option>
  <option value="21">Klaim Layak</option>
  <option value="22">Klaim Tidak Layak</option>
  <option value="23">Klaim Pending</option>
  <option value="30">Terverifikasi</option>
  <option value="40">Proses Cabang</option>
</select><br />
<button id="VERSEP">Kirim</button><br />
</p>

<h3> Data Kunjungan Peserta </h3>
<p> Nomor SEP: <input type="text" id="paramSEPKUN"  value=""/>
<button id="SEPKUN">Kirim</button></p>

<h3> Data Riwayat Pelayanan Peserta </h3>
<p> No.Kartu BPJS: <input type="text" id="paramNOR"  value=""/>
<button id="NOR">Kirim</button></p>

<h3> Integrasi SEP dengan Inacbg 4.1 </h3>
<p> Nomor SEP: <input type="text" id="paramCBG"  value=""/>
<button id="CBG">Kirim</button></p>

</body>
</html>

File response: getresponse.php

<?php

if(!isset($_GET["parameter"])) exit(0);
if(!isset($_GET["cat"])) exit(0);
$printarr=false;
if(isset($_GET["arr"])) $printarr=true;
$extraparam="";
if(isset($_GET["extraparam"])) $extraparam=$_GET["extraparam"];

$parameter = $_GET["parameter"];
$cat = $_GET["cat"];

$dataid    = "1234"; //Ganti dengan consumerID dari BPJS
$secretKey = "5678"; //Ganti dengan consumerSecret dari BPJS
$localIP   = "dvlp.bpjs-kesehatan.go.id";
$port      = 8081; //port url
$url       = "http://".$localIP.":".$port."/devwslokalrest".$cat.$parameter; //Lihat katalog, jangan sertakan port

date_default_timezone_set('UTC');
$tStamp = strval(time()-strtotime('1970-01-01 00:00:00'));
$signature = hash_hmac('sha256', $dataid."&".$tStamp, $secretKey, true);
$encodedSignature = base64_encode($signature);
$urlencodedSignature = urlencode($encodedSignature);

/*
echo "X-cons-id: " .$dataid ."<br>";
echo "X-timestamp:" .$tStamp ."<br>";
echo "X-signature: " .$encodedSignature."<br>";
*/

$opts = array(
 'http'=>array(
 'method'=>"GET",
 'header'=>"Host: api.asterix.co.id\r\n".
 "Connection: close\r\n".
 "X-timestamp: ".$tStamp."\r\n".
 "X-signature: ".$encodedSignature."\r\n".
 "User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64)\r\n".
 "X-cons-id: ".$dataid."\r\n".
 "Accept: application/json\r\n"
 )
);

$context = stream_context_create($opts);
$url=$url.$extraparam;
$result = file_get_contents($url, false, $context);

//echo "<br>Respon:";
if ($result === false) 
{ 
 echo "Tidak dapat menyambung ke server"; 
} else { 
 echo $result;
 if($printarr==true){
    echo "<pre>";
    print_r(json_decode($result, true)); 
    echo "</pre>";

    /*
    //contoh penggunaan array untuk menampilkan peserta
    $resultarr = json_decode($result, true);
    echo "Nama :". $resultarr['response']['peserta']['nama'] ."<br />";
    echo "Nik  :". $resultarr['response']['peserta']['nik'] ."<br />";
    echo "Lahir:". date("d-m-Y", strtotime($resultarr['response']['peserta']['tglLahir'])) ."<br />";
    echo "Usia :". $resultarr['response']['peserta']['umur']['umurSekarang'] ."<br />";
    echo "#Krtu:". $resultarr['response']['peserta']['noKartu'] ."<br />";
    echo "Sex  :". $resultarr['response']['peserta']['sex'] ."<br />";
    */
 }
}

?>

 

 

Contoh bridging BPJS dengan PHP (Update SEP)

<?php

$dataid = "1234"; //Ganti dengan consumerID dari BPJS
$secretKey = "5678"; //Ganti dengan consumerSecret dari BPJS
$localIP = "dvlp.bpjs-kesehatan.go.id";
$url = "http://".$localIP."/devwslokalrest/SEP/update"; //Lihat katalog, jangan sertakan port
$port = 8081; //port url

date_default_timezone_set('UTC');
date_default_timezone_set('Asia/Jakarta');

$tStamp = strval(time() - strtotime('1970-01-01 00:00:00'));
$signature = hash_hmac('sha256', $dataid . "&" . $tStamp, $secretKey, true);
$encodedSignature = base64_encode($signature);
$urlencodedSignature = urlencode($encodedSignature);

echo "X-cons-id: " . $dataid . "<br>";
echo "X-timestamp:" . $tStamp . "<br>";
echo "X-signature: " . $encodedSignature . "<br>";

function post_request($url, $port, $dataid, $tStamp, $encodedSignature, $data, $referer = '')
{
 
 //-Convert the data array into URL Parameters like a=b&foo=bar etc.
 //$data = http_build_query($data);
 
 // parse the given URL
 $url = parse_url($url);
 
 if ($url['scheme'] != 'http') {
 die('Error: Only HTTP request are supported !');
 }
 
 // extract host and path:
 $host = $url['host'];
 $path = $url['path'];
 
 // open a socket connection on port 80 - timeout: 50 sec
 $fp = fsockopen($host, $port, $errno, $errstr, 50);
 
 if ($fp) {
 
 // send the request headers:
 fputs($fp, "PUT $path HTTP/1.1\r\n");
 fputs($fp, "Host: $host\r\n");
 
 if ($referer != '')
 fputs($fp, "Referer: $referer\r\n");
 
 fputs($fp, "x-cons-id: " . $dataid . "\r\n");
 fputs($fp, "x-timestamp: " . $tStamp . "\r\n");
 fputs($fp, "x-signature: " . $encodedSignature . "\r\n");
 fputs($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
 fputs($fp, "Content-length: " . strlen($data) . "\r\n");
 fputs($fp, "Connection: close\r\n\r\n");
 fputs($fp, $data);
 
 $result = '';
 while (!feof($fp)) {
 // receive the results of the request, 128 char
 $result .= fgets($fp, 128);
 }
 } else {
 return array(
 'status' => 'err',
 'error' => "$errstr ($errno)"
 );
 }
 
 // close the socket connection:
 fclose($fp);
 
 // split the result header from the content
 $result = explode("\r\n\r\n", $result, 2);
 
 $header = isset($result[0]) ? $result[0] : '';
 $content = isset($result[1]) ? $result[1] : '';
 
 // return as structured array:
 return array(
 'status' => 'ok',
 'header' => $header,
 'content' => $content
 );
 
}


$databpjs = '{
 "request":
 {
 "t_sep":
 {
 "noSep":"0301R00105160000579",
 "noKartu":"0000015223579",
 "tglSep":"2016-06-12 09:00:00",
 "tglRujukan":"2016-06-12 09:00:00",
 "noRujukan":"00009",
 "ppkRujukan":"00010009",
 "ppkPelayanan":"0301R009",
 "jnsPelayanan":"2",
 "catatan":"test",
 "diagAwal":"A00.1",
 "poliTujuan":"INT",
 "klsRawat":"3",
 "lakaLantas":"2",
 "lokasiLaka":"Banyumas",
 "user":"RS",
 "noMr":"001"
 }
 }
 }';

$data = array(
 'Data' => $databpjs
);


$result = post_request($url, $port, $dataid, $tStamp, $encodedSignature, $databpjs, $referer = '');
if ($result['status'] == 'ok') {
 // Print headers
 echo $result['header'];
 
 echo '<hr />';
 
 //mengubah "re d sponse" menjadi "response"
 $resultstr = str_replace("re d sponse", "response", trim(preg_replace('/\s\s+/', ' ', $result['content'])));

 //mengubah format ke JSON yang valid
 $pos = strpos($resultstr, "{");
 if ($pos === false) 
 $pos = 0;
 $rpos = strrpos($resultstr, "}");
 if ($rpos === false) 
 $rpos = strlen($resultstr);
 $resultstr = substr($resultstr,$pos,$rpos-$pos+1);
 
 // print the result of the whole request:
 echo "<pre>";
 echo $resultstr;
 echo "</pre>";
 
} else {
 echo 'A error occured: ' . $result['error'];
}

?>

Koneksi PHP – Serial

Koneksi php ke serialport dengan menggunakan php_dio pada sistem operasi Windows. Caranya adalah dengan menyalin file dll ke subforder ext pada folder php. Edit  file php.ini dengan menambahkan

extension = php_dio.dll (pada windows)

Hentikan (stop) server apache dan jalankan ulang.

Buat sketch arduino untuk menyalakan lampu jika serial menerima huruf w dan mematikan lampu jika serial menerima huruf s, dengan kode berikut:

void setup() {
pinMode(13,OUTPUT);
Serial.begin(9600);
}

void loop() {
if (Serial.available()) {
char inChar = (char)Serial.read();
if (inChar == 'w') {
digitalWrite(13,HIGH);
}
if (inChar == 's') {
digitalWrite(13,LOW);
}
}
}

Buat file serial.php pada forder httdoc dengan kode berikut :

<?php

//ganti com31 dengan alamat port yang digunakan
exec('mode com31: baud=9600 data=8 stop=1 parity=n xon=on');

//ganti COM31 dengan alamat port yang digunakan
$fd = dio_open('\\\\.\COM31', O_RDWR);

sleep(2);
if(isset($_GET['lampu']))
$data = dio_write($fd, $_GET['lampu']);

?>

Ganti alamat port yang digunakan untuk koneksi. Coba dengan membuka firefox atau browser lain dengan alamat http://IPKOMPUTER/serial.php?lampu=w maka lampu menyala. Jika dibuka alamat http://IPKOMPUTER/serial.php?lampu=s maka lampu mati.

Contoh bridging BPJS dengan PHP (Registrasi SEP)

<?php

$dataid    = "1234"; //Ganti dengan consumerID dari BPJS
$secretKey = "1234"; //Ganti dengan consumerSecret dari BPJS
$localIP   = "192.168.0.1";
$url       = "http://".$localIP."/devWSLokalRest/SEP/sep"; //Lihat katalog, jangan sertakan port
$port      = 8081; //port url

date_default_timezone_set('UTC');
$tStamp              = strval(time() - strtotime('1970-01-01 00:00:00'));
$signature           = hash_hmac('sha256', $dataid . "&" . $tStamp, $secretKey, true);
$encodedSignature    = base64_encode($signature);
$urlencodedSignature = urlencode($encodedSignature);

echo "X-cons-id: " . $dataid . "<br>";
echo "X-timestamp:" . $tStamp . "<br>";
echo "X-signature: " . $encodedSignature . "<br>";

function post_request($url, $port, $dataid, $tStamp, $encodedSignature, $data, $referer = '')
{
    
    //-Convert the data array into URL Parameters like a=b&foo=bar etc.
    //$data = http_build_query($data);
    
    // parse the given URL
    $url = parse_url($url);
    
    if ($url['scheme'] != 'http') {
        die('Error: Only HTTP request are supported !');
    }
    
    // extract host and path:
    $host = $url['host'];
    $path = $url['path'];
    
    // open a socket connection on port 80 - timeout: 50 sec
    $fp = fsockopen($host, $port, $errno, $errstr, 50);
    
    if ($fp) {
        
        // send the request headers:
        fputs($fp, "POST $path HTTP/1.1\r\n");
        fputs($fp, "Host: $host\r\n");
        
        if ($referer != '')
            fputs($fp, "Referer: $referer\r\n");
        
        fputs($fp, "x-cons-id: " . $dataid . "\r\n");
        fputs($fp, "x-timestamp: " . $tStamp . "\r\n");
        fputs($fp, "x-signature: " . $encodedSignature . "\r\n");
        fputs($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
        fputs($fp, "Content-length: " . strlen($data) . "\r\n");
        fputs($fp, "Connection: close\r\n\r\n");
        fputs($fp, $data);
        
        $result = '';
        while (!feof($fp)) {
            // receive the results of the request, 128 char
            $result .= fgets($fp, 128);
        }
    } else {
        return array(
            'status' => 'err',
            'error' => "$errstr ($errno)"
        );
    }
    
    // close the socket connection:
    fclose($fp);
    
    // split the result header from the content
    $result = explode("\r\n\r\n", $result, 2);
    
    $header  = isset($result[0]) ? $result[0] : '';
    $content = isset($result[1]) ? $result[1] : '';
    
    // return as structured array:
    return array(
        'status' => 'ok',
        'header' => $header,
        'content' => $content
    );
    
}


$databpjs = "<request>
<data>
<t_sep>
<noKartu>0001134632924</noKartu>
<tglSep>2016-08-4 11:05:03</tglSep>
<tglRujukan>2016-08-2 11:05:03</tglRujukan>
<noRujukan>12345</noRujukan>
<ppkRujukan>0142U037</ppkRujukan>
<ppkPelayanan>3302191</ppkPelayanan>
<jnsPelayanan>2</jnsPelayanan>
<catatan>dari WS</catatan>
<diagAwal>K04.1</diagAwal>
<poliTujuan>GIG</poliTujuan>
<klsRawat>3</klsRawat>
<lakaLantas>2</lakaLantas>
<user>bpjs</user>
<noMr>1234</noMr>
</t_sep>
</data>
</request>";

$data = array(
    'Data' => $databpjs
);


$result = post_request($url, $port, $dataid, $tStamp, $encodedSignature, $databpjs, $referer = '');
if ($result['status'] == 'ok') {
    
    // Print headers
    echo $result['header'];
    
    echo '<hr />';
    
    //mengubah "re d sponse" menjadi "response"
    $resultstr = str_replace("re d sponse", "response", trim(preg_replace('/\s\s+/', ' ', $result['content'])));
    
    // print the result of the whole request:
    echo "<pre>";
    echo $resultstr;
    echo "</pre>";
    
} else {
    echo 'A error occured: ' . $result['error'];
}

?>

Pemanfaatan curl untuk ‘http request’ (POST dan GET) pada PHP

<?php

if(!isset($_GET['curltype'])){
 echo "usage: curlpostget.php?curltype=post or curlpostget.php?curltype=get";
 exit(1);
}


function curl_post($url, array $postdata = NULL, array $options = array())
{
 $defaults = array(
 CURLOPT_POST => 1,
 CURLOPT_HEADER => 0,
 CURLOPT_URL => $url,
 CURLOPT_FRESH_CONNECT => 1,
 CURLOPT_RETURNTRANSFER => 1,
 CURLOPT_FORBID_REUSE => 1,
 CURLOPT_TIMEOUT => 460,
 CURLOPT_POSTFIELDS => http_build_query($postdata)
 );

$ch = curl_init();
 curl_setopt_array($ch, ($options + $defaults));
 if( ! $result = curl_exec($ch))
 {
 trigger_error(curl_error($ch));
 }
 curl_close($ch);
 return $result;
}

function curl_get($url, array $getdata = NULL)
{
 $params = '';
 foreach($getdata as $key=>$value)
 $params .= $key.'='.urlencode($value).'&';
 
 $params = trim($params, '&');
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url.'?'.$params ); 
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , 70); //7 detik
 curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
 curl_setopt($ch, CURLOPT_HEADER, 0);
 
 if( ! $result = curl_exec($ch))
 {
 trigger_error(curl_error($ch));
 }
 curl_close($ch);
 return $result;
}

$url = 'https://latiful.hayat.web.id/test/postgetresponse.php';
 $data = array(
 'id'=>'application/x-www-form-urlencoded',
 'key'=>"! * ' ( ) ; : @ & = + $ , / ? % # [ ]"
 );

if($_GET['curltype']=='post'){ 
 $result = curl_post($url,$data);
 }
 
 if($_GET['curltype']=='get'){ 
 $result = curl_get($url,$data);
 }
 
 echo $result;
?>