How to send WordPress form data via curl using POST? - php

I need to insert the following code into POST using CURL:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.bmby.com/shared/AddClient/index.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_REFERER, 'http://xxxxxxxx/');
$data = [
'ProjectID' => xxxx
'Password' => 'xxxxxx',
'Fname' => $_POST['your-name'],
'Email' => $_POST['email'],
'Phone' => $_POST['your-tel'],
#'Esse' => $_POST['msg'],
'Referal' => 'http://xxxxxxxx/',
'MediaTitle' => 'אתר אינטרנט ראשי',
'AllowedMail' => 2, # 0 = allow, 2 = don't allow
'IP' => $_SERVER['REMOTE_ADDR'],
];
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
Any guidance on how to implement this and have the form that we created to relate to the above code so that the service we are using to gather all the leads from the form could get the required info.

Depending on what kind of a form you have (it could be a .php file or a WP plugin), the above code needs to be in a function or a php file that will be executed when your form is submitted, either using the action attribute in the HTML form tag or in a function that's called using a form submit action/filter (which is common if you're using a plugin).
The code you posted, when correctly substituted with the correct variables (for example all the URLs and whatever you pass in $data) is the code for performing a cURL session using POST. Since CURLOPT_RETURNTRANSFER is set, $output will contain the result of the cURL session on success and FALSE on failure. Make sure that the POST variables like $_POST['your-name'] correspond to the name attributes in your form fields. It is also recommended to validate the form fields instead of directly passing the $_POST['your-name']. Once you've edited the code with the correct variable names and URLs, the code should run and the result would be in your $output. You can check the result to see if it was a success or do something with the result as required. If you wish to get the HTTP code you should look into curl_getinfo().

Related

Fill out HTML form using data from dataset, and store results into a file

What is the most effective way of programmatically filling out an HTML form on a website, using data from a dataset (either CSV, JSON, or similar..) and then retrieving the results of that submitted form into another dataset? I would like to be able to do this multiple times, populating the form with different parameters each time, always retrieving those parameters from my input dataset.
I was reading about Selenium and HTMLUnit, which seem to do similar things. But they require installing dependencies and learning how to use them. Would it be overkill? Is there an easier way to do this by maybe writing my own script?
I tried writing a php curl script, but this one doesn't generate the headers or cookies that the request requires, so I'm not able to retrieve anything.
<?php
/**
* Send a POST requst using cURL
* #param string $url to request
* #param array $post values to send
* #param array $options for cURL
* #return string
*/
function curl_post($url, array $post = NULL, array $options = array())
{
$defaults = array(
CURLOPT_POST => 1,
CURLOPT_HEADER => 0,
CURLOPT_URL => $url,
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_TIMEOUT => 4,
CURLOPT_POSTFIELDS => http_build_query($post)
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
if( ! $result = curl_exec($ch))
{
trigger_error(curl_error($ch));
}
curl_close($ch);
return $result;
}
?>
I'm not sure if that's the right approach.
Any tips/resources would be appreciated.
You can write this script in Selenium - it's just a browser driver, it will fill the form from the client side. If the page isn't very complicated, you can use library requests in Python and directly send POST data to the final page. Requests is a faster lib, and to write a script sending POST data you will need 5 mins of learning.

cURL post data in URL scope not form scope?

Trying to help out someone who is trying to access and API using PHP. My code using ColdFusion works fine posting to the API, but we can't get the PHP to work. In CF the code uses urlparams to send the data:
<cfhttp url="https://example.com/_api/proxyApi.cfc" method="post" result="httpResult" charset="UTF-8">
<cfhttpparam type="url" name="method" value="apiauth"/>
<cfhttpparam type="url" name="argumentCollection" value="#jsData#"/>
</cfhttp>
A dump of the resulting call from the API shows the variables in the URL like this:
method = apiauth is the main authorization function, and then the json string in argumentCollection is passed to the correction function in the API by apiauth.
From PHP his curl is posting as form data, not URL and the API complains that the required information is missing because it's in the wrong scope. I've been trying to figure out how to make curl use URL scope instead:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $target_url,
CURLOPT_POST => 1,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 2,
CURLOPT_AUTOREFERER => true,
CURLOPT_POSTFIELDS => array(
'method' => 'apiauth',
'argumentCollection' => $json
)
));
The same dump from the API shows the same data, but in the wrong scope:
It seems like if we can get the data in the right scope we'll make progress, but my PHP knowledge is dangerously limited.
You are sending an empty POST in your CF example.
<cfhttpparam type="url" is processed as a query string parameter, as in:
https://example.com/_api/proxyApi.cfc?method=apiauth&argumentCollection=...
Thus your dump of the URL scope (the key-value-paired query string) shows the data.
To put those parameters into your POST body, you would use:
<cfhttpparam type="formfield"
And then you FORM scope would show the data.
Your PHP cURL does the latter: it adds your parameters to the POST body.
If you want the cURL to work as your example CF code, do this instead:
// add the parameters to the URL's query string
// start with & instead of ?, if the URL already contains a query string, see comment below snippet
$target_url .= '?'.'method=apiauth'.'&'.'argumentCollection='.urlencode($json);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $target_url,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 2,
CURLOPT_AUTOREFERER => true
));
no query string in $target_url:
$target_url = 'https://example.com/_api/proxyApi.cfc';
$target_url .= '?'.'method=apiauth'.'&'.'argumentCollection='.urlencode($json);
query string in $target_url:
$target_url = 'https://example.com/_api/proxyApi.cfc?p=';
$target_url .= '&'.'method=apiauth'.'&'.'argumentCollection='.urlencode($json);
On a side note: You probably don't want to send JSON via query string as the query string has a limit of about 2000 chars (depends on browser and webserver). If your JSON is complex, your query string will be truncated and mess everything up. Use the POST body for this instead.

