I am having trouble doing cURL PUT in PHP for a REST API. It says 401 Unauthorized and I am quite new to php so I didn't know what to do please help me.
<?php
$url = "https://app.linkemperor.com/api/v2/vendors/blasts/6949235.json";
$data = '{"blasts": {"links" : "http://doblajemexicano.com.mx/sitio/index.php?title=Keyword_Elite_,_The_Ferrari_Of_Search_phrases_Study
http://fi.caravanwiki.com/index.php/Keyword_Elite_,_The_Ferrari_Of_Keywords_and_phrases_Research"}}';
$content = json_encode($data);
$oneMB = 1024 * 1024;
$fh = fopen('php://temp/maxmemory:$oneMB', 'r+');
fwrite($fh, $content);
rewind($fh);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_USERPWD, "<api key>:x");
curl_setopt($curl, CURLOPT_INFILE, $fh);
curl_setopt($curl, CURLOPT_INFILESIZE, strlen($content));
curl_setopt($curl, CURLOPT_PUT, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
?>
Related
$file = "blaynmailhahaha.csv";
$authorization = "Authorization: Bearer [".$response."]";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.toku-maga.com/rest/1.0/contact/import/create");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); // use HTTP/1.0 instead of 1.1
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // uncomment this line if you get no gateway
curl_setopt($curl, CURLOPT_HTTPHEADER, [$authorization, 'Content-Type: text/plain']);
$cfile = new CurlFile($file, 'text/csv','import');
//curl file itself return the realpath with prefix of #
$data = array('data-binary' => $cfile);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
curl_close($curl);
var_dump($cfile);
//echo "<br>Data File : " . $cfile ;
echo "<br>This is Access_token : " . $authorization ;
echo "<br>This is 2nd Output : " . $curl_response ;
I don't get any response from $curl_response and could not upload it to blaynmail. Please help me to solve this problem.
Watson has the next code:
curl -u "{username}":"{password}"
-X POST
--form file=#template.xml
--form name=templateName
"https://gateway.watsonplatform.net/dialog/api/v1/dialogs"
And I have:
$ch = curl_init();
$data['name'] = $this->post['name'].";type:form";
$data['file'] = $this->getCurlValue($this->post['file'], $this->post['nombre']);
curl_setopt($ch, CURLOPT_URL, $this->url.$this->metodo);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_USERPWD, "{$this->user}:{$this->pass}");
if(count($this->post) > 0){
//curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$output = curl_exec($ch);
curl_close($ch);
json_decode($output);
$this->post has...
$data = Request::only('name', 'file');
And I only get as answer: {}
What I'm missing?
Thanks everyone!... First time try to send a uploading file with curl :c
It was simpler than I imagined.
Store:
$data = Request::only('name', 'file');
$nombre = time().".".Request::file('file')->getClientOriginalExtension();
Request::file('file')->move(base_path() . '/public/dialogos/', $nombre);
$data['path'] = base_path() . '/public/dialogos/'.$nombre;
$data['file'] = $_FILES['file'];
Curl:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url.$this->metodo);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_USERPWD, "{$this->user}:{$this->pass}");
if(count($this->post) > 0){
$datos['name'] = $this->post['name'];
$datos['file'] = $this->getCurlValue($this->post['file'], $this->post['path']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datos);
}
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output);
getCurlValue($file, $path);
if (function_exists('curl_file_create')) {
return curl_file_create($path, $file['type'], $file['name']);
}
$value = "#{$path};filename=" . $file['name'];
$value .= ';type=' . $file['type'];
return $value;
Stupid msg that said I need PUT or DELETE methods... haha
I have written a PHP script which is going to loop through approx. 500 URLs and check their status:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_exec($ch);
$destURL = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo $destURL . " - " . $statusCode;
Could this be optimized any further OR is there a better way of doing this?
You could do this quite easily with GuzzleHttp:
use GuzzleHttp\TransferStats;
$effectiveURL = '';
$statusCode = 0;
$client = new GuzzleHttp\Client();
$client->get($url, [
'on_stats' => function (TransferStats $stats) use (&$effectiveURL, &$statusCode) {
$effectiveURL = (string) $stats->getEffectiveUri();
if ($stats->hasResponse()) {
$statusCode = $stats->getResponse()->getStatusCode();
}
},
]);
echo $effectiveURL . '<br>';
echo $statusCode;
I'm trying to make a get request in php using curl. This is what I'm doing:
$curl = curl_init();
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);
printf($result);
But $result doesn't print out anything, no success or failure message. I've successfully reached the endpoint via postman and in a web browser so I know it works. Printing out $curl prints: "Resource #1" which makes me think curl is properly installed on the server.
I'm not sure what steps to take next to make things work.
Add a few more option for troubleshooting purposes.
Check for an error response.
If no error, get the details:
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
curl_setopt($ch, CURLOPT_FAILONERROR,true);
curl_setopt($ch, CURLOPT_ENCODING,"");
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$data = curl_exec($ch);
if (curl_errno($ch)){
$data .= 'Retreive Base Page Error: ' . curl_error($ch);
}
else {
$skip = intval(curl_getinfo($ch, CURLINFO_HEADER_SIZE));
$head = substr($data,0,$skip);
$data = substr($data,$skip);
$info = curl_getinfo($ch);
$info = var_export($info,true);
}
echo $head;
echo $info;
You can utilize curl's CURLOPT_VERBOSE and CURLOPT_STDERR like this:
$curl = curl_init();
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);
$verbose = fopen('php://temp', 'w+');
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_STDERR, $verbose);
$result = curl_exec($curl);
curl_close($curl);
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";
printf($result);
I am using this code... but i am getting some curl error in my code..
function send_data($data) {
$url = ""; // URL to POST FORM. (Action of Form)
$url .= '?acx=' . urlencode('V2ViSnNvbkRldkFwbkBTaWdtYUFwbjpXZWIxMjMkSnNvbg==') . '&key=' . urlencode('QW51bWF0aGlVbmRhQFNpZ21hQXBuOlVuZHVBbnVtYXRoaQ==');
$url .= '&impdata=' . urlencode('{"System":{"Client":"SigmaApn","ACX":"V2ViSnNvbkRldkFwbkBTaWdtYUFwbjpXZWIxMjMkSnNvbg==","KEY":"QW51bWF0aGlVbmRhQFNpZ21hQXBuOlVuZHVBbnVtYXRoaQ==","ClientIP":"74.117.104.99","Mode":"TEST"},"Module":{"Process":"BatchEnrollment","Version":"2.1.5","DataDefinition":[{"Name":"enrolment_queue","IncludeRecType":"false","Identifier":"sys_batch_no","Header":["batch_no","source","source_line","agent_code","premise_id","plan_group","request_date","enrol_type","cust_firstname","cust_lastname","phone1","cm_address1","cm_city","cm_state","cm_zip","life_support","cust_status","plan_id1","contract_ind","contract_type","calc_method","rate_type","adder1_rate","cust_bill_type","edi_bill_presenter"]}],"Data":[["Batch","BATCH","1","0","PREMISE1","R","10/28/2011","M","' . $data['personalinfo_first_name'] . '","' . $data['personalinfo_last_name'] . '","8050123481","' . $data['service_address1'] . '","' . $data['service_city'] . '","' . $data['service_state'] . '","' . $data['service_zipcode'] . '","N","P","PN001","Y","MCP2","1","4","0.02","Default","ESP"]]}}');
$url .= '&mode=' . urlencode('TEST');
$headersVal = array("application/x-www-form-uriencoded");
$myFile = "/tmp/isigma.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$ch = curl_init(); // Initialize a CURL session.
curl_setopt($ch, CURLOPT_URL, $url); // Pass URL as parameter.
curl_setopt($ch, CURLOPT_STDERR, $fh);
curl_setopt($ch, CURLOPT_POST, 1); // use this option to Post a form
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '1');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '1');
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "/iSIGMARootCA.crt");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSLCERT, getcwd() . "/APN_Generic_JSON.pem");
curl_setopt($ch, CURLOPT_SSLKEY, getcwd() . "/apnakey.pem");
curl_setopt($ch, CURLOPT_SSLCERTTYPE, "PEM");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch); // grab URL and pass it to the variable.
curl_close($ch); // close curl resource, and free system resources.
fclose($fh);
$res_array = json_decode($result, true);
if (!empty($result)) {
return $res_array;
} else {
echo "Curl Error" . curl_error($ch);
}
}
thanks for help in advance..
I'm using this function to post data.
You can put an associative array as second parameter, the first is the url that you want to call.
private function postData($url, $data) {
$post_data = http_build_query($data);
$fp = tmpfile();
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_TIMEOUT, 20);
curl_setopt($curl, CURLOPT_FILE, $fp);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_FAILONERROR, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_COOKIEJAR, '/dev/null');
$status = curl_exec($curl);
$response['http_code'] = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status) {
$response['error'] = curl_error($curl);
$response['errno'] = curl_errno($curl);
}
curl_close($curl);
rewind($fp);
$response['data'] = '';
while ($str = fgets($fp, 4096)) {
$response['data'] .= $str;
}
fclose($fp);
return $response['data'];
}