Kamis, Desember 8

PHP Setcookie() Function

Sumber :  w3schools

Definition and Usage

Fungsi setcookie() mengirim sebuah HTTP cookie pada klient.
Cookie merupakan variabel, yang dikirim server ke browser. Cookie biasanya file teks kecil yang embeded server pada komputer user. Setiap kali komputer yang sama melakukan permintaan halaman dengan browser, ia akan mengirim cookie juga.
Nama cookie secara otomatis ditetapkan ke sebuah variabel dengan nama yang sama. Misalnya, jika cookiedikirim dengan nama "user", variabel secara otomatis dibuat dengan nama $user, berisi nilai dari cookie tersebut.
Cookie harus ditetapkan sebelum output lainnya dikirim ke klien.
Fungsi ini bernilai TRUE ketika sukses atau FALSE ketika gagal.

Syntax

setcookie(name,value,expire,path,domain,secure)

Parameter Description
name Required. Menentukan nama cookie
value Required. Menentukan nilai dari cookie
expire Optional. Menentukan kapan cookie berakhir.
time()+3600*24*30 akan mengatur cookie berakhir dalam 30 hari. Jika parameter tidak diatur, cookie akan berakhir pada saat session berakhir (ketika browser ditutup).
path Optional. Menentukan path server cookie
Jika diatur pada "/", cookie akan tersedia dalam seluruh domain. Jika diatur pada "/test/", cookie akan tersedia dalam test directory dan semua sub directory test. Nilai default adalah directory dimana cookie diatur.
domain Optional. Menentukan nama domain cookie.
Untuk membuat cookie tersedia pada semua subdomain dari example.com maka harus di atur pada ".example.com". Pengaturan ke www.example.com akan membuat cookie tersedia hanya dalam subdomain www.
secure Optional. Menentukan apakah cookie hanya boleh dikirim melalui koneksi aman HTTPS. TRUE menunjukkan bahwa cookie hanya akan diatur jika tersedia koneksi aman. Default adalah FALSE.


Tips and Notes

Tip: Nilai dari nama cookie "user" dapat diakses oleh $HTTP_COOKIE_VARS["user"] atau $_COOKIE["user"].
Note:Nilai cookie secara otomatis berupa URLencoded ketika mengirim cookie, dan otomatis diterjemahkan ketika di terima (untuk mencegah URLencoding, gunakan setrawcookie() sebagai penggantinya)

Example 1

Mengatur dan mengirim cookie 

<?php
$value = "my cookie value";


// send a simple cookie
setcookie("TestCookie",$value);
?>


<html>
<body>
...
...

<?php
$value = "my cookie value";

// send a cookie that expires in 24 hours
setcookie("TestCookie",$value, time()+3600*24);
?>

<html>
<body>
...
...

Example 2

Berbagai cara mengambil nilai dari cookie (setelah cookie ditetapkan):

<html>
<body>

<?php
// Print individual cookies
echo $_COOKIE["TestCookie"];
echo "<br />";
echo $HTTP_COOKIE_VARS["TestCookie"];
echo "<br />";

// Print all cookies
print_r($_COOKIE);
?>

</body>
</html>

Ouput dari code di atas akan menjadi:

