[PHP] what is __ means in PHP ?


Description
     Sometime in php we often seen __ (underscore) character in naming methods. why they use that ??
that's magic methods !!. magic method in php always start with underscore __. for example :

public function __sleep()
{
     //to do here
}

you cannot use this function name in any classes unless you want this magic method assosiate with your classes. so when we need magic method ? it's depend on what your need. if  you not need this magic method don't use them.

PHP have several magic method, here's the list :

__construct()
is the method name for the constructor. The constructor is called on an object after it has been created.
class CAR
{
    public $brand = '';
    public function __construct($name) 
    {
        $this->brand = $name ;    }
}

$person = new CAR ( "honda" );
echo $person->brand;

__destruct()
Destructors called during the script shutdown have HTTP headers already sent. Attempting to throw an exception from a destructor can causes a fatal error.
class CAR
{
    public function __destruct() 
    {
        print "destroy the class";    
    }
}

$person = new CAR ();

__call()
this methods will call another function that inaccessible property like private / protected. 
namespace test\foo;

class A
{
    public static function __callStatic($method, $args)
    {
        echo __METHOD__ . "\n";

        return call_user_func_array(__CLASS__ . '::' . $method, $args);
    }

    protected static function foo()
    {
        echo __METHOD__ . "\n";
    }
}

A::foo();

__callStatic()
class A {
    public function __call($method, $parameters) {
        echo "I'm the __call() magic method".PHP_EOL;
    }

    public static function __callStatic($method, $parameters) {
        echo "I'm the __callStatic() magic method".PHP_EOL;
    }
}

class B extends A {
    public function bar() {
        A::foo();
    }
}

A::foo();
(new A)->foo();

B::bar();
(new B)->bar();

Result :
I'm the __callStatic() magic method
I'm the __call() magic method
I'm the __callStatic() magic method
I'm the __call() magic method

__get()
is utilized for reading data from inaccessible properties.

__set()
is run when writing data to inaccessible properties.

__isset()

__unset()

__sleep()

__wakeup()

__toString()

__invoke()

__set_state()

__clone()

__debugInfo()

*Note :
All example i taken from google (mostly from stackoverflow). thanks to the owner whose have this code :).

[PHP] Install Sqlserver driver and extention for PHP


Description
     Install driver and extention sql for php.

Requirement 
     -  OS x86 or 32 bit (XP , MS Win Server 2003)
     -  Apache (Wamp / XAMPP)

Sofware Download info :
    1. Microsoft sqlserver native client 2008 R2
    2. sqlserver extention support for php version under 5.4 but higher than 5.3
    3. if your php version higher 5.4, download extention here
        Microsoft Drivers 3.0 for PHP for SQL Server 

How to
    1. Download sqlserver native client 2008 R2 and sqlserver ext (Download Here)
    2. install sqlserver native client 2008 R2 or higher.
    3. in folder php extention (download in step-1) you will found file with name like
        -php_pdo_sqlsrv_53_ts_vc6.dll
        -php_sqlsrv_53_ts_vc6.dll
        -php_pdo_sqlsrv_53_nts_vc6.dll
        -php_sqlsrv_53_nts_vc6.dll
     here's the meaning :
          * 53 is the meaning for php version higher than 5.3
          * ts / nts (thread safe / non thread safe) , i preffered using thread safe but the default php is nts
          * vc6 , compiler visual c++ 6
     4. for example we use thread safe , so just 2 files we use (if you want use nts is okay )
        -php_pdo_sqlsrv_53_ts_vc6.dll
        -php_sqlsrv_53_ts_vc6.dll
     5. copy that file to C:\wamp\bin\php\php5.3.1\ext\[paste here] (WAMP)
     6. open php.ini and add this line :
         extension=php_pdo_sqlsrv_53_ts_vc6.dll
         extension=php_sqlsrv_53_ts_vc6.dll
     7. restart your webserver, and check the effect when connect sqlserver
     8. if still problem, may be u use OS like Win Server 2012 or later that need ODBC SQL. you can download msodbcsql HERE

