Contact form 7, post data to seperate php file - php

Im using CF7 to get user details.
When user submit his form, i wanna get the input fields to my custom.php file and do some stuff in there.
I tried doing that with the js on_sent_ok: URL/custom.php?.....fields data.... but i think this is not the right method. But anyway that is working for me.
Is there a way to do that with hook action? I tried this.
function wpcf7_do_something (&$cfdata) {
$goURL = 'http://contactform7.com';
$cfdata->set_properties( array( 'additional_settings' => "on_sent_ok: \"location = '".$goURL."';\"" ) );
}
add_action("wpcf7_before_send_mail", "wpcf7_do_something");
I tried to echo something , triger a js console.log, and to redirect inside the wpcf7_do_something function but nothing is works. I really dont know if it works at all.
Is there a way to test if this action is working?
Is there a way to redirect to onother location?
Thnx

Once you forward the user after a successful submission, your form data is lost. You can intercept the form data processing in WP by hooking into the before_send_mail action hook provided by CF7. This allows you to access the form data on the server, preprocess it if necessary, and then POST the data to your custom processor script.
// Create the new wordpress action hook before sending the email from CF7
add_action( 'wpcf7_before_send_mail', 'my_conversion' );
function my_conversion( $contact_form ) {
$submission = WPCF7_Submission::get_instance();
// Get the post data and other post meta values.
if ( $submission ) {
$posted_data = $submission->get_posted_data();
// these variables are examples of other things you may want to pass to your custom handler
$remote_ip = $submission->get_meta( 'remote_ip' );
$url = $submission->get_meta( 'url' );
$timestamp = gmdate("Y-m-d H:i:s", $submission->get_meta( 'timestamp' ));
$title = wpcf7_special_mail_tag( '', '_post_title', '' );
// If you have checkboxes or other multi-select fields, make sure you convert the values to a string
$mycheckbox1 = implode(", ", $posted_data["checkbox-465"]);
$mycheckbox2 = implode(", ", $posted_data["checkbox-466"]);
// Encode the data in a new array in JSON format
$data = json_encode(array(
"posted_key_name_1" => "{$posted_data['input-name-1']}",
"posted_key_name_2" => "{$posted_data['input-name-2']}",
"posted_key_name_..." => "{$posted_data['input-name-...']}",
"posted_key_name_n" => "{$posted_data['input-name-n']}",
// any additional data to include that wasn't part of the form post?
"From URL" => "$url",
"From IP" => "$remote_ip",
"Page Title" => "$title"
));
// Finally send the data to your custom endpoint
$ch = curl_init("https://www.YOURDOMAIN.com/custom.php");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,5); //Optional timeout value
curl_setopt($ch, CURLOPT_TIMEOUT, 5); //Optional timeout value
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
}
This will post the selected form data to your custom processor right before CF7 processes the form and sends the confirmation mail. You'll still want to make sure the user experience is satisfactory by either displaying the CF7 confirmation message that the form has been submitted, or forwarding the user to a thank you page using the JS redirect -> on_sent_ok: https://yourdomain.com/thanks/
If it is necessary that the user visits your custom processor page because the processor page generates information important to the user, you could package up all the form data into a URL string and append that onto the processing URL. Then, in your processing.php code, you'd use $_GET[] to access the data.
See this article for details on how to dynamically update set the redirect URL: How to change contact form 7 Redirecting URL dynamically - WordPress
Submitting data to a webhook code from this page: http://moometric.com/integrations/wp/contact-form-7-zapier-webhook-json-post/

Related

extract reCaptcha from web page to be completed externally via cURL and then return results to view page

