แต่ถ้าเรา setup form page ด้วย PHP Build-in Web server เราจะไม่สามารถเรียกใช้งาน curl ได้ เพราะว่า PHP Build-in Web server นั้น ออกแบบมาเพื่อใช้ในการพัฒนาเป็นหลัก ทำงานเป็น Single Thread ดังนั้น ถ้า php เป็นเราไปเขียน curl ไปเรียก อีกหน้าที่อยู่ใน web server เดียวกัน ก็จะเกิดอาการค้าง หรือที่เรียกว่า "deadlock" เราต้องไปเขียนที่เครื่องหนึ่ง แล้ว ก็ Run อีกเครื่องหนึ่งแทน
ผมได้ทดลองเขียน script Post เพื่อ Login เข้าไปใน http://lms.phuket.psu.ac.th/ ของวิทยาเขต มีตัวอย่าง Code ดังนี้ครับ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
ini_set('display_errors', 'On'); | |
error_reporting(E_ALL); | |
function get($url,$cookieFile, $referer, $params=array()) { | |
$url = $url.'?'.http_build_query($params, '', '&'); | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $url); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); | |
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); | |
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); | |
curl_setOpt($ch, CURLOPT_REFERER, $referer); | |
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Origin: http://lms.phuket.psu.ac.th', 'Host: lms.phuket.psu.ac.th')); | |
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); | |
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); | |
curl_setopt($ch, CURLOPT_VERBOSE, true); | |
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); | |
$response = curl_exec($ch); | |
curl_close($ch); | |
return $response; | |
} | |
function post($url,$cookieFile, $referer, $fields){ | |
$post_field_string = http_build_query($fields, '', '&'); | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $url); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); | |
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); | |
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); | |
curl_setOpt($ch, CURLOPT_REFERER, $referer); | |
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Origin: http://lms.phuket.psu.ac.th', 'Host: lms.phuket.psu.ac.th')); | |
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); | |
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); | |
curl_setopt($ch, CURLOPT_VERBOSE, true); | |
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); | |
// for POST method | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_field_string); | |
curl_setopt($ch, CURLOPT_POST, true); | |
$response = curl_exec($ch); | |
curl_close ($ch); | |
return $response; | |
} | |
get('https://lms.phuket.psu.ac.th/moodle/login/index.php','cookie.txt','http://lms.phuket.psu.ac.th/moodle/',array('no'=>' ')); | |
echo post('https://lms.phuket.psu.ac.th/moodle/login/index.php','cookie.txt','http://lms.phuket.psu.ac.th/moodle/', array('username'=>'psuUserName','password'=>'psuPassword')); | |
?> |
Update: 18 ส.ค. 59
ไม่มีความคิดเห็น:
แสดงความคิดเห็น