cURL (or
libcurl) is a PHP library which enables you interact to many different types of servers with many different types of protocols.
libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.
cURL has many potential uses and I'm gonna show you the different uses of cURL. It can be used to grab a webpage, submit a form, upload a file, and many more!
How to Use cURL to submit to a Form
We have a form located at
http://localhost/form.php
that uses the POST method to submit its content. And we want to use cURL to submit a form.
<?php
if($_POST):
echo 'Username: '.$_POST['username'].'<br>'.'Password: '.$_POST['password'];
else:
?>
<form action="" method="post">
<label for="_username">Username:</label>
<input name="username" id="_username"/>
<label for="_username">Password:</label>
<input name="password" id="_password"/>
<input type="submit" />
</form>
<?php endif; ?>
To submit a form using cURL, we use
CURLOPT_POST
and
CURLOPT_POSTFIELDS
since the form method is POST.
<?php
$data = array(
//postfield name => value
'username' => 'tipsicle',
'password' => 'abc123');
$ch = curl_init('http://localhost/form.php');
CURL_SETOPT_ARRAY($ch,array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => true
));
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
How to Upload a file to a form using cURL
<?php
if(isset($_FILES["fileupload"])):
echo "Upload: " . $_FILES["fileupload"]["name"] . "<br />";
echo "Type: " . $_FILES["fileupload"]["type"] . "<br />";
echo "Size: " . ($_FILES["fileupload"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["fileupload"]["tmp_name"];
else:
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="fileupload">
<input type="submit" />
</form>
<?php endif; ?>
To upload a file using cURL, you need to affix
@
at the beginning of the location of your file.
<?php
$data = array(
//postfield name => value
'fileupload' => '@/wamp/www/php/Sunset.jpg');
$ch = curl_init('http://localhost/php/form.php');
CURL_SETOPT_ARRAY($ch,array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => true
));
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>