NOTE :
     - please always read compatibility(OS) every software requirement before install the software. !!

[PHP][PHPExcel] Create Report Excel from PHP


Description
     Create report excel from PHP , only basic write :)

How To
    1. Download PHPExcel class Download Here
    2. after download you will see 3 folder (classes , example , documentation).
    3. if you want to learn you can find at example's folder , but the crucial part is Classes Folder , without that we cannot create excel.
    4. ok now we test the basic write from php to excel. here's the folder structure in your webserver :
        - Classes
        - Index.php //we create this file

        Here's the listing code for index.php :

<?php
/** Include PHPExcel */
require_once dirname(__FILE__) . '\Classes\PHPExcel.php';

// create object
$objPHPExcel = new PHPExcel();

// create metadata
$objPHPExcel->getProperties()->setCreator("name creator")
->setLastModifiedBy("name")
->setTitle("Report")
->setSubject("Report")
 ->setDescription("Report BOD")
->setKeywords("office PHPExcel php")
->setCategory("Test result file");

// insert data cell
$objPHPExcel->setActiveSheetIndex(0)
                      ->setCellValue('A1', 'this is A1')
                      ->setCellValue('B2', 'this is B2')
                      ->setCellValue('C1', 'this is C1')
                      ->setCellValue('D2', 'this is D2');

// create object for write
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

// save path and transform to excel , choose one if you think is easy
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
   or
$objWriter->save('C:\wamp\www\iniExcel.xlsx');
?>


*Note : don't forget __FILE__ is a magic constant from PHP (GET full path and filename of the file. )

[PHP] Array


Deskripsi
      Cara membuat array, menambahkan/push array ke array, serta mengubah value dari array php.

Howto
//create array
$myarray = array("permission" => array(
                                               "Main" => "true"
                                    ),
                  "Grants" => array(
                                             "Local" => "true"
       )
            );

//Accessing Array
echo $myarray["permission"] // output = array, because another array still exist
echo $myarray["permission"]["Main"] // output = true , because there's only leaf

//Count Array
echo count($myarray); // output 2 (permission and grant, another array not include)

//Count Array Recursive
echo count($myarray,COUNT_RECURSIVE); // output 4 (permission,grant,main,local)

//Add content
array_push($myarray["Grants"],array('suicide'=>'Yes'));
result : array("permission" => array(
                                               "Main" => "true"
                                    ),
                  "Grants" => array(
                                             "Local" => "true"
       ),
                                                      array(
                                             "suicide" => "true"
       ),
     );

//Compac Function
$name = "mahendra";
$position = "IT";
$detail=array("name","position");
$result=compact($detail);

print_r($result);

here's the result:
Array ( [name] => mahendra [position] => IT )

if i comment variable $position, the result:
Array ( [name] => mahendra )

*because the value not linking to same name of variable.

[PHP] Connect Oracle Database


Deskripsi
     Tutorial mengenai koneksi php ke oracle database menggunakan OCI.

Howto
1. You must have OCI Extention, if you don't have you can Download Here
2. Extract Extention in PHP5.x.x/Ext/[Extract Here]
3. Find Php.ini and add the extention, if you don't know how to add extention on php , find on google first.
4. Download and install Oracle Instant Client
5. Download and install Oracle Client Here
6. Create file TNSname.ora at Admin Folder in your Oracle Client, and add this line
// Based on you setup, it's only sample
DB_NAME =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS =
        (PROTOCOL = TCP)
        (HOST = XX.XX.XX.XX)
        (PORT = 1526)
      )
    )
    (CONNECT_DATA =
      (SERVICE_NAME = ServiceOrSID)
    )
  )

7. if all setup complete, now you can connect to oracle database from php with this code
<?php
$host = 'XX.YY.ZZ.GG';
$port = 1526;
$database_name = 'test';
$username = 'user';
$password = 'test';
$SIDorServiceName = 'myservice';

