curl หรือ Client URL Library เป็น function ที่ทำให้ php ทำตัวเป็น browser ที่ใช้เปิดเว็บรับส่งข้อมูลต่างๆ จาก server ของเราไปเซิร์ฟเวอร์เครื่องอื่น ๆ
ตัวอย่างการใช้งานที่ง่ายที่สุด คือการใช้ curl โดยการจำลองการส่งข้อมูลจากฟอร์มแบบเมธอดเก็ต หรือที่เรียกง่ายๆว่า ส่งข้อมูลแบบ url นั่นละ
curl_get.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | <!doctype html> <html> <head> <meta charset="utf-8"> <title>CURL: send get variables</title> <link href="../vendor/twbs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css"> </head> <body> <div class="container"> <?php if (count($_GET)) { $queryString = http_build_query($_GET); $url = 'http://localhost/snippets/PHP/variables.php?' . $queryString; echo '<br>$url = ', $url; $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_URL => $url, ]); $result = curl_exec($ch); curl_close($ch); echo $result; } ?> <form action="curl_get.php" method="get"> <div class="form-group"> <label for="name">Name:</label> <input class="form-control" id="name" name="name" type="text"> </div> <div class="form-group"> <label for="avatar">Avatar:</label> <input accept="image/gif, image/jpeg, image/x-png" class="form-control" id="avatar" name="avatar" type="file"> </div> <div class="form-group"> <label for="address1">text address:</label> <input class="form-control" id="address1" name="address[]" type="text"> </div> <div class="form-group"> <label for="address2">text address 2:</label> <input class="form-control" id="address2" name="address[]" type="text"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div> </body> </html> |
ในการแปลงข้อมูลจากแบบฟอร์มจะใช้
Generate URL-encoded query string
1 | $queryString = http_build_query($_GET); |
แปลงให้อยู่ในรูปแบบคิวรี่สตริงที่ส่งไปกับ url ได้
การทดสอบทำได้โดยไฟล์ variables.php จำลองเป็นฝั่งรับข้อมูล
variables.php
1 2 3 4 5 6 | <?php echo '<h3>$_COOKIE</h3><pre>', print_r($_COOKIE, true), '</pre>'; echo '<h3>$_FILES</h3><pre>', print_r($_FILES, true), '</pre>'; echo '<h3>$_GET</h3><pre>', print_r($_GET, true), '</pre>'; echo '<h3>$_POST</h3><pre>', print_r($_POST, true), '</pre>'; echo '<h3>$_REQUEST</h3><pre>', print_r($_REQUEST, true), '</pre>'; |
ข้อมูลที่ส่งไปจะแสดงกลับมาให้เราเห็น แต่สังเกตได้ว่า ถึงจะส่งไฟล์ avatar ฝั่งรับก็จะไม่ได้รับ เพราะการส่งข้อมูลแบบนี้จะมีข้อเสียคือ ไม่สามารถส่งไฟล์ได้
About the author