การเขียนโปรแกรมภาษา PHP สำหรับ Dynamic website

ปรับปรุง : 2552-03-31 (เพิ่ม google chart)
เกี่ยวกับการเรียนรู้ และการสอน คือ Learning by doing และ Teaching by example
หน่วยที่ 1 : ความรู้เบื้องต้น
+ ความหมายพีเอชพี (PHP Meaning) (wikipedia.org)
ภาษาพีเอชพี (PHP Language) คือ ภาษาคอมพิวเตอร์ประเภทโอเพนท์ซอร์ท (Open Source Computer Language) สำหรับพัฒนาเว็บเพจแบบไดนามิก เมื่อเครื่องบริการได้รับคำร้องจากผู้ใช้ก็จะส่งให้กับ ตัวแปลภาษา ทำหน้าที่ประมวลผลและส่งข้อมูลกลับไปยังเครื่องของผู้ใช้ที่ร้องขอ ในรูปเอชทีเอ็มแอล ภาพ หรือแฟ้มดิจิทอลอื่นใด ลักษณะของภาษามีรากฐานคำสั่งมาจากภาษาซี เป็นภาษาที่สามารถพัฒนาให้ใช้งานแบบโต้ตอบกับผู้ใช้ได้
ภาษาพีเอชพี (PHP Language) มีการทำงานแบบเซอร์ฟเวอร์ไซต์สคริปต์ (Server-Side Script) จึงต้องมีเครื่องบริการ (Server) ที่ทำหน้าที่บริการการแปลภาษา และส่งผลให้กับเครื่องผู้ใช้ (Client) ที่ร้องขอด้วยการส่งคำร้องเข้ามายังเครื่องบริการ คำว่า PHP ย่อมาจาก Personal Home Page แต่พัฒนาให้มีประสิทธิภาพยิ่งขึ้น จึงเปลี่ยนเป็น Professional Home Page
ประวัติของภาษาพีเอชพี (PHP Language History)
ภาษาพีเอชพีถูกคิดค้นขึ้นในปีค.ศ.1994 (พ.ศ.2537) โดย Mr.Rasmus Lerdorf เพื่อใช้ตรวจสอบสถิติการเข้าชมเว็บของตนเอง ต่อมาในปีค.ศ.1995 มีการเผยแพร่ภาษานี้สู่สาธารณะ และพัฒนาเป็น PHP/FI หรือพีเอชพีรุ่น 2 จนกระทั่งกลางปีค.ศ.1996 เริ่มมีทีมพัฒนาอย่างจริงจังโดยมี Mr.Zeev Suraski และ Mr.Andi Gutmans ร่วมทีม และพัฒนาเป็นพีเอชพีรุ่น 3
ความหมาย (Meaning)
- เซสชัน (Session) คือ ข้อมูลที่ถูกสร้างขึ้นเมื่อใช้บราวเซอร์ ติดต่อเข้าเครื่องบริการ และถูกทำลายเมื่อบราวเซอร์ถูกปิดลง ข้อมูลนี้ถูกจัดเก็บในเครื่องบริการ
- คุกกี้ (Cookie) คือ ข้อมูลขนาดเล็กที่เป็น HTTP Header แบบหนึ่ง ถูกส่งจากเครื่องบริการไปเก็บไว้ในเครื่องของผู้ใช้ตามที่บราวเซอร์กำหนด เพื่อบันทึกข้อมูลการเข้าเยี่ยมชม เมื่อผู้ใช้เข้าไปเยี่ยมชมเว็บไซต์อีกครั้ง เครื่องบริการจะใช้ข้อมูลคุกกี้ที่มีอยู่ในเครื่องของผู้ใช้ได้ทันที
- fopen คือ ฟังก์ชันเปิดแฟ้ม ถ้าเปิดตาม URL ต้องแก้ php.ini ให้ allow_url_fopen = on ?
หมายเหตุ (Remark)
- รหัสต้นฉบับ (Source Code) ของตัวแปลภาษา (Compiler) (museum # # v1)
- เอกสารอ้างอิง หรือตัวแปลภาษา (Compiler) มีที่ Quick Reference ซึ่งสมบูรณ์ที่สุด
- การทำให้ Windows เป็น Web server และบริการ PHP
- Free Webhosting หลายแห่งไม่บริการ GD Support Graphic จึงใช้ imagecreate ไม่ได้
- สามารถใช้ phpinfo(); ตรวจสอบได้ว่า Host ให้ GD Support graphic หรือไม่
- แผนการสอน PHP + MySQL เบื้องต้น และ training49.txt
- แผนการสอน PHP + MySQL ระดับกลาง
- แผนการสอน PHP สำหรับครูโรงเรียน (ควรเข้าใจ PHP + MySQL + HTML + Server มาก่อน)
- Script php ไม่ทำงาน ต้องเปลี่ยน Encoding type เป็น Plain Text (ขนาดแฟ้มลดลงครึ่งหนึ่ง)
Download :
  + ตัวแปลภาษา 4.4.7 8 MB (last of 4)
  + PHP Manual 3 MB(html)
  + PHP Manual 14 MB(chm)
รหัสต้นฉบับ (Source Code)
+ icon.php ?
+ รายงานการประเมินตนเอง # 10/48
+ Webboard (Sample)
+ SuperModel (Sample)
+ เพื่อเปิดบริการพื้นที่เว็บฟรี (Sample)
+ รับสมาชิก และตรวจ (admin:p)
+ เอกสารหน่วยที่ 5 (.doc)
+ แปลงสระปัญหาของ PDF
+ โค้ดอื่น ๆ ที่รวมไว้ ...

หน่วยที่ 2 : รหัสต้นฉบับ อย่างสั้น
เอกสาร Power Point
Intro. to HTML27
Intro. to Web Application18
php: echo & remark8
php: Structure Programming13
php: Text File #18
php: Text File #215
php: Cookie & Session8
php: File Uploading & Shell8
asp: Structure Programming9
asp: GET, POST, Session8
asp: Data Selecting6
asp: Data Updating6

หน่วยที่ 3 : บทเรียน
  1. miniboard มี php 5 แฟ้ม ติดต่อ MySQL อย่างง่ายมาก รุ่น 1 2549-08-18 [ test ]
    Case at www.se-ed.net/thaiall (บทเรียนยังอยู่ แต่ตัวอย่างภาคปฏิบัติใช้ไม่ได้แล้ว)
  2. การประมวลผลแฟ้มแบบ text (เพิ่ม ลบ แสดงได้ แต่ไม่มีแก้ไข เพราะอยากให้ท่านแก้โปรแกรมเอง)
  3. ข้อสอบสุ่มไม่ซ้ำ.javascript (ใช้หลักการสุ่มไม่ซ้ำที่ได้ตัวเลขที่กระจาย และการใช้ javascript ตรวจคำตอบอย่างง่าย)
  4. การใช้ cookie เก็บข้อมูล (โปรแกรมง่าย ๆ เพื่อเพิ่ม ลบ หรือ restore)
    Case at www.domaindlx.com/thaiall (บทเรียนยังอยู่ แต่ตัวอย่างภาคปฏิบัติใช้ไม่ได้แล้ว)
  5. การสุ่มเลขมาพิมพ์อย่างง่าย (ทดสอบการใช้คำสั่ง for, if, random)
  6. การทำ form ส่ง mail (วิธีที่ใช้ง่ายกว่า perl, asp จนน่าใจหาย)
    Case at www.worldzone.net/internet/thaiall (บทเรียนยังอยู่ แต่ตัวอย่างภาคปฏิบัติใช้ไม่ได้แล้ว)
  7. การสุ่มเลขมาพิมพ์อย่างง่าย (ทดสอบการใช้คำสั่ง for, if, random)
  8. การทำ form ส่ง mail (วิธีที่ใช้ง่ายกว่า perl, asp จนน่าใจหาย)
  9. การวาดนาฬิกาเข็มในรูปแบบ gif (ธรรมดา แต่ใช้ imagecreate ได้)

CMS + LMS
txt2gift.php ช่วยให้อาจารย์ที่มีข้อสอบนำ ข้อสอบจาก excel หรือ text file ไป import เข้า moodle 1.5 โดยใช้โปรแกรมของผมสร้างแฟ้มแบบ GIFT ให้ โปรแกรมนี้รับ text ที่มาจาก excel แล้วแปลงเป็น text แบบ GIFT ให้ท่าน copy ข้อมูลข้อสอบที่ได้จากการแปลง ไปสร้าง text file ใหม่ โปรแกรม moodle ก็จะนำไปใช้ได้ มีรายละเอียดอีกไม่มากนักที่ http://www.thaiall.com/e-learning/moodle.htm

หน่วยที่ 4 : รหัสต้นฉบับ จาก PERLPHPASP.COM
 PHP from book
1301.intro/index.php
1302.intro/intro01.php
1303.intro/intro02.php
1304.intro/intro03.php
1305.intro/intro04.php
1306.intro/intro05.php
1307.intro/intro06.php
1402.textupdate/index.php
1403.textupdate/create5.php
1404.textupdate/listfile.php
1405.textupdate/addnew.php
1406.textupdate/deldata.php
1407.textupdate/editdata.php
1408.textupdate/delfile.php
 PHP from book
1501.mysqlupdate/index.php
1502.mysqlupdate/step1connect.php
1503.mysqlupdate/step2crtdb.php
1504.mysqlupdate/step3select.php
1505.mysqlupdate/step4insert.php
1506.mysqlupdate/step5delete.php
1507.mysqlupdate/step6update.php
1508.mysqlupdate/step7drop.php
1601.phpgallery/gal.php
1602.phpgallery/galf.php
 PHP from book
1701.entrance/index.php
1702.entrance/connect.php
1703.entrance/entstdrestore.php
1704.entrance/enttyperestore.php
1705.entrance/entchkidstd.php
1706.entrance/entchkidtype.php
1707.entrance/entjoin.php
1708.entrance/entputmany.php
1709.entrance/crtqrydrp.php
1801.cartbasic/cartbasic.php
1802.cartbasic/cartbasicsave.php
1901.vdo/connect.php
1902.vdo/checkeid.php
1903.vdo/createvdo.php
1904.vdo/displayvdo.php
1905.vdo/reportvdo.php
1906.vdo/borrowvdo.php
2001.sticker/index.php
2002.sticker/putpic.php
2003.sticker/puttxt.php


หน่วยที่ 5 : รหัสต้นฉบับที่ขยายจากหน่วยที่ 2
short
1
:: Send mail by HTML format
    Sample : http://www.yonok.ac.th/burin/mailhtml.php
    <?
    # version 2 in html format : http://www.yonok.ac.th/burin/mailhtml.php
    # version 1 in text : http://www.isinthai.com/isinthai/sndform.php
    if (!isset($_POST{"mfrom"})) $_POST{"mfrom"} = "";
    if (!isset($_POST{"mto"})) $_POST{"mto"} = "";
    if (!isset($_POST{"msubj"})) $_POST{"msubj"} = "";
    if (!isset($_POST{"message"})) $_POST{"message"} = "";
    if (!isset($_POST{"redirect"})) $_POST{"redirect"} = "";
    if (!isset($_GET{"mfrom"})) $_GET{"mfrom"} = "";
    if (!isset($_GET{"mto"})) $_GET{"mto"} = "";
    if (!isset($_GET{"msubj"})) $_GET{"msubj"} = "";
    if (!isset($_GET{"message"})) $_GET{"message"} = "";
    if (!isset($_GET{"redirect"})) $_GET{"redirect"} = "";
    $mfrom = $_POST{"mfrom"} . $_GET{"mfrom"};
    $mto = $_POST{"mto"} . $_GET{"mto"};
    $msubj = $_POST{"msubj"} . $_GET{"msubj"};
    $message = $_POST{"message"} . $_GET{"message"};
    $redirect = $_POST{"redirect"} . $_GET{"redirect"};
    if (empty($redirect)) { $redirect = "http://www.yonok.ac.th"; }
    if (empty($message)) { $message = "<html><body bgcolor=red>
    <a href=http://www.thaiall.com>thaiall.com</a><hr color=white>hello
    </body></html>"; }
    if (empty($mto) || empty($msubj) || empty($mfrom)) {
      echo "<font face="courier new">";
      echo "<form action=mailhtml.php method=post>";
      echo ".. From : <input name=mfrom value='$mfrom' size=30><br>";
      echo ".... To : <input name=mto value='$mto' size=30><br>";
      echo "Subject : <input name=msubj value='$msubj' size=50><br>";
      echo "Messages:<br><textarea name=message rows=10 cols=80>$message";
      echo "</textarea> <input type=submit value='Send mail'>";
      echo "<br><input name=redirect type=hidden value=$redirect>";
      echo "</form>";
    } else {
      $msubj = "Subject _ ".$msubj;
      mail("$mto,burin@yonok.ac.th","$msubj",$message,"From: $mfrom\r\n"
      ."Reply-To: $mfrom\r\n"
      ."MIME-Version: 1.0\r\n"
      ."Content-Type: text/html;charset=windows-874\r\n"
      ."Content-Transfer-Encoding: 7bit\r\n"
      ."X-Priority: 1\r\n"
      ."X-Mailer: PHP/" . phpversion());
      // mail("$mto","$msubj",$message,"From: $mfrom\nX-Mailer: PHP/" . phpversion());
      echo "<html><head><meta http-equiv=Refresh content='50; URL=$redirect'>";
      echo "</head><body><font face="courier new"><pre>";
      echo "From    : $mfrom \n";
      echo "To      : $mto \n";
      echo "Subject : $msubj \n";
      echo "Message :<ul><font color=gray>" . htmlentities($message);
      echo "</ul></font><hr color=red>Your message sending : <b>Completely</b>\n";
      echo "Script developer : webmaster@thaiall.com\n";
    }
    ?>
    
short
2
:: Write image in JPEG format by GD JPEG supporting
    Sample : http://www.thaiall.com/php/testjpg.php
    
    <? # some server no support GD GIF but support GD JPEG. # you can check by phpinfo(); # test at http://www.lampang.go.th/webboard/securecode.php # test at http://www.thaiall.com/php/testjpg.php header("Content-type: image/jpeg"); $imagesize = 80; $myImage = ImageCreate($imagesize, $imagesize); $white = ImageColorAllocate($myImage, 255, 255, 255); $red = ImageColorAllocate($myImage, 255, 0, 0); ImageFill($myImage, 0, 0, $red); Imageinterlace($myImage, 1); Imagearc($myImage, 40, 30, 20, 10, 0, 359, $white); ImageLine($myImage, 5, 5, 70, 60, $white); Imagestring($myImage, 3, 5, 40, ("This กขค."), $white); Imagejpeg($myImage); Imagedestroy($myImage); ######## securecode.php ########### # $FILE=file ("topic.htm") ; # $key=count($FILE); # $key=ord(substr(crypt($key,$key),6,1)) * 100; # $key=$key + (ord(substr(crypt($key,$key),7,1))); # header("Content-type: image/jpeg"); # $myImage = ImageCreate(80, 20); # $white = ImageColorAllocate($myImage, 255, 255, 255); # $red = ImageColorAllocate($myImage, 255, 0, 0); # ImageFill($myImage, 0, 0, $red); # Imagestring($myImage, 5, 5, 5, "$key", $white); # Imagejpeg($myImage); # Imagedestroy($myImage); ?>
short
3
:: Listing of thumb nail and click to enlarge
    Sample : http://www.lampang.go.th/nwt
    <table width=100%>
    <?
    if (!isset($_GET["p"])) $_GET["p"] = 1;
    $i = 0;
    $dir_handle = opendir(".");
    while ($list = readdir($dir_handle)) {
      if (strtolower(substr($list,-5)) == "t.jpg") {
       $ar[$i]  = "<td><a href=../nw/".substr($list,0,6).".jpg>";
       $ar[$i] .= "<img src=$list border=0></a></td>";
       $last_modified = filemtime($list);  // Ex. Monday, 27th October, 2003 @ 02:59pm
       $ar[$i] .= " Last modified " . date("l, dS F, Y @ h:ia", $last_modified);
       $i = $i + 1;
      }
    }
    closedir($dir_handle);
    srand(time());
    $pp = 10;
    $end = $_GET["p"] * $pp;
    print "<table width=100%>";
    for ($k=($end - $pp);$k<$end;$k++) {
      // $j = rand() % $i;
      // print $ar[$j];
      print $ar[$k];
    }
    // echo (sprintf("%03d", 5) . strlen(sprintf("%03d", 5))); // 0053
    print "</table>";
    for ($c=1;$c<=($i / $pp);$c++) {
      print "<a href=?p=$c>$c</a> | ";
    }
    ?>
    
    Sample : http://www.thaiall.com/win/openphotodir.php <? # <meta http-equiv=refresh content="1;url=openphotodir.php"> $h = ""; $w = ""; $b = "bgcolor=#400000"; if (isset($_GET['height'])) $h = " height=".$_GET['height']; if (isset($_GET['width'])) $w = " width=".$_GET['width']; if (!isset($_GET['height']) && !isset($_GET['width'])) $w = " height=120"; if (isset($_GET['bgcolor'])) $b = " bgcolor=".$_GET['bgcolor']; ?> <body <?=$b;?>><font face="microsoft sans serif" size=6 color=yellow>OpenPhotoDir.php<br>Type : <a href=?>1</a> | <a href=?type=thumb&height=150>2</a> | <a href=?type=thumb&width=150>3</a> | <a href=?type=thumb&bgcolor=black>4</a> | <br><base target=_blank><font color=#dddddd> <? if (!isset($_GET['type'])) echo "<ol>"; $d = opendir("."); while ($list = readdir($d)) { if (strtolower(substr($list,-4)) == ".jpg" or strtolower(substr($list,-4)) == ".gif") { if (!isset($_GET['type'])) { echo "<li><a href=$list>$list</a> ". filesize($list) ." byte\n"; } else { echo "<a href=$list><img src=$list border=1 $h $w></a>\n"; } } } if (!isset($_GET['type'])) echo "</ol>"; ?> </body>
short
4
:: Array database of course description
    Sample : http://yn1.yonok.ac.th/catalog/subjdesc.php
    <html><head><title>Course description database</title></head>
    <body bgcolor=#ffffdd><font face="microsoft sans serif" size=0>
    <form action=subjdesc.php>
    แสดงรายวิชาทั้งหมด [<a href=subjdesc.php>แบบรายชื่อ</a>,
    <a href=subjdesc.php?codes=csv>แบบ CSV</a>]
    หรือค้นหาตามรหัสวิชา หรือคำอธิบายรายวิชา
    <br><input name=codes><input type=submit><br>
    </form>
    <?
    $d{'ACCT 100'}="การบัญชีทั่วไป~3(3-0)~~ศึกษา...";
    $d{'ACCT 201'}="หลักการบัญชี 1~3(3-0)~~ศึกษาเกี่ยว...";
    $d{'ACCT 202'}="หลักการบัญชี 2~3(3-0)~หลักการบัญชี 1 (ACCT 201)~ศึกษา...";
    if (isset($_GET['codes'])) { $c = $_GET['codes']; }
    if (isset($_POST['codes'])) { $c = $_POST['codes']; }
    if (strlen($c) == 0) { $c = "list"; }
    if (strlen($d{$c}) > 1) {
      $ds = explode("~",$d{$c});
      echo "<b>$c</b> : $ds[0] $ds[1]";
      echo "<ul><b>วิชาบังคับก่อน</b> : $ds[2]";
      echo "<dd>$ds[3]</ul>";
    } else {
      if ($c == "csv") {
        echo "<pre>";
        while( list ($k,$v) = each($d)) {
          $ds = explode("~",$d{$k});
          echo "$k,$ds[0],$ds[1],$ds[2],$ds[3]<br>";
        }
        echo "</pre>";
      } else {
        echo "<ul><ol>";
        while( list ($k,$v) = each($d)) {
          if ((strpos(strtolower($d{$k}),strtolower($c)) > 0) || _
             (strlen($c) == 0) || ($c == "list")) {
             $ds = explode("~",$d{$k});
             echo "<li><a href='?codes=$k'>$k</a> : $ds[0] $ds[1]";
          }
        }
        echo "</ol></ul>";
      }
    }
    // Code เพิ่มเติมเกี่ยวกับอาร์เรย์
    // $arr = array("thai", "siam", "lampang");
    // sort($arr);
    // reset($arr);
    // while (list($key, $value) = each($arr)) {
    //    echo "Key: $key; Value: $value<br>";
    // }
    // foreach ($arr as $key => $value) {
    //    echo "Key: $key; Value: $value<br>";
    // }
    ?>
    </body></html>
    
short
5
:: Security by word in image putting
    Sample : http://www.thaiall.com/php/secure.php
    <body>
    <?
    $ft = $_POST['keept']  % 5;
    if (($_POST['u'] == "a" && $_POST['p'] == "b")  && (
    ($ft == "0" && $_POST['w'] == "abc") ||
    ($ft == "1" && $_POST['w'] == "def") ||
    ($ft == "2" && $_POST['w'] == "oho") ||
    ($ft == "3" && $_POST['w'] == "love") ||
    ($ft == "4" && $_POST['w'] == "wow") ))
    { echo "ok : pass"; } else {
    $t = microtime() * 1000000;
    $img = $t % 5;
    echo "<img src=secure". $img .".jpg>";
    ?>
    <form action=secure.php method=post>
    Word in picture : <input name=w><br>
    User : <input name=u value="a"><br>
    Password : <input name=p value="b"><br>
    <input type=hidden name=keept value=<?=$t;?>><br>
    <input type=submit value="Check password">
    </form>
    <? } ?>
    </body>
    
short
6
:: 2 connection method of PHP+MDB in Windows
    Source Code : (empl.mdb 68 KB = empl :emplid as double,emplname as text,emplsalary as double)
    
      <body>Connection method of PHP+MDB in Windows<br>
    1. <a href=?connect=DSNLess&action=List>DSNLess+List</a> | <a href=?connect=DSNLess&action=Add1>DSNLess+Add1</a> | <a href=?connect=DSNLess&action=Delete99>DSNLess+Delete99</a><br>
    2. <a href=?connect=OdbcDSN&action=List>OdbcDNS+List</a> | <a href=?connect=OdbcDSN&action=Add1>OdbcDNS+Add1</a> | <a href=?connect=OdbcDSN&action=Delete99>OdbcDNS+Delete99</a><hr>
      <? if(!isset($_GET{'action'})) { $_GET["connect"] = "DSNLess"; $_GET["action"] = "List"; } else { $_GET["connect"] = $_GET{'connect'}; $_GET["action"] = $_GET{'action'}; } // DNSLess connection method if($_GET["connect"] == "DSNLess" ) { // วิธีนี้ไม่ต้องเข้าไปใน ODBC Data Sources $db_connection = new COM("ADODB.Connection"); $db_connstr="DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=".realpath("empl.mdb").";"; $db_connection->open($db_connstr); if ($_GET["action"] == "List") { $rs = $db_connection->execute("select * from empl"); $rs_fld0 = $rs->Fields(0); $rs_fld1 = $rs->Fields(1); while (!$rs->EOF) { print "$rs_fld0->value $rs_fld1->value <br>\n"; $rs->MoveNext(); } $rs->Close(); } if ($_GET["action"] == "Add1") { $rs = $db_connection->execute("insert into empl(emplid,emplname)values(99,'abc')"); print "Add1 : complete"; } if ($_GET["action"] == "Delete99") { $rs = $db_connection->execute("delete from empl where emplid =99"); print "Delete99 : complete (all where emplid=99)"; } $db_connection->Close(); } // OdbcDNS connection method // (Open DataBase connectivity & Data source name) // ต้องมี ODBC driver ในเครื่องนะครับ ปกติเครื่องที่ลง office น่าจะมี // Control panel, ODBC Data Sources, System DSN, Add, Access, empldsn, select, ... if($_GET["connect"] == "OdbcDSN" ) { $cnx = odbc_connect('empldsn','',''); if ($_GET["action"] == "List") { $SQL_Exec_String = "select * from empl"; $cur= odbc_exec( $cnx, $SQL_Exec_String ); while( odbc_fetch_row( $cur ) ) { $field1= odbc_result( $cur, 1 ); $field2= odbc_result( $cur, 2 ); echo "$field1 $field2 <br>\n"; } } if ($_GET["action"] == "Add1") { $SQL_Exec_String = "insert into empl(emplid,emplname)values(99,'abc')"; $cur= odbc_exec( $cnx, $SQL_Exec_String ); print "Add1 : complete"; } if ($_GET["action"] == "Delete99") { $SQL_Exec_String = "delete from empl where emplid =99"; $cur= odbc_exec( $cnx, $SQL_Exec_String ); print "Delete99 : complete (all where emplid=99)"; } } ?>
    เพราะนักศึกษาคนหนึ่งที่ผมเคยสอนคอมพิวเตอร์เบื้องต้น ถามเรื่องนี้ ทำให้ผมต้องศึกษาเพิ่มเติม แล้วนำมาเขียนไว้ที่นี่ เพราะเดิมผมไม่สนใจเรื่อง php+mdb
short
7
:: Open File From Internet (ดูดเว็บอื่นมาใช้งานเป็นเว็บเพจของเรา)
:: บาง Server ไม่ยอมให้ใช้ file() ดูดข้อมูลจากเว็บเพจนอกเครื่อง (Using remote files) เช่น thaiall.com เพราะใน php.in กำหนด allow_url_fopen เป็น off ถ้าเป็น on ก็จะไม่พบปัญหานี้ สามารถตรวจสอบด้วย phpinfo()
    <base href=http://www.youtube.com/>
    <?
    $ar = file("http://www.youtube.com");
    foreach ($ar as $value) {
       echo $value;
    }
    ?>
    ตัวอย่างนี้แสดงการดูดเว็บ http://www.youtube.com
    มาแสดงเป็นเว็บของเรา ถ้าจะ split หรือนับ line ก็ต้องเขียนโปรแกรมเพิ่ม เช่น $lines = split("\n", $multi-line-input);
    
short
8
:: ดูดบางส่วนของเว็บ โดยเลือกจาก keyword มาเท่าจำนวนบรรทัดที่ต้องการ
    Commnet : manager.co.th มี hit rate เยอะเกินไป Response Time ต่ำ ไม่เหมาะที่จะดูด
    <?
    $x = '<table cellspacing=0 cellpadding=2 width="100%" border=0>';
    $a = file("http://www.manager.co.th/Home/default.html");
    $xl = strlen($x);
    $found = 0;
    $l = 0;
    echo "คำที่ค้นหามีขนาด $xl ตัวอักษร\n";
    for($i=0;$i<count($a);$i++) {
     if (stristr($a[$i],$x)) {
       $found = 1;
     }
     if ($l <= 26 && $found == 1) {
       echo $a[$i]."\n";
       $l = $l + 1;
     }
    }
    ?>
    
    ตัวอย่างนี้แสดงการดูดเว็บ http://www.manager.co.th เพียงบางส่วน
    โปรแกรมนี้ใช้กับบาง server ไม่ได้ เพราะเขาไม่ยอมให้ใช้ฟังก์ชัน file() เช่น thcity.com เป็นต้น
    
short
9
:: ดูด Directory และเปลี่ยน Link ของ Google.com
    9.1 ดูด Directory ของ google
    Sample : http://www.thaiall.com/php/google.php
    <?
    $web = file("http://www.google.co.th/dirhp?hl=th&tab=gd&q=");
    $chk1 = '<table width=1% border=0 cellspacing=7 cellpadding=0 align=center>';
    $chk2 = "</table><br>";
    $found = 0;
    $first = 1;
    $l = 0;
    if (!isset($_GET['url'])) {
    echo "<body bgcolor=#ffffdd><b>ระบบ directory</b>\n";
    for($i=0;$i<count($web);$i++) {
     $r1 = split($chk1,$web[$i]);
     if (count($r1) > 1) $found = 1;
     if ($found == 1) {
       if ($first == 1) {
         echo $chk1;  # พิมพ์คำที่ค้นหาเป็นคำแรก
         $first = 0;
       }
       $r2 = split($chk2,$r1[1]);
       if (count($r2) > 1) {
        $u = $r2[0];
       } else {
        $u = $r1[1]; # กรณีหัว และท้ายไม่อยู่บรรทัดเดียวกัน
       }
       echo str_replace("http://directory.google.com/","?url=",$u);
     }
    } # end for
    } else {
    echo "<frameset><frame src=http://directory.google.com/" . $_GET['url'] . "></frameset>)";
    } # end if
    ?>
    
    9.2 ดูดจาก lovelampang.com มาไว้ใน thaiall.com
    <?
    $a = file("http://www.lovelampang.com/iblog.php");
    for($i=0;$i<count($a);$i++) {
      echo str_replace("<body","<base href=http://www.lovelampang.com/><body",$a[$i]);
      echo "\n";
    }
    ?>
    
    9.3 ดูด url ของ mp3 จากเว็บไซต์ของ encarta
    Sample : http://www.thaiall.com/listen/_cut.php
    <font size=6><b>โปรแกรมช่วยจับชื่อแฟ้มเสียงจากผลการสืบค้น
    <br>http://encarta.msn.com</b></font>
    <form action=_cut.php method=post>
    <input name=url size=90 value='http://encarta.msn.com/dictionary_1861582869/a.html'>
    <input type=submit>
    </form><br>
    <?
    if (isset($_POST['url'])) {
      $chk1 = "http://images.encarta.msn.com";
      $chk2 = ".mp3";
      $r = file($_POST['url']);
      $found = 0;
      for($i=0;$i<count($r);$i++) {
        $r1 = split($chk1,$r[$i]);
        if (count($r1) > 1) {
          $found = 1;
          $r2 = split($chk2,$r1[1]);
          $r3 = $r2[0];
        }
      }
      echo "<a href=".$chk1.$r3.$chk2.">mp3</a>";
    }
    ?>
    
    9.4 ดูดเว็บเพจของ ไอทีในชีวิตประจำวัน
    Sample : http://www.thaiall.com/itinlife/article.php
    ปรับปรุงมาจากโปรแกรมดูดเว็บที่ใช้กับ google.com จึงทำให้ดูเข้าใจง่ายขึ้น
    <table width=760 align=center><td bgcolor=#ffffdd>
    <?
    $web = file("http://www.thaiall.com/opinion/readonly.php?view=".$id);
    $chk1 = "<td bgcolor=white>";
    $chk2 = "</td></tr><tr><td align=right bgcolor=black>";
    $found = 0;
    $first = 1;
    $stop = 0;
    $l = 0;
    for($i=0;$i<count($web);$i++) {
     $r1 = split($chk1,$web[$i]);
     $r2 = split($chk2,$web[$i]);
     if (count($r1) > 1) $found = 1;
     if ($found == 1 && $stop == 0) {
       if ($first == 1) {
         echo "<dd>$r1[1]"; // พิมพ์ครั้งแรก เมื่อพบคำแรก
         $first = 0;
       } else {
         if (count($r2) > 1) $stop = 1;
         echo "<dd>$r2[0]"; // พิมพ์ที่เหลือ ก่อน $stop = 1
       }
     }
    }
    ?>
    </td></table>
    
    
short
10
:: โปรแกรม upload แฟ้มข้อมูลเข้า server อย่างง่าย 3 แบบ
    <! up.php โปรแกรม upload แฟ้มข้อมูลเข้าไปในเครื่องบริการ>
    <form action=up.php enctype="multipart/form-data" method=post>
    <input type=file name=uploadfile>
    <input type=submit>
    </form>
    <?
    if (isset($_FILES["uploadfile"]["name"])) {
      if(copy($_FILES["uploadfile"]["tmp_name"],"./".$_FILES["uploadfile"]["name"]))
        echo "upload : process";
      else
        echo "upload : error";
    }
    ?>
    
    <! upmany.php สัจจามาถามว่า ทำอย่างไร up หลายแฟ้ม ถ้ารับคำสั่งมาจากอาร์เรย์> <form action=upmany.php method=post enctype="multipart/form-data"> <input name=x value='a'><br> <? $tot = 3; for($i=1;$i<=$tot;$i++) { echo "<input type=file name=uploadfile$i><br>"; } ?> <input type=submit> </form> <? if (!empty($_FILES["uploadfile1"]["name"])) { echo $_POST{'x'}."<br>"; for($i=1;$i<=$tot;$i++) { echo "<br>Upload : " . $_FILES["uploadfile$i"]["name"]; if(copy($_FILES["uploadfile$i"]["tmp_name"],"./".$_FILES["uploadfile$i"]["name"])) echo " ok"; else echo " error"; } } ?>
    <! upn.php ส่งแฟ้มเข้าแบบกำหนดชื่อ> <form action=upn.php enctype="multipart/form-data" method=post> <input name=new value="new.jpg"> <input type=file name=uploadfile> <input type=submit> </form> <? if (isset($_POST["new"])) if (copy($_FILES["uploadfile"]["tmp_name"],"./".$_POST["new"])) echo "upload : completely"; ?>
short
11
:: โปรแกรม 3 โปรแกรม แสดงการทำงานของ cookie
    <! x.php โปรแกรมที่มีฟอร์มรับค่าเข้าตัวแปร uname แล้วส่งให้ y.php แบบ get>
    <body>
    <form action=y.php method=get>
    <input name=uname size=40><br>
    <input type=submit>
    </form>
    </body>
    
    <! y.php โปรแกรมนำค่าที่รับมาจาก get เก็บลง cookie ไว้ 1 ชั่วโมง> <! keep in c:\windows\temporary internet files\ > <? if (isset($_GET["uname"])) { setcookie("uname",$_GET['uname'],time() + 3600); echo "keep ok"; } ?> <body> <a href=z.php>z.php</a> </body>
    <! z.php โปรแกรมนำค่าจาก cookie มาแสดงทางจอภาพ> <body> <?=$_COOKIE['uname']; ?> </body>
short
12
:: โปรแกรม counter อย่างง่าย ด้วย session
:: เป็นการนับแยก ของผู้เข้าชมแต่ละคน เพราะผมเข้าคนละเครื่อง ก็นับกันคนละเลข ไม่ได้นับต่อของคนอื่น ๆ
:: หากไม่กำหนดอะไรเพิ่มเติมค่าของ session จะหมดอายุตามค่า session.cache_expire ที่แสดงใน phpinfo( )
:: พบ server 2 ตัวที่ต้องกำหนด session_save_path ไม่งั้น error คือ hypermart.net กับ sahapat.co.th
:: ตัวอย่างมากมายเรื่อง authentication ที่ http://www.tutorialized.com/tutorials/PHP/User-Authentication/1
    Sample : http://www.yonok.ac.th/burin/countersession.php
    <body>
    <?
    # http://th2.php.net/manual/en/ref.session.php
    # http://th2.php.net/manual/en/function.session-cache-expire.php
    # session_start() ต้องมีในทุกเว็บเพจที่ต้องการใช้ตัวแปรแบบ session
    # session_save_path("/var/www/cgi-bin/tmp"); สร้างห้อง tmp ไว้เก็บ session สำหรับ Linux
    # session_save_path("f:/203.130.156/sahapat/tmp"); ตัวอย่างสำหรับ windows
    session_start();
    if (!isset($_SESSION['count'])) {
      $_SESSION['count'] = 1;
    } else {
      $_SESSION['count']++;
    }
    # for delete the session variable
    # session_unregister('count');
    ?>
    <br>
    Hello visitor, you have seen this page <?=$_SESSION['count']; ?> times.
    </body>
    :: เพราะผมเคยใช้ session ใน hypermart.net ไม่ได้ และต.ค.48 อ.ถนอมก็บ่นว่า server เขาไม่รับ
    :: พอสืบค้นก็พบข้อมูลจาก http://www.hypermart.net/knowledgebase/read_article.bml?kbid=600
    :: ทำให้รู้ว่าบาง server ต้องกำหนดห้องเก็บ session เอง เพื่อ Security
    :: ถ้าใช้ session ไม่ได้ ก็ให้กำหนด session_save_path ตาม $_ENV["DOCUMENT_ROOT"]
    :: เช่น session_save_path("/home/users/web/[bucket]/[home dir]/cgi-bin/tmp"); ก่อน session_start();
    
short
13
:: โปรแกรมจัดตารางสอบอย่างง่าย (นักเรียนลงทะเบียนคนละ 3 วิชา แต่หลังจัดตารางสอบจะมีชั่วโมงสอบ 3 Hrs คือ ac, be, d)
:: อาจารย์หญิงท่านหนึ่งที่ผมรู้จักใช้ theory การจัดตารางสอบที่มีการทำ generation พร้อมกับ constrain อีกมากมาย
:: ผมลองเขียนดู แต่เอาแบบง่าย ๆ ไม่มีเงื่อนไข จัดให้ลง block ที่เตรียมไว้ ก็ถือว่าใช้ได้แล้ว
    Source Code : http://www.thaiall.com/php/timetabling.php
    

    <? if (!isset($_POST['regist'])) { echo "ระบบจัดตารางสอบอย่างง่าย ของนักเรียน 3 คนที่ลงทะเบียนคนละ 3 วิชา"; echo "<form action=timetabling.php method=post>"; echo "<textarea name=regist rows=10 cols=60> 1,a,b,d, 2,a,d,e, 3,b,c,d, </textarea><br><input type=submit value='Timetabling'>"; echo "</form>"; exit; } // แสดงข้อมูลที่รับมาจาก form echo "<pre>แสดงรายวิชาที่นักเรียนแต่ละคนลงทะเบียนเรียน \n"; $student = split("\n",$_POST['regist']); foreach($student as $one) { $subj = split(",",$one); for($i=0;$i<count($subj);$i++) echo $subj[$i]; } // นำข้อมูลแต่ละคน มาแยกเก็บแยกวิชา เช่น a,1,2 ลงตัวแปร $s เพื่อใช้ในการจัดตารางสอบ foreach($student as $one) { $subj = split(",",$one); for($i=1;$i<count($subj)-1;$i++) { if (!isset($s[$subj[$i]])) $s[$subj[$i]] = $subj[$i] . ","; $s[$subj[$i]] = $s[$subj[$i]] . $subj[0] . ","; } } // อ่าน $s มาจัดลงตัวแปร $sub เพื่อใช้อ้างวิชาที่ได้ เช่น $sub[0] หมายถึงวิชา "a" echo "<hr>แสดงชื่อนักเรียนที่ลงทะเบียนในแต่ละวิชา"; $i = 0; foreach($s as $sepsubj) { $sepagain = split(",",$sepsubj); $sub[$i] = $sepagain[0]; $i = $i + 1; echo $sepsubj . "\n"; // $sepsubj เก็บรหัสนักศึกษาในแต่ละวิชา } // จัดกลุ่มตามวัน โดยใช้ while ซ้อน for และตรวจสอบความซ้ำซ้อน $end = 0; $i = 0; while ($end == 0) { $outday = 0; for($j=0;$j<count($sub);$j++) { if (strlen($s[$sub[$j]]) > 2 && $outday == 0) { $day[$i] = $sub[$j].","; $base = $s[$sub[$j]]; $s[$sub[$j]] = ""; $outday = 1; } } for($j=1;$j<count($sub);$j++) { $sbase = $s[$sub[$j]]; $ssubj = split(",",$sbase); $found = 0; for($k=1;$k<count($ssubj)-1;$k++) { if (stristr($base,$ssubj[$k])) $found = 1; } if ($found == 0 && count($ssubj) > 1) { $s[$sub[$j]] = ""; $day[$i] = $day[$i] . $sub[$j] . ","; } } $i++; $end = 1; foreach ($s as $checksubj) { if (strlen($checksubj) > 2 ) $end = 0; } } echo "<hr>"; // แสดงผลการจัดตารางแล้ว for($i=0;$i<count($day);$i++) { echo "ชั่วโมงที่ "; echo $i + 1; echo " สอบวิชา " . $day[$i] . "\n"; } ?>
short
14
:: วาดกราฟอย่างง่าย จากข้อมูลผ่าน querystring หรือ get
:: ศูนย์ข้อมูลจังหวัด ต้องการเขียนกราฟใน webpage ผมจึงเขียนโปรแกรมง่าย ๆ ขึ้นมาให้นำไปปรับปรุง
    Source Code : http://www.thaiall.com/php/barchart.php?b1=50&b2=100&b3=120&b4=30
    14.1 เขียน barchart.php (ปรับปรุง : 5 กรกฎาคม 2548 เพราะเดิมลืมเครื่องหมาย $)
    
    <?
    if (!isset($_GET{'b1'})) {
    $sample = "barchart.php?b1=50&b2=100&b3=120&b4=30";
    echo "<a href=$sample>$sample</a>";
    echo "<br>or <iframe src=$sample height=200 width=200></iframe>";
    echo "<br>or <img src=$sample>";
    echo "<br>Can test at http://www.yonok.ac.th/burin/php/$sample";
    } else {
    header("Content-type: image/png");
    $width = 200;
    $height = 150;
    $bw = 20; // barwidth
    $im = @imagecreate ($width,$height);
    $white = ImageColorAllocate($im, 255, 255, 255);
    $red = ImageColorAllocate($im, 255, 0, 0);
    $yellow = ImageColorAllocate($im, 255, 255, 0);
    $black = ImageColorAllocate($im, 0, 0, 0);
    imagefill($im, 0, 0, $red);
    imagefilledrectangle($im, 5, 5, $width - 5, $height - 5, $black);
    imageline($im, 5, $height - 3, $width - 5, $height - 3, $yellow);
    imagestring ($im, 4, 5, 5, "only in english", $white);
    for ($i=1;$i<=10;$i++) {
    if (isset($_GET{"b".$i})) {
     imagerectangle($im,$bw * $i,$height - $_GET{"b".$i},$bw * $i + 8,$height - 20,$white);
     imagestring ($im, 0, $bw * $i, $height - 18,  $_GET{"b".$i}, $yellow);
    }
    }
    imagepng ($im);
    imagedestroy($im);
    }
    ?>
    
    14.2 ทดสอบเขียนภาพอีกแบบหนึ่ง
    <?
    header("Content-type: image/png");
    if (!isset($_GET{"string"})) $string = "?string=none"; else $string = $_GET{"string"};
    $font  = 4;
    $width = 200;
    $height = 150;
    $im = @imagecreate ($width,$height);
    //white background
    $background_color = imagecolorallocate($im, 255, 255, 255);
    //black text
    $text_color = imagecolorallocate ($im, 0, 0, 0);
    $white = ImageColorAllocate($im, 255, 255, 255);
    $red = ImageColorAllocate($im, 255, 0, 0);
    imagefill($im, 0, 0, $red);
    imagestring ($im, $font, 0, 0,  $string, $text_color);
    imageinterlace($im, 1);
    imagearc($im, 40, 30, 20, 10, 0, 359, $white);
    imageline($im, 5, 5, 70, 60, $white);
    imagepng ($im);
    imagedestroy($im);
    ?>
    
    14.3 ทดสอบเรื่องใช้ php อ่านแฟ้ม .gif มาแสดง
    <?
      header("Content-Type: image/gif");
      $fn=fopen("ta5.gif","r");
      fpassthru($fn);
    ?>
    
    14.4 อ่านแฟ้มภาพภาษาไทยใน linux เพราะใช้ชื่อแฟ้มภาษาไทยตรง ๆ ไม่ได้
    <?
    // http://www.thaiall.com/lampangmap/img.php?f=ลำปาง1
    $f = "ta6.jpg";
    if(isset($_GET["f"]) && file_exists($_GET["f"].".jpg")) { $f = $_GET["f"].".jpg"; }
    if($fn=fopen($f,"rb")) {
    if(filesize($f) < 200000) {
    	header("Content-Type: image/png");
    	header("Content-Length: " . filesize($f));
    	while(!feof($fn)){
    	  print(fread($fn, 1024));
    	  flush();
    	}
    	fclose($fn);
    } else echo "over limit of file size";
    } 
    ?>
    14.5 สำหรับเปิดแฟ้ม .pdf ที่มีชื่อไทยใน fedora เพื่อแก้ปัญหาการมีชื่อแฟ้มเป็นภาษาไทย
    <?
    if(!isset($_GET["file"])) {
        $f = "ทดสอบ.pdf";
        echo "<a href=openpdf.php?file=". urlencode($f) . " target=_blank>$f</a>";	
        echo "<form action=openpdf.php method=get target=_blank>
        <input name=file size=60 value=$f><br><input type=submit></form>";
        exit;
    }
    $filename = $_GET["file"];
    header('Content-type: application/pdf');
    header('Content-Disposition: inline; filename="foo.pdf"');
    readfile($filename); 
    ?>
    14.6 ซ้อนภาพแบบ Transparent
    <?
    $dest = imagecreatefromgif('d.gif');
    $src = imagecreatefromgif('s.gif');
    $bg_color = imagecolorat($src, 1,1);
    imagecolortransparent($src, $bg_color);
    imagecopymerge($dest, $src, 50, 80, 0, 0, 100, 200, 300);
    header('Content-Type: image/gif');
    imagegif($dest);
    imagedestroy($dest);
    imagedestroy($src);
    ?>
    14.7 การแสดง icon เป็นผลจากการตรวจสอบแฟ้ม
    ใช้งานที่ : http://www.thaiall.com/me/lyric.htm
    <?
    header("Content-Type: image/png");
    if (isset($_GET["name"]) && file_exists($_GET["name"] . ".mid")) 
      $fn=fopen("1.png","r");
    else
      $fn=fopen("0.png","r");
    fpassthru($fn);
    ?>
    
short
15
:: การเชื่อมต่อกับ MsSQL server (Access to MSSQL, PHP.net Guide)
    <?
    // $msconnect = mssql_connect("172.16.20.81:1433","sa","");
    $msconnect = mssql_connect("MyServer70","sa","");
    $msdb=mssql_select_db("Northwind",$msconnect);
    $msquery = "select firstname,lastname from employees";
    $msresults= mssql_query($msquery);
    echo "<ol>";
    while ($row = mssql_fetch_array($msresults)) {
      echo "<li>" . $row['firstname'] . " " . $row['lastname'] . "\n";
    }
    echo "</ol>";
    ?>
    
short
16
:: Online User Counter (no mysql)
:: โปรแกรมนับผู้ใช้ที่กำลัง online อยู่ แบบใช้ mysql มีมากมาย แต่ของผมใช้ text file ทดสอบแล้วใน thaiabc3e.exe
    ขณะนี้ online : <?
    $gap = 60; // 60 seconds
    $t   = $_SERVER["REMOTE_ADDR"].",".time()."\n";
    $f   = "countuser.txt";
    $c   = 0;
    $new = 1; // ตั้งไว้ก่อนว่าเป็นคนใหม่
    if (file_exists($f)) {
      $fr=file($f);
      $fw=fopen ($f,"w");
      foreach ($fr as $value) {
         $ft = split(",",$value);
         if ($ft[0] == $_SERVER["REMOTE_ADDR"]) {
           fputs ($fw,$_SERVER["REMOTE_ADDR"].",".time()."\n");
           $c = $c + 1;
           $new = 0;
         } else {
           if ((time() - $gap) < $ft[1]) {
             fputs ($fw,$value);
             $c = $c + 1;
           }
         }
      }
      if ($new == 1) {
        fputs ($fw,$t);
        $c = $c + 1;
      }
      echo $c;
      fclose ($fw);
    } else {
      $fw=fopen ($f,"w");
      fputs ($fw,$t);
      fclose ($fw);
      echo "1";
    }
    ?> คน
    
short
17
:: สุ่มเลขไม่ซ้ำ แบบใช้ in_array
:: วิธีสุ่มเลขไม่ซ้ำให้ได้เลข 10 ตัวคือ 0 - 9
:: ถ้าไม่ใช้ in_array จะมี loop อีกตัวหนึ่ง สำหรับเช็คซ้ำ .. ซึ่งเป็นวิธีที่ผมใช้ตามปกติ
    <?
    srand(time());
    $num = 10;
    $a = array();
    while (count($a) < $num) {
      $n = rand() % $num;
      if (!in_array($n, $a)) array_push($a,$n);
    }
    for ($i=0;$i<$num;$i++) echo $a[$i]."<br>";
    ?>
    
short
18
:: Bad Word Blockinging (หาคำที่ไม่สุภาพ แล้วเปลี่ยน)
    <body>
    <form action=bad.php method=post>
    <textarea name=word rows=5 cols=50>
    แดงบอย น้อย ขาวดำ ก็มี
    ดาว ดำ ดีดี สุภาพดำนะไม่ดี
    </textarea><input type=submit></form>
    <?
    $bi=-1;
    $bi++; $bad[$bi]="ทอง";
    $bi++; $bad[$bi]="ขาว";
    $bi++; $bad[$bi]="ดำ";
    for($b=0;$b<=$bi;$b++)
    $_POST["word"] = str_replace($bad[$b],"..",$_POST["word"]);
    echo $_POST["word"];
    ?>
    </body>
short
19
:: Redirection Header (จาก www.yonok.ac.th)
    <?
    if (isset($_GET['codes']))
    header("Location: http://yn1.yonok.ac.th/catalog/subjdesc.php?codes=" . $_GET['codes']);
    else
    header("Location: http://yn1.yonok.ac.th/catalog/subjdesc.php");
    ?>
short
20
:: Encode and Decode
:: เข้ารหัส URL แก้ปัญหา Internal Server Error ในบางกรณีได้
    <pre>
    <?
    if (!isset($_POST["ch"])) $a = "<a title=test>ทดสอบ/aaa</a> // \\ // \\";
    else $a = $_POST["ch"];
    // Normal Output
      echo $a."\n";
      # Output: ทดสอบ/aaa // \ // \
    // Un-quote string quoted with addslashes()
      echo stripslashes($a)."\n";
      # Output: ทดสอบ/aaa //  //
    // Quote string with slashes
      echo addslashes($a)."\n";
      # Output: ทดสอบ/aaa // \\ // \\
    // URL-encodes string
      echo urlencode($a)."\n";
      # Output: %3Ca+title%3Dtest%3E%B7%B4%CA%CD%BA%2Faaa%3C%2Fa%3E+%2F%2F+%5C+%2F%2F+%5C
    // Decodes URL-encoded string
      echo urldecode(urlencode($a))."\n";
      # Output: ทดสอบ/aaa // \ // \
    // Convert special characters to HTML entities
      echo htmlspecialchars($a)."\n";
      # Output: <a title=test>ทดสอบ/aaa</a> // \ // \
    // Convert all applicable characters to HTML entities
      echo htmlentities($a)."\n";
      # Output: <a title=test>?????/aaa</a> // \ // \
    // Encodes data with MIME base64
      echo base64_encode($a)."\n";
      # Output: PGEgdGl0bGU9dGVzdD63tMrNui9hYWE8L2E+IC8vIFwgLy8gXA==
    // Decodes data encoded with MIME base64
      echo base64_decode(base64_encode($a))."\n";
      # Output: ทดสอบ/aaa // \ // \
    // One-way string encryption (hashing) (ผลไม่ซ้ำกัน)
      echo crypt($a)."\n";
      # Output: $1$RL..GJ..$HzbDnURKr6iBOL1txhwk2/
      # EX. if (crypt($user_input, $passwd) == $passwd) echo "OK";
      # EX. if (crypt($_GET["p"],"$1$01..Hv/") == "$1$01..Hv/") { }
    ?>
    <form action="" method=post><input name=ch><input type=submit></form>
    </pre>
short
21
:: Each _SESSION, _SERVER, _ENV
:: แสดงข้อมูลทั้งหมดในตัวแปร Session หรือตัวแปร Server
    <?
    # ใช้ session_save_path ในกรณีที่ server บังคับให้ใช้ เช่น hypermart.net
    # session_save_path("/var/www/cgi-bin/tmp"); สร้างห้อง tmp ไว้เก็บ session เป็นต้น
    session_start();
    $_SESSION["a"] = 5;
    foreach ($_SESSION as $k=>$v) {
      echo $_SESSION["$k"];
    }
    foreach ($_SERVER as $k=>$v) {
      echo $k . $_SERVER["$k"];
    }
    foreach ($_ENV as $k=>$v) echo $k." = ".$v."<br>";
    phpinfo();
    ?>
    
    Testing of session.php
    <?
    session_start();
    if (isset($_SESSION["aaa"])) {
      echo $_SESSION["aaa"] . "<br>";
      if (isset($_GET["delete"])) {
        session_unset();
        session_destroy();
        header("location: session.php");
      }
    }
    if (isset($_GET["create"])) {
      $_SESSION["aaa"] = "aaa";
      header("location: session.php");
    }
    ?>
    <a href=?create=yes>?create=yes</a>
    <a href=?delete=yes>?delete=yes</a>
    
short
22
:: MySQL Manage (insert, delete, update, select)
:: ถ้าพบปัญหา ?? ต้องใช้ set names tis620 ทั้งตอน insert และ select
    <?
    $host     = "localhost";
    $db       = "test";
    $tb       = "testtb";
    $user     = "root";
    $password = "";
    ###########################
    if (isset($_POST["action"])) {
     if ($_POST["action"] == "insert") {
      $query = "insert into $tb (id,name) values (". $_POST["id"] .",'". $_POST["name"] ."')";
     }
     if ($_POST["action"] == "delete") {
      $query = "delete from $tb where id =". $_POST["id"];
     }
     if ($_POST["action"] == "update") {
      $query = "update $tb set name='".$_POST["name"] ."' where id =". $_POST["id"];
     }
     $connect = mysql_connect("$host","$user","$password");
     mysql_query("set names tis620"); // การเพิ่มบรรทัดนี้ ทำให้ข้อมูลใน mysql เก็บถูกต้อง
     $result = mysql_db_query($db,$query);
     if ($result) echo "<br>". $_POST["action"] ." OK<br>"; else exit;
     mysql_close($connect);
    }
    ###########################
    $query    = "select * from $tb";
    $connect = mysql_connect("$host","$user","$password");
    mysql_query("set names tis620"); // การเพิ่มบรรทัดนี้ ทำให้ดึงข้อมูลมาแสดงอย่างถูกต้อง
    $result = mysql_db_query($db,$query);
    if ($result) echo "<br>OK<br>"; else exit;
    while ($object = mysql_fetch_object($result)) {
      foreach ($object as $o) echo $o." ";
      # echo $object->cust . "  " . $object->custname;
      echo "<br>";
    }
    echo "Total records : ".mysql_num_rows($result);
    mysql_close($connect);
    ###########################
    ?>
    <form action=? method=post>
    <b>Insert</b><br>id : <input name=id><br>name : <input name=name><br>
    <input type=submit value=insert name=action>
    </form>
    <form action=? method=post>
    <b>Update</b><br>id : <input name=id><br>name : <input name=name><br>
    <input type=submit value=update name=action>
    </form>
    <form action=? method=post>
    <b>Delete</b><br>id : <input name=id><br>
    <input type=submit value=delete name=action>
    </form>
short
23
:: แก้ปัญหาภาษาไทยเป็น ??? เมื่ออ่านข้อมูลจาก MySQL
:: ทุกครั้งที่อ่านข้อมูล จึงต้องเพิ่ม mysql_query .. เพื่อกำหนดภาษาเป็น tis620 (ทราบจาก phpconcept.com)
:: คัดลอก SQL ใน Notepad ไปใส่ใน MySQL-Front เป็น ??? พอเปลี่ยนเป็น wordpad ไม่มีปัญหาเรื่อง ??? (w2003)
    <?
    // http://www.phpconcept.com/content/view/21/28/
    $host     = "localhost";
    $db       = "db";
    $tb       = "phpbb_users";
    $user     = "admin";
    $password = "p";
    $query    = "select * from $tb";
    ###########################
    $connect = mysql_connect("$host","$user","$password");
    // $charset = "set character_set_results=tis620";
    $charset = "set names tis620";
    mysql_query($charset) or die('Invalid query: ' . mysql_error());
    $result = MySQL_db_query($db,$query);
    while ($object = MySQL_fetch_object($result)) {
       echo $object->username . "<br>";
    }
    mysql_close($connect);
    ?>
+ แก้ปัญหาภาษาไทย เมื่อพิมพ์ภาษาไทยใน phpmyadmin แล้วออกเป็น ???
- ให้ทำตอนเริ่มต้นสร้างตาราง หรือ backup ข้อมูลไว้ก่อน เพราะถ้ามีข้อมูลมาก ๆ อาจมีปัญหา
- เปลี่ยน การเรียงลำดับในแต่ละ field จาก latin1_swedish_ci เป็น tis620_thai_ci
- ใน php script ต้องเพิ่ม mysql_query("set names tis620"); ต่อจาก mysql_connect( .. );
- วิธีนี้ไม่ได้แก้ปัญหาภาษาไทยในข้อมูลเดิม แต่จะไม่มีปัญหากับข้อมูลใหม่ที่เพิ่ม หรือแก้ไข
short
24
:: ตรวจ Link ในเว็บเพจที่ต้องการ
:: รุ่นนี้ยังไม่เช็ค link ปลายทาง เพียงแต่บอกว่า เว็บเพจนั้นมี link อะไรบ้าง
:: ลองทดสอบดูได้ ที่ linkchk1.php
    <?
    $url = "http://lampang.thcity.com/face/indexo.html";
    if (isset($_POST["url"])) {
      $url = strtolower($_POST["url"]);
      $web = file($url);
      echo "<ol>";
      for($i=0;$i<count($web);$i++) {
       $web[$i] = strtolower($web[$i]);
       $found = 0;
       $r1 = split("href=",$web[$i]);
       if (count($r1) > 1) $found = 1;
       if ($found == 1) {
         $r2 = split('[ >]',$r1[1]);
         $tag = $r2[0];
         echo "<li>";
         if (substr($r2[0],0,4) != "http")
           echo "<font color=red>$tag</font>\n"; else  echo $tag."\n";
       }
      }
      echo "</ol>Total Line : ". count($web);
    }
    echo "<form action='' method=post><input name=url value='$url' size=60>
    <input type=submit></form>";
    ?>
short
25
:: ฟังก์ชัน กับการจับเวลาเว็บเพจ
:: ทำให้โปรแกรมเป็นระเบียบ เขียนได้ง่าย และอ่านง่าย
:: เขียนโปรแกรมจับเวลาเว็บเพจ แบบใช้ฟังก์ชัน
    <?
    // global $x; declare here, can not used in function
    $start = 0;
    xtime("start");
    for($i=1;$i<=10;$i++) echo "$i<br>";
    echo xtime("stop");
    // =======================
    function xtime ($action) {
      global $start;
      list($u,$s) = split(" ",microtime());
      $n = $s + $u;
      if ($action == "start")
        $start = $n;
      else
        return ($n - $start);
    }
    ?>
short
26
:: จัดการข้อมูลในมายเอสคิวแอล แบบแยก (my01.htm, my01.php)
    my01.htm
    <form action=my01.php method=post>
    <input name=a><input name=b><br>
    <input type=radio value=i name=c>insert<br>
    <input type=radio value=d name=c>delete<br>
    <input type=radio value=u name=c>update<br>
    <input type=radio value=s name=c>select<br>
    <input type=submit>
    </form>
    
    my01.php <? # mysql> use test; # mysql> create table abc(a1 int,a2 varchar(10)); $c = mysql_connect("127.0.0.1:3306","root",""); if ($_POST["c"] == "i") $sql = "insert into abc values(".$_POST["a"].",'".$_POST["b"]."')"; elseif ($_POST["c"] == "d") $sql = "delete from abc where a1=".$_POST["a"]; elseif ($_POST["c"] == "u") $sql = "update abc set a2='".$_POST["b"]."' where a1=". $_POST["a"]; elseif ($_POST["c"] == "s") $sql = "select * from abc"; $r = mysql_db_query("test",$sql); if ($_POST["c"] == "s") while ($o = mysql_fetch_object($r)) echo "$o->a1 $o->a2 <hr>"; else echo $sql; ?>
short
27
:: คลายแฟ้ม .zip ด้วย PHP (Zip Management with PHP)
:: http://pecl.php.net/package/zip
:: http://th.php.net/manual/en/ref.zip.php
:: http://www.w3schools.com/php/php_ref_zip.asp
:: ลบ ; หน้า extension=php_zip.dll ใน php.ini ออก มีผลให้ phpinfo แสดง Zip Support เป็น enabled
    <?
    // unzip( $zipfile, $destination_folder )
    // สร้างห้อง c:\xxx ให้ใหม่ เมื่อไม่ถูกสร้างไว้
    unzip('c:\\test.zip','c:\\xxx\\');
    echo ": ok";
    function unzip($file, $path) {
    $zip = zip_open($file);
    if ($zip) {
    while ($zip_entry = zip_read($zip)) {
      if (zip_entry_filesize($zip_entry) > 0) {
        // str_replace must be used under windows to convert "/" into "\"
        $complete_path = $path.str_replace('/','\\',dirname(zip_entry_name($zip_entry)));
        $complete_name = $path.str_replace ('/','\\',zip_entry_name($zip_entry));
        if(!file_exists($complete_path)) {
          $tmp = '';
          foreach(explode('\\',$complete_path) AS $k) {
            $tmp .= $k.'\\';
            if(!file_exists($tmp)) mkdir($tmp, 0777);
          }
        }
        if (zip_entry_open($zip, $zip_entry, "r")) {
          $fd = fopen($complete_name, 'w');
          fwrite($fd, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
          fclose($fd);
          zip_entry_close($zip_entry);
        }
      } // end of if
    } // end of while
    zip_close($zip);
    } // end of if
    } // end of function
    ?>
    
short
28
:: Shell Command หรือ shell_exec()
:: ถ้าใน php.ini กำหนดว่า safe_mode = On จะทำให้ใช้ shell_exec ไม่ได้ ต้องเปลี่ยนเป็น safe_mode = Off
    <?
    echo "<br>".date("d/m/Y H:i:s"); // 13/07/2006 18:29:00
    echo "<br>".time();  // 1152185502
    echo "<br>".microtime(); // 0.23212200 1152185502
    echo "<br>". ( microtime() + microtime() ); // 0.464397
    echo "<pre><font face="courier new">";
    $cmd =`type c:\\autoexec.bat`;
    echo "<hr>$cmd";
    $cmd =`echo dir %WINDIR% > a.bat`;
    echo "<hr>$cmd";
    $cmd =`type a.bat`;
    echo "<hr>$cmd";
    $cmd =`a.bat`;
    echo "<hr>$cmd";
    $cmd =`dir`;
    echo "<hr>$cmd";
    $cmd = shell_exec("echo dir %WINDIR% > b.bat");
    $cmd = shell_exec("dir b.bat");
    echo "<hr>$cmd"; // 17 Bytes
    $cmd = shell_exec('del b.bat');
    $cmd = shell_exec('dir b.bat');
    echo "<hr>$cmd";
    ?>
short
29
:: เพิ่ม Linux User ผ่าน shell_exec
:: น้องคนหนึ่งโทรถามเรื่อง ssh authentication กับ php เพื่อใช้ useradd ในสิทธิ์ของ root
:: Linux ของผมไม่อนุญาติให้เชื่อมต่อผ่าน ssh จึงต้องใช้ shell_exec กับการจัดการ sudoers แทน แล้งส่งให้ php ประมวลผล
:: ถ้าใน php.ini กำหนดว่า safe_mode = On จะทำให้ใช้ shell_exec ไม่ได้ ต้องเปลี่ยนเป็น safe_mode = Off
    $host = "127.0.0.1" ;
    $output = shell_exec("ping -c1 $host"); 
    echo "<pre>$output</pre>";
    $user = "hello";
    $pass = "wow";
    echo shell_exec("sudo -u root -S /usr/sbin/useradd $user");
    echo shell_exec("echo $pass |sudo -u root -S /usr/bin/passwd $user --stdin");
    echo shell_exec("id $user");
    วิธีทำให้ใช้ sudo และ useradd ด้วยการแก้ไขแฟ้ม /etc/sudoers
    - เปลี่ยนสิทธิ์จาก 440 เป็น 777 
    - เปิดแฟ้ม /etc/sudoers ด้วย vi แล้วแก้ให้เลิกถามรหัสผ่านเมื่อใช้ sudo
    - เพิ่ม apache ALL= NOPASSWD: /usr/sbin/useradd, /usr/bin/passwd	
    - ต้องเปลี่ยนกลับเป็น 440 จึงจะสั่ง script ให้ทำงานได้
    วิธีทำให้ใช้ shell_exec ไม่ได้
    
    ถ้าผู้ดูแลระบบไม่ต้องการให้นักพัฒนาใช้ shell_exec สามารถทำได้โดยกำหนด safe_mode เป็น On ใน php.ini ก็จะใช้ฟังก์ชัน shell_exec ไม่ได้
short
30
:: webservices แบบ REST จาก amazon.com
:: ทดสอบไว้ที่ http://www.thaiall.com/rss/callAmazonRESTWS.php
    <?
    // callAmazonRESTWS.php จาก http://gotoknow.org/blog/krunapon/74176
    // โดย ผศ.ดร.กานดา รุณนะพงศา
    // - ถ้าไม่ส่ง parameters จะเรียก http://webservices.amazon.com/onca/xml ไม่ได้
    // - http://www.onlamp.com/pub/a/php/2003/10/30/amazon_rest.html
    header("Content-type: text/xml");
    $base = 'http://webservices.amazon.com/onca/xml'; 
    $query_string = '';
    $params = array( 
    'Service' =>'AWSECommerceService', 
    'SubscriptionId' => '16XT8ETKKB7NWHAGCQ02' , 
    'Operation' => 'ItemSearch',
    'SearchIndex' => 'Books',
    'Keywords' => 'Web Services'); 
    foreach ($params as $key => $value) { 
      if ($key != 'Keywords')
       $query_string .="$key=".urlencode($value) . "&";
      else
       $query_string .="$key=".urlencode($value);
    }
    $url = "$base?$query_string";
    $xml = file_get_contents($url);
    echo $xml;     
    ?>
    
short
31
:: crop or resize image
ใช้งานจริงใน http://www.thaiall.com/vbnet/testtoolbox.htm
    <?
    if (isset($_GET["i"])) $i = $_GET["i"]; else $i = 1;
    if (isset($_GET["f"])) $f = $_GET["f"]; else $f = 1;
    if ($i < 1 || $f < 1) exit;
    $filename = 'http://www.thaiall.com/vbnet/testtoolbox_0' . $f .'.gif';
    $percent = 1; // 0.2 สำหรับลดขนาดลง 20%
    header('Content-type: image/gif');
    list($width, $height) = getimagesize($filename);
    $newwidth = $width * $percent;
    $newheight = $height * $percent;
    $gap = ($height - 17) / 20;
    $nh = $newheight - (20 * $gap);
    // $thumb = imagecreatetruecolor($newwidth, $newheight);
    $thumb = imagecreatetruecolor($newwidth, $nh);
    $source = imagecreatefromgif($filename);
    // imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    imagecopyresized($thumb, $source, 0, 0, 0, ($i * 20 - 2), $newwidth, $nh, $width, $nh);
    imagejpeg($thumb);
    ?> 
    
short
32
:: การทำงานของ PHP เพื่อนำไปใช้ใน WAP Browser
ตัวอย่าง http://www.thaiall.com/wap
    
    <?php
    header("Content-type: text/vnd.wap.wml");
    print "<?xml version=\"1.0\"?>\n";
    ?>
    <wml><card id="HTML" title="<?php print rand();?>">
    <p>Hello on thaiall.com<br/>
    <?php print date("d/m/Y H:i:s"); ?></p>
    </card></wml>
    
หน่วยที่ 6 : แนะนำเว็บ (Web Guides)
Writing XLS File with PHP [ Download : php2xls.zip ]
Demo Files หรือ example-stocks.php (ได้นำไปทดสอบใน thaiabc.com ก็ไม่พบปัญหาใด)
การนำไปใช้ ทำโดยเปิดแฟ้ม example-stocks.php ด้วย notepad เพื่อแก้ไข หรือเพิ่มข้อมูลลงใน cell
PHP e-Commerce
http://www.tutorialized.com/tutorials/PHP/E-Commerce/1 (รวม link)
http://www.oscommerce.com (สมบูรณ์ด้วย PHP + MYSQL)
http://www.zen-cart.com (หน้าตาก็เหมือน zen-cart.com นั่นเลย)
PHP calendar with MYSQL
http://www.jtr.de/scripting/php/calendar/index_eng.html
http://keithdevens.com/software/php_calendar
Library of .dll on PHP
http://www.multimedia.uni-greifswald.de/~php4/
http://bugs.php.net/bug.php?id=4284 (problem about php_mssql70.dll on win98)
http://www.kromann.info/php.php (problem about php_mssql70.dll on win98)
Image in Script
http://cannot.info/base64image (convert image in php)
Flash Charts(XML)
charts.htm ตัวอย่าง
charts.zip
Open Flash Charts
(ยังแสดงภาษาไทยไม่ได้)
test01.htm ตัวอย่าง
ofcv2.zip
Open Flash Charts
Open Flash Charts
Open Flash Charts
Fusion Charts
http://www.fusioncharts.com
Google Charts (หาวิธีแสดงภาษาไทยยังไม่ได้ ใช้ %A1 แล้วหยุดเลยครับ)
http://chart.apis.google.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=%41%42|%61%62%25
แนะนำหนังสือ
- คู่มือเรียน PHP และ MYSQL สำหรับผู้เริ่มต้น, พร้อมเลิศ หล่อวิจิตร, provision, 239 บาท

แนะนำเว็บใหม่ : ผลการจัดอันดับ
รักลำปาง : thcity.com : korattown.com : topsiam.com : มหาวิทยาลัยโยนก
ศูนย์สอบ : รวมบทความ : ไอทีในชีวิตประจำวัน : ดาวน์โหลด : yourname@thaiall.com
ติดต่อ ทีมงาน ชาวลำปาง มีฝันเพื่อการศึกษา Tel.08-1992-7223