curl หรือ Client URL Library เป็น function ที่ทำให้ php ทำตัวเป็น browser ที่ใช้เปิดเว็บรับส่งข้อมูลต่างๆ จาก server ของเราไปเซิฟเวอร์เครื่องอื่นๆ
ตัวอย่างการใช้งานที่ง่ายที่สุด คือการใช้ curl โดยการจำลองการส่งข้อมูลจากฟอร์มแบบเมธอดเก็ต หรือที่เรียกง่ายๆว่า ส่งข้อมูลแบบ url นั่นละ
[code language=”php” title=”curl_get.php”]<!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>[/code]ในการแปลงข้อมูลจากแบบฟอร์มจะใช้ [code language=”php” title=”Generate URL-encoded query string”]$queryString = http_build_query($_GET);[/code] แปลงให้อยู่ในรูปแบบคิวรี่สตริงที่ส่งไปกับ url ได้
การทดสอบทำได้โดยไฟล์ variables.php จำลองเป็นฝั่งรับข้อมูล[code language=”php” title=”variables.php”]<?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>’;
[/code]
ข้อมูลที่ส่งไปจะแสดงกลับมาให้เราเห็น แต่สังเกตุได้ว่า ถึงจะส่งไฟล์ avatar ฝั่งรับก็จะไม่ได้รับ เพราะการส่งข้อมูลแบบนี้จะมีข้อเสียคือ ไม่สามารถส่งไฟล์ได้