PHP cURL filling out values form action is not fired

I've got two different remote forms which I need to submit data to. The first one is an http form, and it works just fine. Submit > redirect to result page > return response as variable.
The second one lives on an https page, and it just doesn't work, no matter what I try. So here's what I'm working with:
First form's form tag
<form method="post" name="entry_form" action="a_relative_page.asp?start=1">
Second form's form tag
<form method="post" novalidate enctype="multipart/form-data" action="https://asubdomain.formstack.com/forms/index.php" class="stuff" id="stuff1234567890">
Both buttons are completely unremarkable, with no fancy javascript, and look essentially like
<input type="submit">
And here's the PHP cURL request
$post_data = http_build_query(
array(
'lots_of' => 'values_here'
)
);
$url = 'https://asubdomain.formstack.com/forms/a_page_with_form';
$ch = curl_init($url);
$opts = array(
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_SSL_VERIFYHOST => FALSE,
CURLOPT_UNRESTRICTED_AUTH => TRUE,
CURLOPT_VERBOSE => TRUE,
// Above options for debugging because I'm desperate
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $post_data
);
curl_setopt_array($ch, $opts);
//Capture result and close connection
$result = curl_exec($ch);
$debug = curl_getinfo($ch);
curl_close($ch);
There's nothing out of the ordinary in curl_getinfo except the expected ["ssl_verify_result"]=> int(0), which I'm ignoring for debugging.
HTTP code is 200. If I echo $result, I can see that all form values are filled out, but the form never submitted and thus never redirected. If I then CLICK on submit, the form submits without issue and redirects as expected.
Again, this is not a problem with the first form, only the second. I'm guessing there's something about the underlying code on formstack that prevents cURL POST from submitting the form, but I can't seem to find it.
EDIT: I found the problem. There are two invisible elements on formstack forms. One of them is an input field called _submit which must be set to 1. The other is the form identifier, which is an integer.

Passing a parameter form PHP HTML form