my cookie value
my cookie value
Array ([TestCookie] => my cookie value

Example 3

Menghapus cookie dengan menetapkan tanggal berakhirnya ke akhir tanggal/waktu: 

<?php
// Set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
?>

<html>
<body>

...
...

Example 4

Membuat cookie array

<?php
setcookie("cookie[three]","cookiethree");
setcookie("cookie[two]","cookietwo");
setcookie("cookie[one]","cookieone");

// print cookies (after reloading page)
if (isset($_COOKIE["cookie"]))
  {
  foreach ($_COOKIE["cookie"] as $name => $value)
    {
    echo "$name : $value <br />";
    }
  }
?>

<html>
<body>

...
...

Ouput dari code di atas akan menjadi: 

three : cookiethree
two : cookietwo
one : cookieone 

Selasa, Desember 6

PHP Cookie


Sumber : w3schools


Cookie sering digunakan untuk mengidentifikasi pengguna

What is a Cookie?

Cookie sering digunakan untuk mengidentifikasi pengguna. Cookie adalah file kecil yang embed pada server komputer pengguna. Setiap kali komputer yang sama melakukan permintaan halaman dengan browser, ia akan mengirim cookie juga. Dengan PHP, anda bisa membuat dan mengambil nilai cookie.

How to Create a Cookie?

Fungsi setcookie() digunakan untuk mengatur cookie.
Note: Fungsi setcookie() harus berada SEBELUM tag <html>.

Syntax

setcookie(name, value, expire, path, domain);

Example 1

Pada contoh di bawah ini, kita akan membuat cookie dengan nama "user" dan memberinya nilai "Alex Porter". Kita juga mendeskripsikan bahwa cookie akan habis masanya setelah satu jam:

<?php
setcookie("user", "Alex Porter", time()+3600);
?>

<html>
.....

Note: Nilai cookie secara otomatis berupa URLencoded ketika mengirim cookie, dan otomatis diterjemahkan ketika di terima (untuk mencegah URLencoding, gunakan setrawcookie() sebagai penggantinya).

Example 2

Anda juga dapat mengatur masa berlaku cookie dengan cara lain. Ini mungkin lebih mudah dari pada menggunakan hitungan detik.

<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>

<html>
.....

Pada contoh di atas masa berlaku cookie diatur dalam bentuk bulan (60 sec * 60 min * 24 hours * 30 days).

How to Retrieve a Cookie Value?

Variabel PHP $_COOKIE digunakan untuk mengambil nilai cookie.

Pada contoh di bawah ini, cookie dengan nama "user" diambil nilainya dan ditampilkan pada halaman:

<?php
// Print a cookie
echo $_COOKIE["user"];

// A way to view all cookies
print_r($_COOKIE);

?>

Pada contoh di bawah fungsi isset() digunakan untuk memeriksa apakah cookie sudah diatur atau tidak:

<html>
<body>

<?php
if (isset($_COOKIE["user"]))
  echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
  echo "Welcome guest!<br />";
?>

</body>
</html>


How to Delete a Cookie?

Ketika menghapus cookie harus dipastikan bahwa tanggal masa aktifnya sudah lewat.

Contoh:


<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>


What if a Browser Does NOT Support Cookies?

Jika aplikasi anda berhubungan dengan browser yang tidak mendukung cookie, anda harus menggunakan metode lain untuk melewatkan informasi dari satu halaman ke halaman lain dalam aplikasi anda. Salah metodenya adalah melewatkan data melalui form.
Form di bawah melewatkan user input pada "welcome.php" ketika user menekan tombol "Submit":

<html>
<body>

<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

</body>
</html>

Mengambil nilai di file "welcome.php" seperti ini:

<html>
<body>

Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.

</body>
</html>

Minggu, Desember 4

PHP Sessions

Sumber : w3schools

Sebuah variabel PHP Sessions digunakan untuk menyimpan informasi, atau mengubah pengaturan untuk pengguna. Variabel sesi menyimpan informasi tentang satu pengguna tunggal, dan tersedia untuk semua halaman dalam satu aplikasi.


PHP Session Variables

Ketika anda bekerja dengan sebuah aplikasi, anda membukanya, melakukan beberapa perubahan dan kemudian anda menutupnya. Ini jauh seperti sebuah Session. Komputer tahu siapa Anda. Ia tahu ketika Anda memulai aplikasi dan ketika anda mengakhiri. Tapi di internet ada satu masalah server web tidak tahu siapa anda dan apa yang anda lakukan.

Sebuah session PHP memecahkan masalah ini dengan memungkinkan anda untuk menyimpan informasi pengguna pada server untuk digunakan kemudian (yaitu nama pengguna, belanja barang, dll). Namun, informasi session bersifat sementara dan akan dihapus setelah pengguna telah meninggalkan situs web. Jika anda membutuhkan penyimpanan permanen anda mungkin ingin menyimpan data dalam database.

Session bekerja dengan menciptakan sebuah id unik (UID) untuk setiap pengunjung dan menyimpan variabel berdasarkan UID ini. UID disimpan baik dalam cookie atau disebarkan dalam URL.
 


Starting a PHP Session

Sebelum Anda dapat menyimpan informasi pengguna dalam session PHP, Anda harus terlebih dahulu memulai sesi.

Catatan: Fungsi session_start() harus muncul SEBELUM tag <html>:


<?php session_start(); ?>
<html>
<body>
</body>
</html>

Kode di atas akan mendaftarkan pengguna session pada server, memungkinkan anda untuk memulai menyimpan informasi pengguna, dan menetapkan UID untuk sesi pengguna.


Storing a Session Variable

Cara yang benar untuk menyimpan dan mengambil variabel session adalah dengan menggunakan variabel $_SESSION PHP:

<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>

Output:

Pageviews=1

Pada contoh di bawah, kita membuat counter tampilan halaman sederhana. Para fungsi isset() memeriksa jika "views" variabel sudah diatur. Jika "views" telah ditetapkan, kita dapat menaikkan counter. Jika "views" tidak ada, kita menciptakan sebuah "views" variabel, dan diset ke 1:

<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>


Destroying a Session

Jika anda ingin menghapus beberapa data session, anda dapat menggunakan fungsiunset() atau session_destroy().

Unset() adalah fungsi yang digunakan untuk membebaskan variabel session yang ditentukan:


<?php
unset($_SESSION['views']);
?>

Anda juga dapat benar-benar menghapus session dengan memanggil fungsi session_destroy():

<?php
session_destroy();
?>

Catatan: session_destroy() akan mengatur ulang session dan akan menghilangkan semua data yang tersimpan pada session.

Kamis, Juni 9

Setting Sms Gateway dengan gammu

http://anriz.com/ : Ini saya tunjukkan cara cepat untuk membuat sms gateway dengan gammu untuk Operating System windows. Saya memakai versi gammu jaman bahula yaitu bukan versi .exe tapi berupa file-file. Karena saat saya kerja praktek di Koperasi Telkomsel yaitu Kisel Telkomsel jawa timur. Saya sama temen saya di suruh buat sms gateway dan web menggunakan PHP yang akan digunakan untuk cek client ke server tentang validasi no hp pelanggan. Dan alhamdulillah dalam waktu 1 bulan akhirnya kami berhasil.

Oklah dari pada banyak ngemeng lebih baik to the point. ini step2nya q ambilkan dari blog aswandi, cz males tulis, tapi udh q edit sesuai pengalaman saya :
1. Colokin modem gsm / HP kesalah satu port USB (jika ada paralel port silahakan dipasang di usb atau lewat paralel port cz sama saja), jangan lupa pasang SIM Card dan ditutup dg rapat. Install drivernya dari CD.
2. Cek modem ini masuk ke Port COM berapa dan type koneksinya apa, caranya klik kanan my Computer, klik Hardware, klik Device Wizard. Klik 2 kali Hardware Modem HP, dari situ ntar keliatan di port com berapa, (kasus saya masuk di port: COM10)
3. Ekstrak file gammu_win32.zip ke salah satu folder, misalnya di C:gammu_win32, dalam folder gammu_win32 ada file gammurc, itu adalah file konfigurasi gammu utk konek dengan modem, ubah tulisan di bawah tulisan [gammu] pada baris port dan connection aja, dan untuk tulisan [gammu1] semua baris di bawahnya di tutup aj dengan menggunakan tanda pagar (#), berikut contohnya :
———-start setting file gammurc ————–
port = com1:
#model = 6110
connection = at115200
#synchronizetime = yes
#logfile = gammulog
#logformat = textall
#use_locking = yes
#gammuloc = locfile
#startinfo = yes
#gammucoding = utf8
#rsslevel = teststable
#usephonedb = yes
[gammu1]
#port = com7:
#model = 6110
#connection = fbusblue
#synchronizetime = yes
#logfile = gammulog
#logformat = textall
#use_locking = yes
#gammuloc = locfile
#startinfo = yes
#gammucoding = utf8
———-end setting  file gammurc ————–
4. Skrg coba masuk ke DOS Prompt, masuk ke folder gammu_win32 folder dimana terdapat file gammu.exe
5. coba ketik: gammu –identify, bila gammu telah dapat mengenali modem HP/hardware mu, maka akan muncul detail hardware mu.
6. langkah berikutnya adalah membuat database untuk tempat peyimpanan database sms masuk dan keluar, buka browser anda dan bukalah URL http://localhost/phpmyadmin.  Bila tidak bisa kebuka berarti apache dan mysql anda belum jalan, untuk pemula saya sarankan pake Xampp di windows XP, karena aplikasi ini otomatis menjalankan apache dan mysql saat booting windows.
7. Buat database dengan nama smsd (nama terserah anda), import file SQL di C:/gammu_win32 dg nama file mysql.sql
8. Edit file smsdrc di C:/gammu_win32, yang perlu diubah hanya baris ini aja (sesuaikan dengan settingan database server anda)
# ——– start setting for–smsd MYSQL ——–
user = root
password =
pc = localhost
database = smsd
# ——–  end setting for–smsd MYSQL ——–
9. sekarang jalankan SMS Daemon (server SMS) dengan cara masuk ke dos prompt, C:gammu_win32>gammu –-smsd MYSQL smsdrc
(tanda minus-nya 2 kali), bila sukses maka SMS server telah berjalan.
Setelah itu sms2 yang masuk ke hp langsung masuk ke database.
WARNING : sms2 di inbox akan terhapus, jadi backup dahulu sms2 yg penting
Jadi, proses gammu / smsgateway akn ttp jalan selama daemonnya masih jalan, setiap ada sms yang masuk ke inbox kita, sms itu langsung ‘ditarik’ dan dimasukkan ke database tabel inbox.
Dan kalau mau kirim sms, cukup dengan memasukkan entry ke tabel outbox maka entry tersebut akan ‘diteruskan’ ke hp dan dikirim lah sms. setelah terkirim entry di tabel outbox akan di pindah ke tabel sent-item.
Next, kalau pengen bikin sistem yang auto reply sms, cukup bikin code yang mendeteksi setiap ada inbox yang masuk, terus di baca format textnya, kalau cocok dengan pattern tertentu dan udah di generate reply yang dimaksud, insert data ke tabel outbox. (keyword: crontab, trigger)
Troubleshooting / masalah yang sering terjadi saat setting koneksi sms gateway dengan gammu di windows atau wammu di linux. Klik disini troubleshooting
Berbagi ilmu itu adalah kebaikan yg besar karena bisa membantu sesama … hidup open source …

Sabtu, Mei 28

Best .htaccess Hacks For Websites

http://www.priteshgupta.com/ : The .htaccess configuration file on your server which controls Apache Server is an important file and a very powerful tool for your website if used properly. It is generally found in root of your web server. In this article I will share how .htaccess can help improve your website’s  stability, security, functionality and usability.
Please backup your .htaccess file before doing any changes. In case anything goes unexpected just replace the .htaccess with your backup.

Search Engine Friendly 301 Redirects

If you have moved your website to another domain and want to redirect all the pages to their new location or you want to redirect a particular URL to a specific page in most Search Engine Friendly manner then you can use the below code in your .htaccess.
## .htaccess Code :: BEGIN
Redirect 301 /Old_Directory/ http://www.new-domain.com/
## .htaccess Code :: END
Note: Remember not to insert “http://www” to the “/Old_Directory/”.

Block Requests From User Agents

By adding a ban list to your .htaccess file you can block all unwanted user agents. These agents at times are harmful and can can cause load on your server.
## .htaccess Code :: BEGIN
## Block Bad Bots by user-Agent
SetEnvIfNoCase user-Agent ^FrontPage [NC,OR]
SetEnvIfNoCase user-Agent ^Java.* [NC,OR]
SetEnvIfNoCase user-Agent ^Microsoft.URL [NC,OR]
SetEnvIfNoCase user-Agent ^MSFrontPage [NC,OR]
SetEnvIfNoCase user-Agent ^Offline.Explorer [NC,OR]
SetEnvIfNoCase user-Agent ^[Ww]eb[Bb]andit [NC,OR]
SetEnvIfNoCase user-Agent ^Zeus [NC]
Order Allow,Deny
Allow from all
Deny from env=bad_bot
## .htaccess Code :: END

Remove WWW from your website’s URL

If you wish to remove the “www” from your website’s URL, like http://your-domain.com instead of http://www.your-domain.com, then you can use the below code.
## .htaccess Code :: BEGIN
RewriteEngine on
Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^www\.your-domain\.com$ [NC]
RewriteRule ^(.*)$ http://your-domain.com/$1 R=301,NC]
## .htaccess Code :: END

Add WWW to your website’s URL

If you wish to add “www” your website URL, you can add the below code.
## .htaccess Code :: BEGIN
RewriteEngine On
Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^your-domain.com [NC]
RewriteRule ^(.*)$ http://www.your-domain.com/$1 [L,R=301]
## .htaccess Code :: END

Allow only specific IP addresses and block everyone else

If you want to allow only few particular IPs and deny everyone else then you can use the below code in your .htaccess file. Replace “http://www.your-domain.com/under_construction.html” with the error page which you will like to be displayed to everyone(except the particulars IPs) or you can simply omit the line if you don’t need it.
## .htaccess Code :: BEGIN
ErrorDocument 403 http://www.your-domain.com/under_construction.html
Order deny,allow
Deny from all
Allow from 172.16.254.1
Allow from 172.16.254.9
## .htaccess Code :: END

Ban only specific IP addresses and allow everyone else

If you think there are spammers regularly flooding your website you can simply ban their IP addresses to get rid of them and allow everyone else.
## .htaccess Code :: BEGIN
allow from all
deny from 172.16.254.6
deny from 172.16.254.5
## .htaccess Code :: END

Custom Error Pages

You must have already seen many custom 404 error pages, you can use the below code for error pages for 404 errors and other errors too.
## .htaccess Code :: BEGIN
ErrorDocument 401 /error/401.html
ErrorDocument 403 /error/403.html
ErrorDocument 404 /error/404.html
ErrorDocument 500 /error/500.html
## .htaccess Code :: END

Change Index Page

The default page of a regular server is either an index.html or index.php, you can use the below code to change it.
## .htaccess Code :: BEGIN
DirectoryIndex index2.html
## .htaccess Code :: END

Remove Extensions from Files

The below code removes extension in a URL, this make it the URL more Search Engine Friendly. Example: http://www.your-domain.com/about.php will be http://www.your-domain.com/about. You can replace .php with .html or whatever you want.
## .htaccess Code :: BEGIN
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ /$1.php [L,QSA]
## .htaccess Code :: END

Disable Directory Browsing

You can block users from viewing directories without an index page using the below code.
## .htaccess Code :: BEGIN
Options All -Indexes
## .htaccess Code :: END

Disable Browser To Prompt Open/Save As Option

Usually when you try to download something you generally get asked whether to Save it or Open it. To disable this from server side, you can use the following code:
## .htaccess Code :: BEGIN
AddType application/octet-stream .mp3
AddType application/octet-stream .mpg
AddType application/octet-stream .avi
AddType application/octet-stream .mov
AddType application/octet-stream .pdf
AddType application/octet-stream .xls
AddType application/octet-stream .zip
## .htaccess Code :: END

Change Script Execution Type

If you have php within an html file, you can still execute it as php using the below code.
## .htaccess Code :: BEGIN
AddType application/x-httpd-php .html
## .htaccess Code :: END

Stop Execution of Script

If you want, you can stop scripts like php, asp, etc from executing and simply display them as plain text.
## .htaccess Code :: BEGIN
RemoveHandler cgi-script .php .asp .html
AddType text/plain .php .asp .html
## .htaccess Code :: END

Set Default Admin Email ID

Using below code you can set the default Email ID of your server.
## .htaccess Code :: BEGIN
ServerSignature EMail
SetEnv SERVER_ADMIN mail@your-site.com
## .htaccess Code :: END

Disable Hotlinking

Using this disable users from using images hosted on your server in their website, this helps in saving bandwidth. You can do this by adding the below code, replace “http://your-domain.com/copyright.jpg” with the image which you will like to be displayed instead.
## .htaccess Code :: BEGIN
Options +FollowSymlinks
#Protect against hotlinking
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)?your-domain.com/ [nc]
RewriteRule .*.(gif|jpg|png)$ http://your-domain.com/copyright.jpg[nc]
## .htaccess Code :: END

Enable Caching

The below code will tell the web browser to use cache instead when your website is loaded. It doesn’t directly increase the loading speed of your website, it will basically loads the cached content when the user visits your website second time. Currently the cache expiry time is set to 1 day(86400 seconds).
## .htaccess Code :: BEGIN
# BEGIN EXPIRES
ExpiresActive On
ExpiresDefault "access plus 86400 seconds"
ExpiresByType text/css "access plus 1 week"
ExpiresByType text/plain "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType application/x-javascript "access plus 1 month"
ExpiresByType application/javascript "access plus 1 week"
ExpiresByType application/x-icon "access plus 1 year"
# END EXPIRES
## .htaccess Code :: END