I am creating a web scraper for personal use that scrape car dealership sites based on my personal input but several of the sites that I attempting to collect data from a blocked by a redirected captcha page. The current site I am scraping with curl returns this HTML
<html>
<head>
<title>You have been blocked</title>
<style>#cmsg{animation: A 1.5s;}#keyframes A{0%{opacity:0;}99%{opacity:0;}100%{opacity:1;}}</style>
</head>
<body style="margin:0">
<p id="cmsg">Please enable JS and disable any ad blocker</p>
<script>
var dd={'cid':'AHrlqAAAAAMA1gZrYHNP4MIAAYhtzg==','hsh':'C0705ACD75EBF650A07FF8291D3528','t':'fe','host':'geo.captcha-delivery.com'}
</script>
<script src="https://ct.captcha-delivery.com/c.js"></script>
</body>
</html>
I am using this to scrape the page:
<?php
function web_scrape($url)
{
$ch = curl_init();
$imei = "013977000272744";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_COOKIE, '_ym_uid=1460051101134309035; _ym_isad=1; cxx=80115415b122e7c81172a0c0ca1bde40; _ym_visorc_20293771=w');
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'imei' => $imei,
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
return $server_output;
curl_close($ch);
}
echo web_scrape($url);
?>
And to reiterate what I want to do; I want to collect the Recaptcha from this page so when I want to view the page details on an external site I can fill in the Recaptcha on my external site and then scrape the page initially imputed.
Any response would be great!
Datadome is currently utilizing Recaptcha v2 and GeeTest captchas, so this is what your script should do:
Navigate to redirection https://geo.captcha-delivery.com/captcha/?initialCid=….
Detect what type of captcha is used.
Obtain token for this captcha using any captcha solving service like Anti Captcha.
Submit the token, check if you were redirected to the target page.
Sometimes target page contains an iframe with address https://geo.captcha-delivery.com/captcha/?initialCid=.. , so you need to repeat from step 2 in this iframe.
I’m not sure if steps above could be made with PHP, but you can do it with browser automation engines like Puppeteer, a library for NodeJS. It launches a Chromium instance and emulates a real user presence. NodeJS is a must you want to build pro scrapers, worth investing some time in Youtube lessons.
Here’s a script which does all steps above: https://github.com/MoterHaker/bypass-captcha-examples/blob/main/geo.captcha-delivery.com.js
You’ll need a proxy to bypass GeeTest protection.
based on the high demand for code, HERE is my upgraded scraper that bypassed this specific issue. However my attempt to obtain the captcha did not work and I still have not solved how to obtain it.
include "simple_html_dom.php";
/**
* Get a web file (HTML, XHTML, XML, image, etc.) from a URL. Return an
* array containing the HTTP server response header fields and content.
*/
// This function is where the Magic comes from. It bypasses ever peice of security carsales.com.au can throw at me
function get_web_page( $url ) {
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_SSL_VERIFYPEER => false // Disabled SSL Cert checks
);
$ch = curl_init( $url ); //initiate the Curl program that we will use to scrape data off the webpage
curl_setopt_array( $ch, $options ); //set the data sent to the webpage to be readable by the webpage (JSON)
$content = curl_exec( $ch ); //creates function to read pages content. This variable will be used to hold the sites html
$err = curl_errno( $ch ); //errno function that saves all the locations our scraper is sent to. This is just for me so that in the case of a error,
//I can see what parts of the page has it seen and more importantly hasnt seen
$errmsg = curl_error( $ch ); //check error message function. for example if I am denied permission this string will be equal to: 404 access denied
$header = curl_getinfo( $ch ); //the information of the page stored in a array
curl_close( $ch ); //Closes the Curler to save site memory
$header['errno'] = $err; //sending the header data to the previously made errno, which contains a array path of all the places my scraper has been
$header['errmsg'] = $errmsg; //sending the header data to the previously made error message checker function.
$header['content'] = $content; //sending the header data to the previously made content checker that will be the variable holder of the webpages HTML.
return $header; //Return all the pages data and my identifying functions in a array. To be used in the presentation of the search results.
};
//using the function we just made, we use the url genorated by the form to get a developer view of the scraping.
$response_dev = get_web_page($url);
// print_r($response_dev);
$response = end($response_dev); //takes only the end of the developer response because the rest is for my eyes only in the case that the site runs into a issue