I am using WordPress and Gravity Forms plugin and I am trying to pass a parameter from a third party provider to a Gravity Form with Dynamic Population from another page, using the below code
<form method="post" name="goToForm" action="http://www.example.com/?page_id=123">
<input type="hidden" name="param" value="Hello">
<input type="submit" name="fromSubmit" value="Submit">
</form>
Note that the above http://www.example.com/?page_id=123 is the Gravity Form URL.
the closest solution I found is using the HOOK method, but still I want to know how can I call the custom function that is created in functions.php using the HOOK approach from post and pass the parameter.
Any suggestions will be appreciated
If I'm understanding you correctly you want to pass the parameters on the form url?
You can accomplish this in 2 ways:
URL: http://www.example.com/?page_id=123
You can add a hidden field in the form. In the advanced section of the field, select Allow field to be populated dynamically and add the parameter name. So example I want to get the page_id:
After saving your form, inspect the hidden field and you should see it's value as 123
You can add a hook function:
add_filter('gform_field_value_page_id', 'my_custom_population_function');
function my_custom_population_function($value){
return $value'; //or do what ever you want with it
}
If you want to add the page title or id automatically to the form:
Add a hidden field, in the advanced section of the field, add this {embed_post:ID} (Post ID) to the default value. OR
Add a hidden field, in the advanced section of the field, add this {embed_post:post_title} (Post Title) to the default value.
Edit
The user is looking for http://www.gravityhelp.com/documentation/page/Gform_after_submission
You can get your fields/parameters from your form and then save it to your database, update a Wordpress page/post or send it to a third party service provider.
I'm not too sure what user would like to do with the parameter, so I'll show an example of sending it to a third party provider:
We want our entry field numbers so we can get the correct fields:
/* Getting correct field numbers */
add_action("gform_after_submission", "post_to_third_party", 10, 2);
function post_to_third_party($entry, $form){
// Lets get the IDs of the relevant fields and prepare an email message
$message = print_r($entry, true);
// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70);
// Send
mail('you#domain.com', 'Getting the Gravity Form Field IDs', $message);
}
You should get something like this in your mail:
Array
(
[id] => 64
[form_id] => 5
[date_created] => 2014-07-02 13:27:00
[is_starred] => 0
[is_read] => 0
[ip] => ::1
[source_url] => http://localhost/
[post_id] =>
[currency] => USD
[payment_status] =>
[payment_date] =>
[transaction_id] =>
[payment_amount] =>
[payment_method] =>
[is_fulfilled] =>
[created_by] => 1
[transaction_type] =>
[user_agent] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153
Safari/537.36
[status] => active
[1] => Name
[4] => Parameter
)
Where [1] => Name is a Name field and I entered Name for testing and [4] => Parameter is the parameter field with a default value of Parameter.
After we have our correct field numbers, we can then submit it to the third party provider, I'm using curl in this example:
/* Submitting to thirdparty.com */
add_action("gform_after_submission", "post_to_third_party", 10, 2);
function post_to_third_party($entry, $form){
//Submitting to thirdparty.com using curl
function post_to_url($url, $data) {
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, count($data));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($post, CURLOPT_HEADER, 1); //if you want headers
curl_setopt($post, CURLOPT_HEADER, "Content-Type:application/xml");
$result = curl_exec($post);
//If there's an error
if($result === false)
{
echo "Error Number:".curl_errno($ch)."<br>";
echo "Error String:".curl_error($ch);
}
curl_close($post);
}
if($form["id"] == 1){//Form ID
//Lets get the fields to match submission to thirdparty.com
$data = array(
"FirstName" => $entry["1"],
"ParameterName" => $entry["4"]
);
post_to_url("http://thirdparty.com", $data);
}
}
If you want the hook to work for a specific form gform_after_submission_1 will work for form id 1 only.

Forward data from php script to calendar

I have a project where I need to do the following: retrieve some data from a form, fill the database, create a response for the user and post the data to a third party. To give an example, it's like booking a ticket to a concert.The ajax call: You buy the ticket, you receive a response (whether the purchase was successful), a php script sends data to the database, and someone may be announced that a new ticket was bought. Now, I need to pass data to that "someone". Which is what I don't know how to do.
Or, like when someone posts a comment to my question on stackoverflow, I get a notification.
In my particular case, the user creates an event, receives a response and I will need to have certain parameters posted by the user on a calendar. It is important that I could hardly integrate the calendar with the script retrieving the data. I would rather need to "forward" the data to the calendar- quite like pushing notifications.
Can anyone please give me a clue what should I use, or what should I need in order to do the above?
The process will go like this:
AJAX
user----> php script->database
|_ calendar
So if i get you right, you could post your data to the calendar via curl:
$url = "http://www.your-url-to-the-calendar.com";
$postData = array(
"prop1" => "value1",
"prop2" => "value2",
"prop3" => "value3"
);
//urlify the data for the post
$data_string = "";
foreach ($postData as $key => $value)
$data_string .= urlencode($key) . '=' . urlencode($value) . '&';
$data_string = rtrim($data_string, '&');
//will output --> prop1=value1&prop2=value2=prop3=value3
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_POST => count($postData),
CURLOPT_POSTFIELDS => $data_string
));
$result = curl_exec($ch);
If your third party calendar does not require authentication than this would be the best way to post it, if you can not write to the database yourself.
When it requires authentication you would have to first login via curl (send credentials via curl-post, receive cookies, send cookies with your data)
Hope this helps.

Categories