$TNSEditor = "(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = $host)(PORT = $port))
(CONNECT_DATA = (SID = $SIDorServiceName)))";

$statusOra = oci_connect("$username", "$password", $TNSEditor);

if($statusOra)
{
echo "connect sukses"."<br>";
$stid = oci_parse($statusOra, 'SELECT * FROM table where rownum <= 1');
oci_execute($stid);

while ($row = oci_fetch_array($stid,OCI_BOTH))
{
//echo $row["TASK_NAME"]."<br>";
  //echoing your field here
}
}
else
{
echo "connect failed";
}
oci_close($statusOra);
?>

[PHP] Understanding Regex


Deskripsi
      Sebenarnya udah banyak yang nanya regex itu apaan sih ? dan awalnya saya juga seperti itu tetapi sepertinya masih belum terlalu banyak yang membahas tentang regex (kagak tau juga sih tapi tetep aja masih bingung). regex merupakan singkatan dari regular expression dan banyak dipakai di beragam platform, tapi untuk kali ini saya akan menjelaskan regex untuk PHP.

Howto
1. Regex di PHP selalu diawali ^ dan diakhiri dengan $.
2. Untuk penggunaan tergantung dari fungsi PHP yang dipakai , dan HTACCESS juga  menggunakan regex.
3. Untuk basic syntax or example , anda dapat melihat di web ini
    http://www.noupe.com/php/php-regular-expressions.html
    menurut saya sudah sangat lengkap untuk penjelasan dari regex for PHP.

Hope this helps.

[PHP][JSON] Read JSON File


Deskripsi
        JSON (JavaScript Object Notation) adalah format data interchange yang ringan. Sangat mudah bagi manusia untuk membaca dan menulis. Sangat mudah bagi mesin untuk memparsing. Hal ini didasarkan pada subset dari JavaScript Programming Language, Standar ECMA-262 Edisi 3 - Desember 1999. JSON adalah format teks yang benar-benar independen tetapi menggunakan konvensi yang sangat memudahkan bagi programmer dari C-keluarga bahasa, termasuk C, C + +, C #, Java, JavaScript, Perl, Python, dan banyak lainnya. Properti ini membuat JSON bahasa data interchange yang ideal.

How To


Read File Json from Php  :


Json file content
{"val1":1,"val2":2}



<?php
// get file json and reading content
$varSementara = json_decode(file_get_contents('filejson.json'));

echo $varSementara->{'val1'};
echo '<br/>';
echo $varSementara->{'val2'};
?>


output :
1
2


[PHP][JSON] Write JSON File


Deskripsi
        JSON (JavaScript Object Notation) adalah format data interchange yang ringan. Sangat mudah bagi manusia untuk membaca dan menulis. Sangat mudah bagi mesin untuk memparsing. Hal ini didasarkan pada subset dari JavaScript Programming Language, Standar ECMA-262 Edisi 3 - Desember 1999. JSON adalah format teks yang benar-benar independen tetapi menggunakan konvensi yang sangat memudahkan bagi programmer dari C-keluarga bahasa, termasuk C, C + +, C #, Java, JavaScript, Perl, Python, dan banyak lainnya. Properti ini membuat JSON bahasa data interchange yang ideal.

How To


Write File from Php to JSON format :



<?php
$file = array('val1' => 1,'val2' => 2);

// Write to the file
file_put_contents('filejson.json', json_encode($file));
?>

output :
filejson.json with content {"val1":1,"val2":2}

[PHP] Regex Quick Refference


Deskripsi
      hanya untuk sharing aja , mungkin aja perlu dan dipakai pada saat menggunakan fungsi pencarian string preg_match() di php.

How To

