How to send data from my form to webservice? - php

I need to send some data from my form in html to webservice. (For do this, i need to do the operation of POST)
I have seen research that I can transmit information using php cURL. But in all examples, i don't view to send data to webservice, only to file php that print $_POST variable.
I have this webservice: http://192.168.1.1/fastfood/event/attendee (example)
And i try to send data in an array.
For example i try to send: attendee = array( 'name' => $_POST['name'] , 'lastname' => $_POST['lastname'] , 'address' => $_POST['address'] );
Then, the web service takes out the array data. ¿How to do this?
UPDATE 1:
This is my code that i'm doing now... But don't work :(
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$attendee = array(
'name' => "$name",
'lastname' => "$lastname",
'address' => "$address"
);
$url_target = 'http://192.168.1.1/fastfood/event/attendee';
//$header = array('Content type: multipart/form-data');
$user = 'root';
$pass = '123';
$userpasswd = "$user:$pass";
$ch = curl_init($url_target);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_USERPWD, $userpasswd);
//curl_setopt($ch, CURLOPT_URL, $url_target);
//curl_setopt($ch, CURLOPT_HEADER, TRUE);
//curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attendee);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$result = curl_exec($ch);
$getInfo = curl_getinfo($ch);
curl_close($ch);
The variable $result return me a FALSE, and the variable $getInfo return me a http_code = 500, Content-Type = Null.
Reading the documentation of cURL when i send a data like a array, the content type should be a "multipart/form-data" but, also, don't work for me.

// Here is the data we will be sending to the service
$data = array(
'name' => $_POST['name'],
'lastname' => $_POST['last_name'],
'address' => $_POST['address']
);
$curl = curl_init('http://192.168.1.1/fastfood/event/attendee');
curl_setopt($curl, CURLOPT_POST, 1); //Choosing the POST method
curl_setopt($curl, CURLOPT_URL, 'http://localhost/helloservice.php'); // Set the url path we want to call
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Make it so the data coming back is put into a string
curl_setopt($curl, CURLOPT_POSTFIELDS, $some_data); // Insert the data
// Send the request
$result = curl_exec($curl);
// Free up the resources $curl is using
curl_close($curl);
echo $result;
Written by Chad Lung at GiantFlyingSaucer

Related

How to make api calls in batches of 100 calls per second per request in PHP

I am developing an sms sending php system the server can only handle 100 calls per request. How can I make 100 API calls per second per request when I'm sending large data of messages of about 5000+,
here is my PHP code
$phones = $_POST['recipient_phones']; //get phone numbers from textarea
$phones = chop($phones,","); //remove last comma
$phones = multiexplode(array(","," ","\r\n",".","|",":"),$phones);//reformat and convert to array
$sender = $_POST['sender_id']; //Get Sender ID input field
$message = $_POST['message']; //Get Message input field
$link_id = $rand_link_id;
$correlator = $randCorrelator;
$endpoint = 'https://exampleurl.com';
foreach($phones as $phone){
$data = array("link_id" => "$link_id", "sender" => "$sender","phone" => "$phone", "message" => "$message","endpoint" => "$endpoint","correlator" => "$correlator");
$data_string = json_encode($data);
$ch = curl_init('https://bulk.example.com/api/v1/send-sms');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json','Accept: application/json','Authorization:Bearer '.$token,
'Content-Length: ' . strlen($data_string))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
//execute post
$smsResults = curl_exec($ch);
sleep(3);
//close connection
curl_close($ch);

MailChimp API Responds 404 in V3.0 PHP Curl

I am using the following code to initiate a member add request to a list in MailChimp.
<?php
error_reporting(-1);
ini_set('display_errors', 1);
$email = 'test#domain.com';
$first_name = 'name';
$last_name = 'last name';
$api_key = 'xx-us18'; // YOUR API KEY
// server name followed by a dot.
// We use us13 because us13 is present in API KEY
$server = 'us18.';
$list_id = 'xx'; // YOUR LIST ID
$auth = base64_encode( 'user:'.$api_key );
$data = array(
'apikey' => $api_key,
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => array(
'FNAME' => $first_name,
'LNAME' => $last_name
)
);
$json_data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://'.$server.'api.mailchimp.com/3.0/lists/'.$list_id.'/members');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = curl_exec($ch);
echo $result;
?>
But what happened is the response is 404.
{
type: "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
title: "Resource Not Found",
status: 404,
detail: "The requested resource could not be found.",
instance: "78a35efa-ef43-471d-9e70-aecdc992d2e6"
}
Does anyone know what I am doing wrong? What might be the reason for this error?
Extra Infos: API Key is valid, If I provide that wrong, I am getting another error.
List-id is also true.
I am running this code on localhost with MAMP.
The issue was I used web_id instead of list_id.
When I changed that, the issue was resolved.

