Created
November 23, 2017 09:51
-
-
Save ManishLSN/16b6f1a9c6f085bdde73aa0e49bfc428 to your computer and use it in GitHub Desktop.
curl method in php
This file contains hidden or 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 | |
| ### function for curl ### | |
| /* gets the data from a URL */ | |
| function get_data($url) { | |
| $ch = curl_init(); | |
| $timeout = 5; | |
| curl_setopt($ch, CURLOPT_URL, $url); | |
| curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
| curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); | |
| $data = curl_exec($ch); | |
| curl_close($ch); | |
| return $data; | |
| } | |
| ### Call API by function ### | |
| // Method: POST, PUT, GET etc | |
| // Data: array("param" => "value") ==> index.php?param=value | |
| function CallAPI($method, $url, $data = false) | |
| { | |
| $curl = curl_init(); | |
| switch ($method) | |
| { | |
| case "POST": | |
| curl_setopt($curl, CURLOPT_POST, 1); | |
| if ($data) | |
| curl_setopt($curl, CURLOPT_POSTFIELDS, $data); | |
| break; | |
| case "PUT": | |
| curl_setopt($curl, CURLOPT_PUT, 1); | |
| break; | |
| default: | |
| if ($data) | |
| $url = sprintf("%s?%s", $url, http_build_query($data)); | |
| } | |
| // Optional Authentication: | |
| curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); | |
| curl_setopt($curl, CURLOPT_USERPWD, "username:password"); | |
| curl_setopt($curl, CURLOPT_URL, $url); | |
| curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); | |
| $result = curl_exec($curl); | |
| curl_close($curl); | |
| return $result; | |
| } | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment