มาลองเขียน PHPCurl เรียกหน้า ASP แบบง่าย ๆ กัน
อังคาร, 02/19/2008 - 18:58 | by sake
แค่นี้เราก็สามารถเรียก wrapper สำหรับ ใช้กับเว็บเราได้แล้วครับ :D
หลาย ๆ คนอาจจะรู้จักแล้ว ว่า cURL คืออะไร แต่ส่วนตัว เพิ่งเคยใช้นี่ละ :P
cURL เป็น tool ที่ใช้สำหรับในการ transfer ข้อมูลของ protocol ต่าง ๆ อย่าง HTTP HTTPS FTP SSH เป็นต้น
ตัวอย่างการใช้งานที่ผมจะลองใช้คือ มีเว็บนึง ต้องการการ login ก่อน จากนั้นจะสามารถเข้าใช้งานฟังก์ชันต่าง ๆ ในเว็บได้
ผมจะลองใช้ cURL ในการเรียกใช้ครับ ตัว cURL จะทำหน้าที่คล้าย ๆ เป็น web browser หรือ client ที่ browse ไปยังหน้าต่าง ๆ ให้
สำหรับ หน้า aspx จะมี FIELD ที่ชื่อ __VIEWSTATE อยู่เป็น ID ประจำหน้า ซึ่งก็ไม่รู้เหมือนกันมันคืออะไร
เพราะไม่สันทัด แต่เอาเป็นว่า ต้องใส่ละกัน
// สร้าง cookie $cookie_file_path = "/path/to/cookie.txt"; $LOGINURL = "http://www.example.com/login.aspx"; $agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)"; // ทำการ login $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$LOGINURL); curl_setopt($ch, CURLOPT_USERAGENT, $agent); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path); curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); $result = curl_exec ($ch); curl_close ($ch); // ค้นหา view state ปัจจุบัน $viewstate = $matches[1]; //ทำการเรียกใช้งานฟังก์ชั่นที่ต้องการ $POSTURL = "http://www.example.com/main.aspx"; $reffer = "http://www.example.com/main.aspx"; $POSTFIELDS = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=$viewstate&txtARG1=$arg1&txtARG2=$arg2"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$POSTURL); curl_setopt($ch, CURLOPT_USERAGENT, $agent); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS,$POSTFIELDS); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_REFERER, $reffer); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path); curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); $result = curl_exec ($ch);<br /><br />curl_close ($ch); echo $result; // ค้นหา view state ปัจจุบัน $viewstate = $matches[1]; //Log out $LOGOFFURL = "http://www.example.com/logOff.aspx"; $agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$LOGOFFURL); curl_setopt($ch, CURLOPT_USERAGENT, $agent); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path) curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); $result = curl_exec ($ch); curl_close ($ch);
แค่นี้เราก็สามารถเรียก wrapper สำหรับ ใช้กับเว็บเราได้แล้วครับ :D









ความคิดเห็น
แสดงความคิดเห็น