Send invoice by email through Zoho Books API

My Code is as follows...
The email functions
public function zoho_email($array){
$data = json_decode($array,true);
$url = '/invoices/'.$data['invoice']['invoice_id'].'/email';
$recivers[] = array($data['invoice']['contact_persons_details'][0]['email']);
$data = array(
'to_mail_ids' => $recivers,
'subject' => 'Invoice from MSL (Invoice#: '.$data['invoice']['invoice_number'].')',
'body' => 'Dear Customer,<br><br><br><br>Thanks for your business,
'send_from_org_email_id' => true
);
$result = $this->zoho_create($url, $data);
}
The curl Function for create invoices, contacts, and send email
public function zoho_create($url,$array){
$json = json_encode($array);
$data = array('authtoken' => ZOHOAUTHTOKEN,'JSONString' => $json,'organization_id' => ZOHOORGNISATIONID);
$curl = curl_init($this->apiUrl.$url);
if($url=='contacts/'){
curl_setopt_array($curl, array(
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => true
));
}
else{
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded") );
}
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
I want to send invoice by email through API to customer but This error occur in my code.
{"code":5,"message":"Invalid URL Passed"}
Please help me out there....
Thanks in advance...
Your code is working correctly. Try to print the url ($url) and confirm once if it is in the required format (/invoices/invoice_id/email). For example if your invoice_id is 1234, then the $url should be '/invoices/1234/email'. Also make sure that $this->apiUrl is https://books.zoho.com/api/v3
If there occurs a problem still u can use the help documents mentioned below:
https://www.zoho.com/books/api/v3/.
have you tried using full url : "https://books.zoho.com/api/v3/invoices/:invoiceno/email"

Updating subscribers in a list using cURL and Mailchimp API v3

I have this code below that adds a user to a pre-existing list in Mailchimp.
$apikey = '<api_key>';
$auth = base64_encode( 'user:'.$apikey );
$data = array(
'apikey' => $apikey,
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => array(
'FNAME' => $name
)
);
$json_data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://us2.api.mailchimp.com/3.0/lists/<list_id>/members/');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = curl_exec($ch);
var_dump($result);
die('Mailchimp executed');
This code only adds users to the list and when I try add the details of the same user twice it throws the following error on the second attempt:
test#user.com is already a list member. Use PATCH to update existing members.
How do I go about using PATCH to update user details? I'm not sure where to specify it.
I figured out where I'm going wrong. When the user is initially added to the list the response provides an ID. I need to store the ID in my database with those person's details and reference the ID in the url I'm making a call to when I want to update the user's details in the Mailchimp List.
https://us2.api.mailchimp.com/3.0/lists/<list_id_goes_here>/members/<members_id_goes_here>
Thanks #TooMuchPete for the correct curl command.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
You're looking for the CURLOPT_CUSTOMREQUEST option in cURL.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
But, since this is now your second question in as many days asking how to use built-in cURL library, it might be worth using something a little better. If you're on PHP 5.4 or better, I recommend Guzzle. PHP Requests is also very good, though, and works with PHP 5.3.
Try this one. It's working for me. I am using this function. Hope it should be solved your problem.
<?php
/**
* Created by PhpStorm.
* User: Faisal
* Website: www.faisal-ibrahim.info
* Date: 2/12/2016
* Time: 10:07 AM
*/
if (isset($_POST['email'])) {
$email = $_POST['email'];
} else {
$email = 'faisal.im048#gmail.com';
}
$data = [
'email' => $email,
'status' => 'subscribed',
'firstname' => 'Faisal',
'lastname' => 'Ibrahim'
];
$api_response_code = listSubscribe($data);
echo $api_response_code;
/**
* Mailchimp API- List Subscribe added function.In this method we'll look how to add a single member to a list using the lists/subscribe method.Also, We will cover the different parameters for submitting a new member as well as passing in generic merge field information.
*
* #param array $data Subscribe information Passed.
*
* #return mixed
*/
function listSubscribe(array $data)
{
$apiKey = "cf8a1fd222a500f27f9e042449867c7c-us15";//your API key goes here
$listId = "e8f3f5f880";// your trageted list ID
$memberId = md5(strtolower($data['email']));
$dataCenter = substr($apiKey, strpos($apiKey, '-') + 1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/' . $memberId;
$json = json_encode([
'email_address' => $data['email'],
'status' => $data['status'], // "subscribed","unsubscribed","cleaned","pending"
'merge_fields' => [
'FNAME' => $data['firstname'],
'LNAME' => $data['lastname']
]
]);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpCode;
}

Passing $_POST values with cURL

How do you pass $_POST values to a page using cURL?
Should work fine.
$data = array('name' => 'Ross', 'php_master' => true);
// You can POST a file by prefixing with an # (for <input type="file"> fields)
$data['file'] = '#/home/user/world.jpg';
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_exec($handle);
curl_close($handle)
We have two options here, CURLOPT_POST which turns HTTP POST on, and CURLOPT_POSTFIELDS which contains an array of our post data to submit. This can be used to submit data to POST <form>s.
It is important to note that curl_setopt($handle, CURLOPT_POSTFIELDS, $data); takes the $data in two formats, and that this determines how the post data will be encoded.
$data as an array(): The data will be sent as multipart/form-data which is not always accepted by the server.
$data = array('name' => 'Ross', 'php_master' => true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
$data as url encoded string: The data will be sent as application/x-www-form-urlencoded, which is the default encoding for submitted html form data.
$data = array('name' => 'Ross', 'php_master' => true);
curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));
I hope this will help others save their time.
See:
curl_init
curl_setopt
Ross has the right idea for POSTing the usual parameter/value format to a url.
I recently ran into a situation where I needed to POST some XML as Content-Type "text/xml" without any parameter pairs so here's how you do that:
$xml = '<?xml version="1.0"?><stuff><child>foo</child><child>bar</child></stuff>';
$httpRequest = curl_init();
curl_setopt($httpRequest, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($httpRequest, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
curl_setopt($httpRequest, CURLOPT_POST, 1);
curl_setopt($httpRequest, CURLOPT_HEADER, 1);
curl_setopt($httpRequest, CURLOPT_URL, $url);
curl_setopt($httpRequest, CURLOPT_POSTFIELDS, $xml);
$returnHeader = curl_exec($httpRequest);
curl_close($httpRequest);
In my case, I needed to parse some values out of the HTTP response header so you may not necessarily need to set CURLOPT_RETURNTRANSFER or CURLOPT_HEADER.
Another simple PHP example of using cURL:
<?php
$ch = curl_init(); // Initiate cURL
$url = "http://www.somesite.com/curl_example.php"; // Where you want to post data
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true); // Tell cURL you want to post something
curl_setopt($ch, CURLOPT_POSTFIELDS, "var1=value1&var2=value2&var_n=value_n"); // Define what you want to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the output in string format
$output = curl_exec ($ch); // Execute
curl_close ($ch); // Close cURL handle
var_dump($output); // Show output
?>
Instead of using curl_setopt you can use curl_setopt_array.
http://php.net/manual/en/function.curl-setopt-array.php
$query_string = "";
if ($_POST) {
$kv = array();
foreach ($_POST as $key => $value) {
$kv[] = stripslashes($key) . "=" . stripslashes($value);
}
$query_string = join("&", $kv);
}
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
$url = 'https://www.abcd.com/servlet/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($kv));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$url='Your url'; // Specify your url
$data= array('parameterkey1'=>value,'parameterkey2'=>value); // Add parameters in key value
$ch = curl_init(); // Initialize cURL
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
<?php
function executeCurl($arrOptions) {
$mixCH = curl_init();
foreach ($arrOptions as $strCurlOpt => $mixCurlOptValue) {
curl_setopt($mixCH, $strCurlOpt, $mixCurlOptValue);
}
$mixResponse = curl_exec($mixCH);
curl_close($mixCH);
return $mixResponse;
}
// If any HTTP authentication is needed.
$username = 'http-auth-username';
$password = 'http-auth-password';
$requestType = 'POST'; // This can be PUT or POST
// This is a sample array. You can use $arrPostData = $_POST
$arrPostData = array(
'key1' => 'value-1-for-k1y-1',
'key2' => 'value-2-for-key-2',
'key3' => array(
'key31' => 'value-for-key-3-1',
'key32' => array(
'key321' => 'value-for-key321'
)
),
'key4' => array(
'key' => 'value'
)
);
// You can set your post data
$postData = http_build_query($arrPostData); // Raw PHP array
$postData = json_encode($arrPostData); // Only USE this when request JSON data.
$mixResponse = executeCurl(array(
CURLOPT_URL => 'http://whatever-your-request-url.com/xyz/yii',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPGET => true,
CURLOPT_VERBOSE => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_CUSTOMREQUEST => $requestType,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => array(
"X-HTTP-Method-Override: " . $requestType,
'Content-Type: application/json', // Only USE this when requesting JSON data
),
// If HTTP authentication is required, use the below lines.
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $username. ':' . $password
));
// $mixResponse contains your server response.

Categories