How do I send info to this API using cURL and PUT?

I am working with an API that is documented here: https://cutt.ly/BygHsPV
The documentation is a bit thin, but I am trying to understand it the best I can. There will not be a developer from the creator of the API available before the middle of next week, and I was hoping to get stuff done before that.
Basically what I am trying to do is update the consent of the customer. As far as I can understand from the documentation under API -> Customer I need to send info through PUT to /customers/{customerId}. That object has an array called "communicationChoices".
Going into Objects -> CustomerUpdate I find "communicationChoices" which is specified as "Type: list of CommunicationChoiceRequest". That object looks like this:
{
"choice": true,
"typeCode": ""
}
Doing my best do understand this, I have made this function:
function update_customer_consent() {
global $userPhone, $username, $password;
// Use phone number to get correct user
$url = 'https://apiurlredacted.com/api/v1/customers/' . $userPhone .'?customeridtype=MOBILE';
// Initiate cURL.
$ch = curl_init( $url );
// Specify the username and password using the CURLOPT_USERPWD option.
curl_setopt( $ch, CURLOPT_USERPWD, $username . ":" . $password );
// Tell cURL to return the output as a string instead
// of dumping it to the browser.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
// Data to send
$data = [
"communicationChoices" => [
"communicationChoiceRequest" => [
"choice" => true,
"typeCode" => "SMS"
]
]
];
$json_payload = json_encode($data);
print_r($json_payload);
// Set other options
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($json_payload)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_payload);
// Execute the cURL request
$response = curl_exec($ch);
// Check for errors.
if( curl_errno( $ch ) ) :
// If an error occured, throw an Exception.
throw new Exception( curl_error( $ch ) );
endif;
if (!$response)
{
return false;
} else {
// Decode JSON
$obj = json_decode( $response );
}
print_r($response);
}
I understand that this is very hard to debug without knowing what is going on within the API and with limited documentation, but I figured asking here was worth a shot anyway.
Basically, $json_payload seems to be a perfectly fine JSON object. The response from the API however, is an error code that means unknown error. So I must be doing something wrong. Maybe someone has more experience with APIs and such documentation and can see what I should really be sending and how.
Any help or guidance will be highly appreciated!
before you test your code, you can use the form provided on the API Documentation.
when you navigate to API > Customers > /customers/{customerId} (GET), you will see a form on the right side of the page (scroll up). you need to provide the required values on the form then hit Submit button. you will surely get a valid data for communicationChoices based on the result from the Response Text section below the Submit button.
now, follow the data structure of communicationChoices object that you get from the result and try the same on API > Customers > /customers/{customerId} (PUT) form.
using the API forms, you may be able to instantly see a success or error from your input (data structure), then translate it to your code.

Make several POST CURL API in one request PHP

I am trying to do some POST with CURL in some way, I explain:
I am using the PhpExcel library, the idea is to upload an excel file that contains a table with several records and the names of the field, with a PhpExcel function I go through each record, so I save it in an array.
The next step is to make a request that sends each of the records to a URL, in this case it is an API URL to edit several products, waiting for parameters (which are each of the fields that are sent in a record) , I have already armed the function to send a single request, I just need to know how I can send several records at once in a single request.
Summary:
I upload the excel file that contains several records. (done)
I keep these records in an array through a function that collects the contents of PhpExcel (done)
Make a POST request with CURL that runs through each of the records and send them at the same time (I have only managed to send only one record)
This code is for call function send POST
private function peticion_get_post($ruta,$formdata,$tipo){
$apiurl = 'https://url/api/v1/';
$url = $apiurl.$ruta;
$postvars = '';
foreach($formdata as $key=>$value) {
$postvars .= $key . "=" . $value . "&";
}
$ch = curl_init();
if($tipo == 'GET'){
curl_setopt($ch,CURLOPT_URL,$url."?".$postvars);
}
if($tipo == 'POST'){
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
}
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch,CURLOPT_CUSTOMREQUEST, $tipo);
//curl_setopt($ch,CURLOPT_POST, $tipo);//0 for a GET request y 1 para POST
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$respuesta = curl_exec($ch);
$resultado = json_decode($respuesta);
return $resultado;
}
This code is for call function before and sends content from form
$formdata_post = array(
'id_box' => $id_box,
'number' => $number,
'label' => $label
);
$ruta = 'edit.json';
$resultado_post = $this->peticion_get_post($ruta, $formdata_post, 'POST');
I work with Codeigniter, currently, I send the content by JSON through a form and just send a record, I just have to edit the form and send the content that is in the array that generated the PhpExcel when uploading the file.