Regex quick reference
[abc]     A single character: a, b or c
[^abc]     Any single character but a, b, or c
[a-z]     Any single character in the range a-z
[a-zA-Z]     Any single character in the range a-z or A-Z
^     Start of line
$     End of line
\A     Start of string
\z     End of string
.     Any single character
\s     Any whitespace character
\S     Any non-whitespace character
\d     Any digit
\D     Any non-digit
\w     Any word character (letter, number, underscore)
\W     Any non-word character
\b     Any word boundary character
(...)     Capture everything enclosed
(a|b)     a or b
a?     Zero or one of a
a*     Zero or more of a
a+     One or more of a
a{3}     Exactly 3 of a
a{3,}     3 or more of a
a{3,6}     Between 3 and 6 of a

/teSt/   include word 'teSt' (case sensitive)
/tEst/i  include word 'test' (case insensitive)
/tEst|CrAp/i  include word 'test' or crap(case insensitive)


options: i case insensitive 



example case , detecting mobile browser


<?php
// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match(strtolower("/chrome|mozila|Opera/"), strtolower($_SERVER['HTTP_USER_AGENT']))) 
{
    echo "Browser Standart(Chrome or Mozilla or Opera) Found.";


if (preg_match("/MSIE/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {

    echo "Browser IE Found.";



if (preg_match("/opera mini/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
    echo "Mobile Browser Found.";


?>

[PHP][FTP] Using FTP in php


Deskripsi
           File Transfer Protocol (FTP) adalah protokol jaringan standar yang digunakan untuk mentransfer file dari satu host ke host lain melalui jaringan berbasis TCP. FTP dibangun pada arsitektur client-server dan menggunakan kontrol terpisah dan sambungan data antara klien dan server. untuk menggunakan FTP dibutuhkan Username dan Password untuk otentikasi namun dapat diberikan juga secara anonymous.

How To

1. Step ke-1 set FTP server anda , saya asumsikan FTP rootnya folder FTP .
    contoh / example IP FTP Server : 192.168.1.2
    Struktur FTP :
         FTP (root folder) --> Files (folder) --> text.txt (file ini yang akan kita ambil)

2. Struktur file php di webserver (in your webserver),
     
       WWW / Localhost   --> download.php
                                       --> files (folder) --> 'we will create here

3. write Php code in download php

<?php
// define some variables
$save_to = 'files'; // download only just in webserver
$server_file_ftp = 'Files/text.txt';
root folder webserver : WWW/FTP/Download

// set up basic connection
$conn_id = ftp_connect('192.168.1.2');

// login with username and password, you can create account in FTP server
$login_result = ftp_login($conn_id, 'Anonymous', '');

$save_to =  'files\text.txt';
$server_file_ftp = 'files\text.txt';

// try to download $server_file_ftp and store in $save_to (your local web server)
if (ftp_get($conn_id, $save_to, $server_file_ftp , FTP_BINARY))
{
    echo "Successfully written to $save_to\n";
}
 else
{
    echo "There was a problem\n";
}

// close the connection
ftp_close($conn_id);

?>

4. Open URL in LOCALHOST/files/download.php
5. Done, jika tidak ada masalah maka file anda berada di direktory in webserver :
    WWW --> files/text.txt

[PHP][TCPDF] Create Report PDF from PHP


Deskripsi
        Membuat Report PDF menggunakan TCPDF , diharapkan user dapat memahami konsep dasar membuat Report PDF menggunakan class dari TCPDF.

How To
1. Download Class TCPDF  http://www.tcpdf.org/
2. Buat folder TEST di webserver anda.
3. Extract TCPDF beserta isi classnya ke dalam folder TEST.
4. Struktur folder anda sekarang :

       TEST ---> TCPDF ---> File and library TCPDF Here

5. Sekarang buat file index.php di dalam folder TEST, sehingga strukturnya menjadi seperti ini :

       TEST ---> TCPDF ---> File and library TCPDF Here
                 ---> index.php

6. Copy paste Code dibawah ini


<?php
require_once('tcpdf/tcpdf.php');

// for setting variable you can goto tcpdf/config/tcpdf_config, you can change them
// create new PDF document; (i set PDF_UNIT from Milimeter  to Centimeter)
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

//set margin page (all direction)
//setMargins(LEFT,TOP,RIGHT)  in CM (centimeter), it's looks like MS Word :D
$pdf->SetMargins(1, 3, 1,true);


//setup Header
$pdf->SetHeaderMargin(1); // margin header 1 CM
$pdf->setPrintHeader(true); // enabled ? true
$pdf->SetHeaderData(false, 0, "Hellow World Header", "mynotework.blogspot.com"); //your text here
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', 15)); // data font header

//Set Footer
$pdf->SetFooterMargin(1); // margin footer 1 CM
$pdf->setPrintFooter(true); // enabled ? true
//$pdf->setFooterData($tc=array(0,64,0), $lc=array(0,64,128));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
//$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

//set auto page breaks
$pdf->SetAutoPageBreak(true, 1.3); // it's use when u use table, to increase break page

// Set font
$pdf->SetFont('dejavusans', '', 14, '', true); // set global font

// Add a page, MUST BE DECLARATION at lease 1 statement
$pdf->AddPage();

// Set some content to print
$html = ' Hello World TCPDF';


// Print text using writeHTML()
$pdf->writeHTML($html, true, 0, true, 0);

// Buat output buffer page(I) / create file (F)
$pdf->Output('example_001.pdf', 'I');

//============================================================+
// END OF FILE
//============================================================+
?>

if you will use table ? simple ! , just write you HTML , for example


//some example
$html = ' <table>
                <tr nobr="true" border="1">
                       <td nowrap="true">this if my first cell</td>
                </tr>
             </table>';


// Print text using writeHTML()
$pdf->writeHTML($html, true, 0, true, 0);

*nobr="true" => no breakline
*border="1" => show border cell
*nowrap="true" => cell can increase width automatically when character veryyyy loooong :D

one more , you can customize TCPDF setting on tcpdf/config/tcpdf_config.php ALL OF SETTINGS VARIABLE IN THERE and it's familiar with MS WORD.

still not understand ?
you can download my sample and running in your webserver wamp/xampp (apache) :


Download Sample Tutorial
Instruction :
1. before download take a survey first to help our advertiser.
2. after download, just drop extract the file (.rar) to your webserver (WWW / Htdocs)
3. Access via localhost using browser and you will get the result.
4. every download = you give a cup of cofee to me, thank you very much it make me wants to create a better tutorial.
5. this file, include tcpdf library.

[PHP][Security] Prevention XSS Attack


Description
           Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications. XSS enables attackers to inject client-side script into Web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls.
there is 3 type of XSS attack : Stored, Reflected, and DOM-Based. 

1. Stored XSS  
    this type the script stored into database, the common attack via URL or Form .
XSSStored1.PNG


 for example display cookie , injected via Form 

XSSStored2.PNG

2. Reflected XSS 
     this type attack where script not stored in database but direct in client html, typically attack via URL and distribute using link, 
here's for example http://example.com/index.php?user=<script>alert(123)</script>

3. DOM-Based XSS 
    this type attack modified DOM element on client html , of course this attack maybe reflected or stored xss. here's for example :
    http://example.com/index.php?user=<script>window.onload = function() {var AllLinks=document.getElementsByTagName("a");AllLinks[0].href = "http://badexample.com/malicious.exe"; }</script> 

but these day typical attack just include source javascript from CDN <script type="text/javascript" src="www.somecdnnetwork.com/maliciousscript.js"></script>

of course with calling that file the attacker can do many things such as dom manipulation , redirect to phising site or  steal cookie.  


How To Prevent XSS

1.  Use Httponly for prevent stealing cookie. 
2.  Always filter every input parameter (including html char , hexadecimal, base64 dll) .  

Syntax :  htmlspecialchars() or strip_tags()