note 113876 added to function.curl-exec
| From: | ManuManjunath | Date: | Thu, 12 Dec 2013 13:24:59 +0000 |
| Subject: | note 113876 added to function.curl-exec | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-197913@lists.php.net to get a copy of this message | ||
If you want to get contents of a page through HTTP GET or POST, you can write a small function like
below.
<?php
/**
* Read entire contents of a URL in a string
* @param string $url URL to fetch data from
* @param mixed $params Parameters to the URL, typically an array. In case of POST, can be a string
* @param string $method HTTP method - can be 'GET' (default) or 'POST'
* @return mixed Contents of the webpage. Returns <i>false</i> in case of failure.
*/
function url_get_contents($url, $params = null, $method = 'GET') {
$contents = false;
if (!in_array($method, array('GET', 'POST'))) {
error_log(__FUNCTION__ . ": Unknown method '$method'");
return false;
}
if ($method == 'GET') {
if (is_array($params) && count($params) > 0) {
if ($params === array_values($params)) {
error_log(__FUNCTION__ . ": Numerical array recieved for argument '\$params'
(assoc array expected)");
return false;
}
else {
$url .= '?' . http_build_query($params);
}
}
elseif (!is_null($params)) {
error_log(__FUNCTION__ . ": If you're making a GET request, argument \$params must be
null or assoc array.");
return false;
}
}
$ch = curl_init($url);
if ($ch !== false) {
curl_setopt_array($ch, array(
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
));
if ($method == 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
if (is_string($params) || is_array($params)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
}
else {
error_log(__FUNCTION__ . ": Argument \$params should be an array of parameters or (if you
want to send raw data) a string");
return false;
}
}
$contents = curl_exec($ch);
curl_close($ch);
}
return $contents;
}
----
Server IP: 72.52.91.14
Probable Submitter: 72.52.91.14
----
Manual Page -- http://php.net/manual/en/function.curl-exec.php
Edit -- https://master.php.net/note/edit/113876
Del: integrated -- https://master.php.net/note/delete/113876/integrated
Del: useless -- https://master.php.net/note/delete/113876/useless
Del: bad code -- https://master.php.net/note/delete/113876/bad+code
Del: spam -- https://master.php.net/note/delete/113876/spam
Del: non-english -- https://master.php.net/note/delete/113876/non-english
Del: in docs -- https://master.php.net/note/delete/113876/in+docs
Del: other reasons-- https://master.php.net/note/delete/113876
Reject -- https://master.php.net/note/reject/113876
Search -- https://master.php.net/manage/user-notes.php