transfer of data on URL click

I am new to JSON data transfer. I want to make a user click on a link in a webpage and that should redirect the user to another page with his login credentials in the url and display it there. Now this all I want to send and receive through JSON . I am working on PHP environment. I am adding a short code on which I am working but not knowing how to proceed exactly.
send.php
<?php
$data = '{ "user" : [
{ "email" : "xyz#gmail.com",
"password" : "xyz#123",
"employee_id" : 77
}
]
} ';
$url_send ="http://localhost/cwmsbi/recieve.php";
$str_data = json_encode($data);
function sendPostData($url_send, $post){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($post))
);
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
return $result;
}
echo " " . sendPostData($url_send, $str_data);
?>
And receive.php
<?php
$json_input_data=json_decode(file_get_contents('php://input'),TRUE);
print_r( $json_input_data);
?>
Now when I am running send.php on my localhost, it displays the data on same page but does not goes to recieve.php.
How this can be achieved? I am curious and in need of this too. How can I run a JSON file and where should i obtain results? Your guidance will be immensely useful to me right now.
First of all i see you are json encoding $data two times (as when it gets defines it is already a json string and then you do $str_data = json_encode($data);).
If you want to achive the change of location with post data too, you can't use curl
(POST data and redirect user by PHP CURL - read this question for further infos) - and i don't think you can do it by php only.
If i was trying to achive what you're trying to achive (and i would never make a page to show login password to users - as it is bad practice to show a password, even in emails), i suggest to set the json string into $_SESSION variable in send.php and redirect with header("Location: http://localhost/cwmsbi/recieve.php") where you get the json data from $_SESSION variable and you print it.
I did not make an example as i think this one perfectly suites you:
https://stackoverflow.com/a/42215249/9606459
Extra hint: even if placing the password in php $_SESSION variable is better than put it in post request, remember you are doing bad practice and at least remember to empty out that json string in $_SESSION variable after you print it.
e.g.:
unset($_SESSION['user_data']);

Submitting a form using PHP

I have a submit form with method POST, I want to write a script that can automatically submit this form, the reason why I need this is for testing purposes. I need a lot of data in little time in order to test a search based on those form fields, and I do not have time to mannulally do this. Is this possible?
You can use curl to simulate form submit.
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/script.php");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, true ); //enable POST method
// prepare POST data
$post_data = array('name1' => 'value1', 'name2' => 'value2', 'name3' => 'value3');
// pass the POST data
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data );
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
Source:http://php.net/manual/en/book.curl.php
if your not comfortable using curl you could use a php library called snoopy that simulates a web browser. It automates the task of retrieving web page content and posting forms.
<?php
/* load the snoopy class and initialize the object */
require('../includes/Snoopy.class.php');
$snoopy = new Snoopy();
/* set some values */
$p_data['color'] = 'Red';
$p_data['fruit'] = 'apple';
$snoopy->cookies['vegetable'] = 'carrot';
$snoopy->cookies['something'] = 'value';
/* submit the data and get the result */
$snoopy->submit('http://phpstarter.net/samples/118/data_dump.php', $p_data);
/* output the results */
echo '<pre>' . htmlspecialchars($snoopy->results) . '</pre>';
?>
Let PHP fill the form with data and print out a Javascript that posts the form, PHP can not post it on it's own thou.
You can use php.net/curl to send POST requests with PHP.

Categories