Problems sending data to PHP with Curl - php

I need some advice with this curl script. I am trying to send values from the FORM to the curl script, but seems that the curl script doesn`t receive the info.
Here is the script:
<?php
if($_SERVER['REQUEST_METHOD'] != 'POST') {
$self = $_SERVER['PHP_SELF'];
?>
<form method="post" action="<?php echo $self; ?>" class="form-horizontal">
<fieldset>
<legend>SMS Contact</legend>
<div class="control-group">
<label for="basic" class="control-label">Name and Surname</label>
<div class="controls">
<input type="text" name="name" id="name" disabled class='input-square' value="<?php print $contactname;?> <?php print $contactsurname;?>">
</div>
</div>
<div class="control-group">
<label for="basic" class="control-label">Mobile No</label>
<div class="controls">
<input type="text" name="mobile" id="mobile" disabled class='input-square' value="<?php echo urlencode($contactmobile);?>">
</div>
</div>
<div class="control-group">
<label for="textcounter" class="control-label" id="textcounter">Textarea</label>
<div class="controls">
<textarea name="textcounter" id="textcounter" class='input-square span9 counter' data-max="160" rows='6'></textarea>
</div>
</div>
<div class="form-actions">
<button class="btn btn-primary" type="submit">Send SMS</button>
</div>
</fieldset>
</form>
<?php
} else {
$mobile = $_POST['mobile'];
$text = $_POST['textcounter'];
$username = 'xxxx';
$password = 'xxxx';
// Set Timezone
date_default_timezone_set('Africa/Johannesburg');
$date = date("m/d/y G.i:s", time());
// Create Unique ID
$code = md5(time());
$newid = $code.$clientid;
$sql="INSERT INTO sent_itmes (sent_id, sent_message, sent_date, sent_quantity, client_id, sent_mobile)VALUES('$newid', '$text', '$date', '1', '$clientid', '$mobile')";
$result=mysql_query($sql);
$url = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0"; // URL to calc.cgi
$fields = array(
'site'=>'',
'username'=>($username),
'password'=>($password),
'message'=>urlencode($text),
'msisdn'=>urlencode($mobile)
);
$fields_string="?";
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
ob_start();
curl_exec($ch);
ob_end_clean();
echo '<div class="alert alert-block alert-success">
<a class="close" data-dismiss="alert" href="#">×</a>
<h4 class="alert-heading">Success!</h4>
Your message has been Sent!
</div><br/><br/>Search Contact';
//close connection
curl_close($ch);
}
?>
When submitting the form, I get the error from response server "No recipients specified", so this means that the form value "mobile" doesnt pass though the value to the curl.
Help please, going off my mind.

Try adding a header that describes the content you post and maybe content you apply
curl_setopt ( $ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/x-www-form-urlencoded',
'Accept: text/html',
'Expect: ',
) );

use this for sending data
//open connection
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,POSTVARS.$fields_string); // this line is edited..
curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
//execute post
ob_start();
curl_exec($ch);
your order was wrong...
more info http://www.askapache.com/php/sending-post-form-data-php-curl.html

When you submit form with disabled field, that field do not sent:
<input type="text" name="mobile" id="mobile" disabled class='input-square' value="<?php echo urlencode($contactmobile);?>">
If you want to send "mobile", you should add hidden field for it. And maybe replace disabled field name

Related

How to pass user input to an api endpoint using php curl?

I am trying to POST HTML form login credentials(email & password) to an endpoint using PHP cURL and subsequently redirect to a different page(admin/index.php) after a successful login. However, I keep getting {"success":"false","message":"please provide email and password"} error from my nodejs login endpoint. I am inexperienced with cURL hence I am failing to notice where I am getting it wrong. Please help.
<?php
session_start();
// include('includes/config.php');
$error = ''; //Variable to Store error message;
if (isset($_POST['login'])) {
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = "Email or Password is Invalid";
} else {
//Define $user and $pass
$email = ($_POST['email']);
$password = ($_POST['password']);
$url = 'http://localhost:5000/auth/login';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERPWD, $email.":".$password);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(['email' => $email, 'password' =>$password]));
$result = curl_exec($curl);
echo $result;
if ($result == 200) {
$_SESSION['alogin'] = $email;
header("Location: admin/index.php"); // Redirecting to other page
} else {
$error = "Try to login.";
}
curl_close($curl);
}
}
?>
Here is the HTML form.
<div class="panel panel-info">
<div class="panel-heading">
LOGIN FORM
</div>
<div class="panel-body">
<form role="form" method="post" name="login" action="index.php" role="form">
<div class="form-group">
<label>Enter Email</label>
<input class="form-control" type="email" name="email" autocomplete="off" />
</div>
<div class="form-group">
<label>Password</label>
<input class="form-control" type="password" name="password" autocomplete="off" />
</div>
<button type="submit" name="login" class="btn btn-info">LOGIN</button>
</form>
</div>
</div>
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(['email' => $email, 'password' =>$password]));
There are two formats for CURLOPT_POSTFIELDS Neither is JSON.
$post = 'key1=value1&key2=value2&key3=value3';
$post = array('key1'=>$value1,'key2'=>$value2,'key3'=>'value3');
You may need to use urlencode() on username and password.
Were you told to use the CURLOPT_USERPWD,
That is unconventional.
And this is just wrong. It might work, but it is still wrong.
if ($result == 200) {
Use
$status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if ($status == 200){...

MailChimp Add Subscriber using API 3.0 PHP

I am trying to add a php file that adds a new subscriber to my MailChimp list. Here is my form that SHOULD trigger the php file to add the new subscriber:
<form action="/scripts/freemonth_action.php" class="email_form_freemonth" method="post">
<h3>Get your first month free</h3>
<div class="form-group customised-formgroup"> <span class="icon-user"></span>
<input type="text" name="full_name" class="form-control" placeholder="Name">
</div>
<div class="form-group customised-formgroup"> <span class="icon-envelope"></span>
<input type="email" name="email" class="form-control" placeholder="Email">
</div>
<!--<div class="form-group customised-formgroup"> <span class="icon-telephone"></span>
<input type="text" name="phone" class="form-control" placeholder="Phone (optional)">
</div>-->
<div class="form-group customised-formgroup"> <span class="icon-laptop"></span>
<input type="text" name="website" class="form-control" placeholder="Website (optional)">
</div>
<!--<div class="form-group customised-formgroup"> <span class="icon-bubble"></span>
<textarea name="message" class="form-control" placeholder="Message"></textarea>
</div>-->
<div>
<br>
<button style="margin: 0 auto" type="submit" class="btn btn-fill full-width">GET FREE MONTH<span class="icon-chevron-right"></span></button>
</div>
</form>
And here is freemonth_action.php:
<?php
session_start();
if(isset($_POST['submit'])){
$name = trim($_POST['full_name']);
$email = trim($_POST['email']);
if(!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL) === false){
// MailChimp API credentials
$apiKey = '6b610769fd3353643c7427db98d43ad6-us16';
$listID = '0cf013d1d9';
// MailChimp API URL
$memberID = md5(strtolower($email));
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . $memberID;
// member information
$json = json_encode([
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => [
'NAME' => $name,
]
]);
// send a HTTP POST request with curl
$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_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo json_encode($result);
// store the status message based on response code
if ($httpCode == 200) {
$_SESSION['msg'] = '<p style="color: #34A853">You have successfully subscribed to CodexWorld.</p>';
} else {
switch ($httpCode) {
case 214:
$msg = 'You are already subscribed.';
break;
default:
$msg = 'Some problem occurred, please try again.';
break;
}
$_SESSION['msg'] = '<p style="color: #EA4335">'.$msg.'</p>';
}
}else{
$_SESSION['msg'] = '<p style="color: #EA4335">Please enter valid email address.</p>';
}
}
I'm not even sure how to debug this, because when i do echo $result (or anything like that) I do not see anything on the page or logged to the console. I'm also open to any suggestions that use javascript as long as it is still the 3.0 API.
Your subscription code works fine. The reason you aren't seeing any result is because isset($_POST['submit']) looks for an element with the name 'submit' rather than the type 'submit'. Just add the name attribute to your button, and it should work for you:
<button style="margin: 0 auto" type="submit" name="submit" class="btn btn-fill full-width">GET FREE MONTH<span class="icon-chevron-right"></span></button>
Also, you should keep the API key secret so other people can't access your MailChimp account through the API. I'd recommend disabling your current key and creating a new one. See MailChimp's knowledgebase article about API Keys for more details.

execute php function on click in html 204 returneed

I'm trying to post the html form data below to hubspot but when i have it deployed to either heroku or aws elastic beanstalk I receive 204 back instead of my data being posted to the crm. I used the solution found here how to execute php function on html button click
but have had no success getting the information needed into hubspot.
html file
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'index.php', // <=== CALL THE PHP FUNCTION HERE.
success: function ( data ) {
alert( data ); // <=== VALUE RETURNED FROM FUNCTION.
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form>
<div class="row">
<div class="row">
<div class="col-lg-12 form-group">
<label for="email">Email</label>
<input
type="email"
id="email"
class="form-control"
name="email"
required
pattern="'^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$'"
>
</div>
<div class="row moveRight">
<div class="col-lg-12 form-group">
<label for="firstname">First Name</label>
<input
type="text"
id="firstname"
class="form-control"
name="firstname"
required
>
</div>
</div>
<div class="row moveRight">
<div class="col-lg-12 form-group">
<label for="lastname">Last Name</label>
<input
type="text"
id="lastname"
class="form-control"
name="lastname"
required
>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<button onclick="myAjax()" class="btn btn-success" id="startnode" type="submit">Submit</button>
</div>
</div>
</div>
</div>
</form>
<?php include 'index.php';?>
</body>
</html>
php file
<?php
function bb() {
//Process a new form submission in HubSpot in order to create a new Contact.
$hubspotutk = $_COOKIE['hubspotutk']; //grab the cookie from the visitors browser.
$ip_addr = $_SERVER['REMOTE_ADDR']; //IP address too.
$hs_context = array(
'hutk' => $hubspotutk,
'ipAddress' => $ip_addr,
'pageUrl' => 'http://www.example.com/form-page',
'pageName' => 'Example Title'
);
$hs_context_json = json_encode($hs_context);
//Need to populate these variable with values from the form.
$str_post = "firstname=" . urlencode($firstname)
. "&lastname=" . urlencode($lastname)
. "&email=" . urlencode($email)
. "&hs_context=" . urlencode($hs_context_json); //Leave this one be
//replace the values in this URL with your portal ID and your form GUID
$endpoint = 'https://forms.hubspot.com/uploads/form/v2/hubid/guid';
$ch = #curl_init();
#curl_setopt($ch, CURLOPT_POST, true);
#curl_setopt($ch, CURLOPT_POSTFIELDS, $str_post);
#curl_setopt($ch, CURLOPT_URL, $endpoint);
#curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = #curl_exec($ch); //Log the response from HubSpot as needed.
$status_code = #curl_getinfo($ch, CURLINFO_HTTP_CODE); //Log the response status code
#curl_close($ch);
echo $status_code . " " . $response;
}
bb();
?>

(PHP) Web form inserting blank values into the database! Error - array(1) { [“g-recaptcha-response”]=> string(484)-

When sending information from my web form, it inserts blank values into the database. The auto increments on the ID work fine. When performing an Var Dump $_POST, I get this response:
array(1) { ["g-recaptcha-response"]=> string(484) + random letters and numbers
I am trying to pass three values into my database from the user. First Name. Last Name and Email. It checks the values on my web site and looks like the Google Recaptcha V2 is working the way it was intended. I think it has something to do with the Recaptcha PHP script is not passing it to my insert PHP script.
Any Ideas? Thanks for taking the time to help me out.
PHP:
<?php
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => '',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);
if (!$res['success']) {
// What happens when the CAPTCHA wasn't checked
echo '<p>Please Check the Security CAPTCHA Box.</p><br>';
} else {
// If CAPTCHA is successfully completed...
// Paste mail function or whatever else you want to happen here!
$dbhost = "localhost";
$dbname = "";
$dbusername = "";
$dbpassword = "";
try {
$link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $link->prepare("INSERT INTO MailV2(Fname, Lname, Email) VALUES(:Fname, :Lname, :Email)");
$FirstName = $_POST['Fname'];
$LastName = $_POST['Lname'];
$Email = $_POST['Email'];
$statement->execute(array(
":Fname" => "$FirstName",
":Lname" => "$LastName",
":Email" => "$Email"));
// Echo Successful attempt
echo "<p Data added to database.</p></br></br>";
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
?>
HTML:
<article class="contact-form">
<form action="" method="POST">
<div class="col-md-5 col-md-offset-1 contact-form-left">
<input class="Fname" type="text" placeholder="FIRST NAME*">
<input class="Lname" type="text" placeholder="LAST NAME*">
<input class="Email" type="email" placeholder="EMAIL*">
</div>
<div class="col-md-5 contact-form-right text-right">
<div class="g-recaptcha" data-sitekey=""></div>
<br>
<input type="submit" class="submit-btn" value="Subscribe">
</div>
</form>
</article>
In your html form, the name and email fields don't have a name attribute so they aren't included in the response.
Thanks KAF, I just realize that and fix it. I was so fixed on my php, I didn't notice it until I posted it here. It always the simple things.
Fixed HTML:
<article class="contact-form">
<form action="" method="POST">
<div class="col-md-5 col-md-offset-1 contact-form-left">
<input name="Fname" type="text" placeholder="FIRST NAME*">
<input name="Lname" type="text" placeholder="LAST NAME*">
<input name="Email" type="email" placeholder="EMAIL*">
</div>
<div class="col-md-5 contact-form-right text-right">
<div class="g-recaptcha" data-sitekey=""></div>
<br>
<input type="submit" class="submit-btn" value="Subscribe">
</div>
</form>
</article>

Simplest way to stop email submission if field is empty

Im trying to duplicate my client side validation on the server (PHP). What is the simplest way to make sure a field has been filled out? I've done it like this before but am having some issues, is there a better way?
<?php
if(empty($_POST['Contact0FirstName']) || empty($_POST['Contact0Email']) ||
empty($_POST['Contact0Phone1']) || empty($_POST['CaptchaInput']) || !empty($_POST['LeadBlind'])) {
echo "Error";
die();
} else {
//set POST variables
$url = 'xxx';
$infusion_xid = $_POST["xxx"];
$infusion_type = $_POST["xxx"];
$infusion_name = $_POST["xxx"];
$Contact0FirstName = $_POST["Contact0FirstName"];
$Contact0Email = $_POST["Contact0Email"];
$Contact0Phone1 = $_POST["Contact0Phone1"];
$fields = array(
'infusion_xid'=>urlencode($infusion_xid),
'infusion_type'=>urlencode($infusion_type),
'infusion_name'=>urlencode($infusion_name),
'Contact0FirstName'=>urlencode($Contact0FirstName),
'Contact0Email'=>urlencode($Contact0Email),
'Contact0Phone1'=>urlencode($Contact0Phone1)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string = rtrim($fields_string,'& ');
//open connection
$ch = curl_init($url);
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//their return html
$output = curl_exec($ch);
//echo "TEST";
echo $output;
curl_close($ch);
}
?>
<form id="Lead" method="post" action="PHP/Lead.php" accept-charset="UTF-8">
<ul id="LeadForm">
<li>*required field</li>
<li>
<input type="hidden" name="LeadBlind" id="LeadBlind">
<label for="Contact0FirstName">1 | First Name*</label>
<label for="Contact0Email">2 | Email*</label>
<label for="Contact0Phone1">3 | Daytime Phone*</label>
</li>
<li>
<input type="text" name="Contact0FirstName" id="Contact0FirstName">
<input type="text" name="Contact0Email" id="Contact0Email">
<input type="text" name="Contact0Phone1" id="Contact0Phone1">
</li>
<li>
<label for="CaptchaInput">4 | Please enter the code</label>
</li>
<li>
<input type="text" class="numbers" name="Captcha" id="Captcha" value="" readonly>
<input type="text" class="numbers" name="CaptchaInput" id="CaptchaInput" size="6" maxlength="6">
</li>
<li>
<input type="submit" id="LeadSend" value="Try It Now!">
<span id="processing">Submitting Your Request</span>
</li>
</ul>
<div class="clear"></div>
</form>
I need "LeadBlind" to be empty, it is a hidden input that only form filling bots would fill in, so if it has a value it should trigger the error. The ajax function is based on what is returned, if it's "error" it displays an error msg, otherwise a success one. thx for the help!

Categories