Related
my site looks like this.
<?php
include 'dbd.php'; //DB Login details
?>
<!DOCTYPE html>
<html>
<head>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<?php
$showFormular = true;
if (isset($_POST['submit'])) {
$error = false;
if (!$error) {
$statement = $pdo->prepare("INSERT INTO table (email, name) VALUES (:email, :name,)");
$result = $statement->execute(array(
'email' => $email,
'name' => $name
));
if ($result) {
echo "Your Registration was Successful";
$showFormular = false;
} else {
echo 'Could not register your Account';
}
}
}
if ($showFormular) {
?>
<form action="<?php echo ($_SERVER['PHP_SELF']); ?>" method="post">
<input placeholder="Your Forum Name Here" name="name" required>
<input placeholder="Your Forum Email Here" name="email" required>
<div class="g-recaptcha" data-sitekey="public key"></div>
<input name="submit" type="submit">
</form>
<?php
}
?>
</body>
</html>
The Problem what I have is that I dont know how to implement the Serverside ReCaptcha Check. I tried it with the following method but there I get obviously the error that the function is empty because its getting executed directly.
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify',
CURLOPT_POST =>1,
CURLOPT_POSTFIELDS => [
'secret' => 'privat key',
'response' => $_POST['g-recaptcha-response'],
],
]);
I hope I explained it good enough that someone can help me.
Why are you trying to use curl command ? You can do this by directly with php code.
First of all download this php reCaptcha library and import your project : reCaptcha gitHub
Secondly, after you action call your php and implement this on your php code.
require_once('your-imported-autoload.php-path'); ex:Assets/reCaptcha/autoload.php
$privatekey = "-your private key-";
$recaptcha = new \ReCaptcha\ReCaptcha($privatekey);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'],
$_SERVER['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
// Your code here to handle a successful verification
}
For last, for cURL you are trying to connect through SSL and have to handle it
curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
There seems to be something wrong with this documentation: http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-authentication-HTTPPOST.html
I followed it exactly and it does seem to work. I always got SignatureDoesNotMatch error. v2 authorization works though. Makes me wonder if this some kind of Alpha-stage quality product.
Below is my php code. I tried to mimic the example in this page: http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html
<?php
$secret = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY';
$datenow = '20130806';
$region = 'us-east-1';
$service = 's3';
$terminator = 'aws4_request';
$policy = '{ "expiration": "2013-08-07T12:00:00.000Z",
"conditions": [
{"bucket": "examplebucket"},
["starts-with", "$key", "user/user1/"],
{"acl": "public-read"},
{"success_action_redirect": "http://examplebucket.s3.amazonaws.com/successful_upload.html"},
["starts-with", "$Content-Type", "image/"],
{"x-amz-meta-uuid": "14365123651274"},
["starts-with", "$x-amz-meta-tag", ""],
{"x-amz-credential": "AKIAIOSFODNN7EXAMPLE/'.$datenow.'/'.$region.'/'.$service.'/'.$terminator.'"},
{"x-amz-algorithm": "AWS4-HMAC-SHA256"},
{"x-amz-date": "'.$datenow.'T000000Z" }
]
}';
$policy64 = base64_encode($policy);
assert($policy64 == $policy64);
$targetPolicy64 = 'eyAiZXhwaXJhdGlvbiI6ICIyMDEzLTA4LTA3VDEyOjAwOjAwLjAwMFoiLA0KICAiY29uZGl0aW9ucyI6IFsNCiAgICB7ImJ1Y2tldCI6ICJleGFtcGxlYnVja2V0In0sDQogICAgWyJzdGFydHMtd2l0aCIsICIka2V5IiwgInVzZXIvdXNlcjEvIl0sDQogICAgeyJhY2wiOiAicHVibGljLXJlYWQifSwNCiAgICB7InN1Y2Nlc3NfYWN0aW9uX3JlZGlyZWN0IjogImh0dHA6Ly9leGFtcGxlYnVja2V0LnMzLmFtYXpvbmF3cy5jb20vc3VjY2Vzc2Z1bF91cGxvYWQuaHRtbCJ9LA0KICAgIFsic3RhcnRzLXdpdGgiLCAiJENvbnRlbnQtVHlwZSIsICJpbWFnZS8iXSwNCiAgICB7IngtYW16LW1ldGEtdXVpZCI6ICIxNDM2NTEyMzY1MTI3NCJ9LA0KICAgIFsic3RhcnRzLXdpdGgiLCAiJHgtYW16LW1ldGEtdGFnIiwgIiJdLA0KDQogICAgeyJ4LWFtei1jcmVkZW50aWFsIjogIkFLSUFJT1NGT0ROTjdFWEFNUExFLzIwMTMwODA2L3VzLWVhc3QtMS9zMy9hd3M0X3JlcXVlc3QifSwNCiAgICB7IngtYW16LWFsZ29yaXRobSI6ICJBV1M0LUhNQUMtU0hBMjU2In0sDQogICAgeyJ4LWFtei1kYXRlIjogIjIwMTMwODA2VDAwMDAwMFoiIH0NCiAgXQ0KfQ==';
// echo base64_decode($targetPolicy64);
// echo $policy64."\n".$targetPolicy64;
assert($policy64 == $targetPolicy64);
// At this point everything seems to work well. Converting the policy
// to base64 resulted in exactly the same string with example.
// The problem, however, happens when calculating the signature,
// as shown below:
$targetSignature = '21496b44de44ccb73d545f1a995c68214c9cb0d41c45a17a5daeec0b1a6db047';
$signature = '';
$hash1 = hash_hmac(
'sha256',
$datenow,
"AWS4".$secret,
true
);
$hash2 = hash_hmac(
'sha256',
$region,
$hash1,
true
);
$hash3 = hash_hmac(
'sha256',
$service,
$hash2,
true
);
$signingKey = hash_hmac(
'sha256',
$terminator,
$hash3,
true
);
$signature = base64_encode(hash_hmac(
'sha256',
$policy64,
$signingKey,
true
));
echo $signature."\n".$targetSignature;
// This assertion never passed.
assert($signature == $targetSignature);
I thought it was the problem of the example so I tried creating a sample browser upload page with exactly the same methods, but it did not work either.
Running the signature signing code here: PHP hash_hmac not matching AWS Signature 4 example however, works, so I doubt the issue is during signature creation, or is it?
Please help, anyone.
<?php
// Fill These In!
define('S3_BUCKET', '');
define('S3_KEY', '');
define('S3_SECRET', '');
define('S3_REGION', ''); // S3 region name: http://amzn.to/1FtPG6r
define('S3_ACL', 'private'); // File permissions: http://amzn.to/18s9Gv7
// Stop Here
$algorithm = "AWS4-HMAC-SHA256";
$service = "s3";
$date = gmdate('Ymd\THis\Z');
$shortDate = gmdate('Ymd');
$requestType = "aws4_request";
$expires = '86400'; // 24 Hours
$successStatus = '201';
$scope = [
S3_KEY,
$shortDate,
S3_REGION,
$service,
$requestType
];
$credentials = implode('/', $scope);
$policy = [
'expiration' => gmdate('Y-m-d\TG:i:s\Z', strtotime('+6 hours')),
'conditions' => [
['bucket' => S3_BUCKET],
['acl' => S3_ACL],
[
'starts-with',
'$key',
''
],
['success_action_status' => $successStatus],
['x-amz-credential' => $credentials],
['x-amz-algorithm' => $algorithm],
['x-amz-date' => $date],
['x-amz-expires' => $expires],
]
];
$base64Policy = base64_encode(json_encode($policy));
// Signing Keys
$dateKey = hash_hmac('sha256', $shortDate, 'AWS4' . S3_SECRET, true);
$dateRegionKey = hash_hmac('sha256', S3_REGION, $dateKey, true);
$dateRegionServiceKey = hash_hmac('sha256', $service, $dateRegionKey, true);
$signingKey = hash_hmac('sha256', $requestType, $dateRegionServiceKey, true);
// Signature
$signature = hash_hmac('sha256', $base64Policy, $signingKey);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Direct Upload Example</title>
<style>
.progress {
position: relative;
width: 100%;
height: 15px;
background: #C7DA9F;
border-radius: 10px;
overflow: hidden;
}
.bar {
position: absolute;
top: 0; left: 0;
width: 0; height: 15px;
background: #85C220;
}
.bar.red { background: tomato; }
</style>
</head>
<body>
<!-- Direct Upload to S3 -->
<!-- URL prefix (//) means either HTTP or HTTPS (depending on which is being currently used) -->
<form action="//<?php echo S3_BUCKET . "." . $service . "-" . S3_REGION; ?>.amazonaws.com"
method="POST"
enctype="multipart/form-data"
class="direct-upload">
<!-- Note: Order of these is Important -->
<input type="hidden" name="key" value="${filename}">
<input type="hidden" name="acl" value="<?php echo S3_ACL; ?>">
<input type="hidden" name="success_action_status" value="<?php echo $successStatus; ?>">
<input type="hidden" name="policy" value="<?php echo $base64Policy; ?>">
<input type="hidden" name="X-amz-algorithm" value="<?php echo $algorithm; ?>">
<input type="hidden" name="X-amz-credential" value="<?php echo $credentials; ?>">
<input type="hidden" name="X-amz-date" value="<?php echo $date; ?>">
<input type="hidden" name="X-amz-expires" value="<?php echo $expires; ?>">
<input type="hidden" name="X-amz-signature" value="<?php echo $signature; ?>">
<input type="file" name="file">
<!-- Progress Bar to show upload completion percentage -->
<div class="progress"><div class="bar"></div></div>
</form>
<!-- Used to Track Upload within our App -->
<form action="server.php" method="POST">
<input type="hidden" name="upload_original_name" id="upload_original_name">
<label for="upload_custom_name">Name:</label><br />
<input type="text" name="upload_custom_name" id="upload_custom_name"><br />
<input type="submit" value="Save"/>
</form>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script src="fileupload/jquery.fileupload.js"></script>
<script>
$(document).ready(function () {
$('.direct-upload').each(function () {
var form = $(this);
form.fileupload({
url: form.attr('action'),
type: 'POST',
datatype: 'xml',
add: function (event, data) {
// Message on unLoad.
// Shows 'Are you sure you want to leave message', just to confirm.
window.onbeforeunload = function () {
return 'You have unsaved changes.';
};
// Actually submit to form, sending the data.
data.submit();
},
progress: function (e, data) {
// This is what makes everything really cool, thanks to that callback
// you can now update the progress bar based on the upload progress.
var percent = Math.round((data.loaded / data.total) * 100);
$('.bar').css('width', percent + '%');
},
fail: function (e, data) {
// Remove the 'unsaved changes' message.
window.onbeforeunload = null;
$('.bar').css('width', '100%').addClass('red');
},
done: function (event, data) {
window.onbeforeunload = null;
// Fill the name field with the file's name.
$('#upload_original_name').val(data.originalFiles[0].name);
$('#upload_custom_name').val(data.originalFiles[0].name);
}
});
});
});
</script>
</body>
</html>
(https://www.designedbyaturtle.co.uk/2015/direct-upload-to-s3-using-aws-signature-v4-php/)
Works for me
I've just set up the new google recaptcha with checkbox, it's working fine on front end, however I don't know how to handle it on server side using PHP. I've tried to use the old code below but the form is sent even if the captcha is not valid.
require_once('recaptchalib.php');
$privatekey = "my key";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
$errCapt='<p style="color:#D6012C ">The CAPTCHA Code wasnot entered correctly.</p>';}
Private key safety
While the answers here are definately working, they are using a GET request, which exposes your private key (even though https is used). On Google Developers the specified method is POST.
For a little bit more detail: https://stackoverflow.com/a/323286/1680919
Verification via POST
function isValid()
{
try {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => '[YOUR SECRET KEY]',
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return json_decode($result)->success;
}
catch (Exception $e) {
return null;
}
}
Array Syntax: I use the "new" array syntax ( [ and ] instead of array(..) ). If your php version does not support this yet, you will have to edit those 3 array definitions accordingly (see comment).
Return Values: This function returns true if the user is valid, false if not, and null if an error occured. You can use it for example simply by writing if (isValid()) { ... }
this is solution
index.html
<html>
<head>
<title>Google recapcha demo - Codeforgeek</title>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<h1>Google reCAPTHA Demo</h1>
<form id="comment_form" action="form.php" method="post">
<input type="email" placeholder="Type your email" size="40"><br><br>
<textarea name="comment" rows="8" cols="39"></textarea><br><br>
<input type="submit" name="submit" value="Post comment"><br><br>
<div class="g-recaptcha" data-sitekey="=== Your site key ==="></div>
</form>
</body>
</html>
verify.php
<?php
$email; $comment; $captcha;
if(isset($_POST['email']))
$email=$_POST['email'];
if(isset($_POST['comment']))
$comment=$_POST['comment'];
if(isset($_POST['g-recaptcha-response']))
$captcha=$_POST['g-recaptcha-response'];
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
if($response['success'] == false)
{
echo '<h2>You are spammer ! Get the #$%K out</h2>';
}
else
{
echo '<h2>Thanks for posting comment.</h2>';
}
?>
http://codeforgeek.com/2014/12/google-recaptcha-tutorial/
I'm not a fan of any of these solutions. I use this instead:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'secret' => $privatekey,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
]);
$resp = json_decode(curl_exec($ch));
curl_close($ch);
if ($resp->success) {
// Success
} else {
// failure
}
I'd argue that this is superior because you ensure it is being POSTed to the server and it's not making an awkward 'file_get_contents' call. This is compatible with recaptcha 2.0 described here: https://developers.google.com/recaptcha/docs/verify
I find this cleaner. I see most solutions are file_get_contents, when I feel curl would suffice.
Easy and best solution is the following.
index.html
<form action="submit.php" method="POST">
<input type="text" name="name" value="" />
<input type="text" name="email" value="" />
<textarea type="text" name="message"></textarea>
<div class="g-recaptcha" data-sitekey="Insert Your Site Key"></div>
<input type="submit" name="submit" value="SUBMIT">
</form>
submit.php
<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])){
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
//your site secret key
$secret = 'InsertSiteSecretKey';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success){
//contact form submission code goes here
$succMsg = 'Your contact request have submitted successfully.';
}else{
$errMsg = 'Robot verification failed, please try again.';
}
}else{
$errMsg = 'Please click on the reCAPTCHA box.';
}
}
?>
I have found this reference and full tutorial from here - Using new Google reCAPTCHA with PHP
I liked Levit's answer and ended up using it. But I just wanted to point out, just in case, that there is an official Google PHP library for new reCAPTCHA: https://github.com/google/recaptcha
The latest version (right now 1.1.2) supports Composer and contains an example that you can run to see if you have configured everything correctly.
Below you can see part of the example that comes with this official library (with my minor modifications for clarity):
// Make the call to verify the response and also pass the user's IP address
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if ($resp->isSuccess()) {
// If the response is a success, that's it!
?>
<h2>Success!</h2>
<p>That's it. Everything is working. Go integrate this into your real project.</p>
<p>Try again</p>
<?php
} else {
// If it's not successful, then one or more error codes will be returned.
?>
<h2>Something went wrong</h2>
<p>The following error was returned: <?php
foreach ($resp->getErrorCodes() as $code) {
echo '<tt>' , $code , '</tt> ';
}
?></p>
<p>Check the error code reference at <tt>https://developers.google.com/recaptcha/docs/verify#error-code-reference</tt>.
<p><strong>Note:</strong> Error code <tt>missing-input-response</tt> may mean the user just didn't complete the reCAPTCHA.</p>
<p>Try again</p>
<?php
}
Hope it helps someone.
To verify at server side using PHP. Two most important thing you need to consider.
1. $_POST['g-recaptcha-response']
2.$secretKey = '6LeycSQTAAAAAMM3AeG62pBslQZwBTwCbzeKt06V';
$verifydata = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['g-recaptcha-response']);
$response= json_decode($verifydata);
If you get $verifydata true, You done.
For more check out this
Google reCaptcha Using PHP | Only 2 Step Integration
In the example above. For me, this if($response.success==false) thing does not work. Here is correct PHP code:
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "--your_key--";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if (isset($data->success) AND $data->success==true) {
// everything is ok!
} else {
// spam
}
it is similar with mattgen88, but I just fixed CURLOPT_HEADER, and redefine array for it work in domain.com host server. this one doesn't work on my xampp localhost. Those small error but took long to figure out. this code was tested on domain.com hosting.
$privatekey = 'your google captcha private key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_HEADER, 'Content-Type: application/json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'secret' => $privatekey,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
)
);
$resp = json_decode(curl_exec($ch));
curl_close($ch);
if ($resp->success) {
// Success
echo 'captcha';
} else {
// failure
echo 'no captcha';
}
Here you have simple example. Just remember to provide secretKey and siteKey from google api.
<?php
$siteKey = 'Provide element from google';
$secretKey = 'Provide element from google';
if($_POST['submit']){
$username = $_POST['username'];
$responseKey = $_POST['g-recaptcha-response'];
$userIP = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
$response = file_get_contents($url);
$response = json_decode($response);
if($response->success){
echo "Verification is correct. Your name is $username";
} else {
echo "Verification failed";
}
} ?>
<html>
<meta>
<title>Google ReCaptcha</title>
</meta>
<body>
<form action="index.php" method="post">
<input type="text" name="username" placeholder="Write your name"/>
<div class="g-recaptcha" data-sitekey="<?= $siteKey ?>"></div>
<input type="submit" name="submit" value="send"/>
</form>
<script src='https://www.google.com/recaptcha/api.js'></script>
</body>
Source Tutorial Link
V2 of Google reCAPTCHA.
Step 1 - Go to Google reCAPTCHA
Login then get Site Key and Secret Key
Step 2 - Download PHP code here and upload src folder on your server.
Step 3 - Use below code in your form.php
<head>
<title>FreakyJolly.com Google reCAPTCHA EXAMPLE form</title>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<?php
require('src/autoload.php');
$siteKey = '6LegPmIUAAAAADLwDmXXXXXXXyZAJVJXXXjN';
$secret = '6LegPmIUAAAAAO3ZTXXXXXXXXJwQ66ngJ7AlP';
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$gRecaptchaResponse = $_POST['g-recaptcha-response']; //google captcha post data
$remoteIp = $_SERVER['REMOTE_ADDR']; //to get user's ip
$recaptchaErrors = ''; // blank varible to store error
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp); //method to verify captcha
if ($resp->isSuccess()) {
/********
Add code to create User here when form submission is successful
*****/
} else {
/****
// This variable will have error when reCAPTCHA is not entered correctly.
****/
$recaptchaErrors = $resp->getErrorCodes();
}
?>
<form autcomplete="off" class="form-createuser" name="create_user_form" action="" method="post">
<div class="panel periodic-login">
<div class="panel-body text-center">
<div class="form-group form-animate-text" style="margin-top:40px !important;">
<input type="text" autcomplete="off" class="form-text" name="new_user_name" required="">
<span class="bar"></span>
<label>Username</label>
</div>
<div class="form-group form-animate-text" style="margin-top:40px !important;">
<input type="text" autcomplete="off" class="form-text" name="new_phone_number" required="">
<span class="bar"></span>
<label>Phone</label>
</div>
<div class="form-group form-animate-text" style="margin-top:40px !important;">
<input type="password" autcomplete="off" class="form-text" name="new_user_password" required="">
<span class="bar"></span>
<label>Password</label>
</div>
<?php
if(isset($recaptchaErrors[0])){
print('Error in Submitting Form. Please Enter reCAPTCHA AGAIN');
}
?>
<div class="g-recaptcha" data-sitekey="6LegPmIUAAAAADLwDmmVmXXXXXXXXXXXXXXjN"></div>
<input type="submit" class="btn col-md-12" value="Create User">
</div>
</div>
</form>
</body>
</html>
In response to #mattgen88's answer ,Here is a CURL method with better arrangement:
//$secret= 'your google captcha private key';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.google.com/recaptcha/api/siteverify",
CURLOPT_HEADER => "Content-Type: application/json",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => FALSE, // to disable ssl verifiction set to false else true
//CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array(
'secret' => $secret,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
)
));
$response = json_decode(curl_exec($curl));
$err = curl_error($curl);
curl_close($curl);
if ($response->success) {
echo 'captcha';
}
else if ($err){
echo $err;
}
else {
echo 'no captcha';
}
Check below example
<script src='https://www.google.com/recaptcha/api.js'></script>
<script>
function get_action(form)
{
var v = grecaptcha.getResponse();
if(v.length == 0)
{
document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
return false;
}
else
{
document.getElementById('captcha').innerHTML="Captcha completed";
return true;
}
}
</script>
<form autocomplete="off" method="post" action=submit.php">
<input type="text" name="name">
<input type="text" name="email">
<div class="g-recaptcha" id="rcaptcha" data-sitekey="site key"></div>
<span id="captcha" style="color:red" /></span> <!-- this will show captcha errors -->
<input type="submit" id="sbtBrn" value="Submit" name="sbt" class="btn btn-info contactBtn" />
</form>
i have tried a few different ways to get my data to post only when the user clicks it, but to no avail.
Hopefully someone can help:
<link href="facebook.css" rel="stylesheet" type="text/css">
<div class="fbbody">
<?php
require './facebook.php';
$facebook = new Facebook(array(
'appId' => ' *******',
'secret' => '******',
'cookie' => true,
));
$uid = $facebook->getUser();
$status = $_POST['status'];
if($status == "")
$msg = "Please enter a status.";
else {
$msg = "Thanks.";
}
?>
<script>
alert('<? echo $msg; ?>');
</script>
<div align="center">
<form method="GET" action="translate.php">
<textarea name="status2" cols="50" rows="5"/>
<?php echo str_ireplace(array ('old','awkward','all','again','behind','along','alright','hello','among','children','yes','child','kids','food','barnard castle','beer','book','blow','beautiful','bird','burst','brown','burn','boots'),
array ('auld', 'aakwad', 'aall','agyen','ahint','alang','alreet','alreet','amang','bairns','aye','bairn','bairns','bait','barney','beor','beuk','blaa','bonny','bord','borst','broon','bourn','byeuts'),$status); ?>
</textarea><br>
<?php
$args = array(
'message' => $_GET['status2'],
'link' => 'http://apps.facebook.com/geordie-status/',
'caption' => 'Translate from English to Geordie'
);
$post_id = $facebook->api("/$uid/feed", "post", $args);
?>
<input type="submit" value="post to wall"/>
</form>
</div>
</div>
the above code is my translate.php.
how could i use the 'onclick' attribute to run the below code when it is clicked, and only when the button is clicked, not before.
<?php
$args = array(
'message' => $_GET['status2'],
'link' => 'http://apps.facebook.com/geordie-status/',
'caption' => 'Translate from English to Geordie'
);
$post_id = $facebook->api("/$uid/feed", "post", $args);
?>
To post a status message you have to ask the user for permissions see: https://developers.facebook.com/docs/reference/login/extended-permissions/ you will need publish_actions here.
Cause you want to post on the on click event you will have ask the permission before show the form.
You can use jquery to handle your on click event (on submit in the code below). jquery is used to send the message to an second page (ajax request). The second page (facebookpost.php) will post the message on the wall.
facebook.php:
<?
error_reporting(E_ALL);
ini_set('display_errors','on');
require 'facebook-php-sdk-master/src/facebook.php';
$facebook = new Facebook(array(
'appId' => '***************',
'secret' => '*******************************',
));
$applicationurl = 'http://testdrive.nl/facebook.php';
// Get User ID
$user = $facebook->getUser();
if(empty($user))
{
$params = array(
'scope' => 'publish_actions',
'redirect_uri' => $applicationurl
);
$loginUrl = $facebook->getLoginUrl($params);
header('Location: ' . $loginUrl ."\r\n");
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Facebook testpage</title>
</head>
<body>
<div class="container">
<div id="result"></div>
<form id="poster">
<textarea id="status2"></textarea>
<input type="submit" value="post to wall"/>
</form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$('#poster').submit(function() {
$.get("facebookpost.php", { status2: $('#status2').val() }, function(data) {
$('#result').html(data);
});
return false;
});
</script>
</body>
</html>
facebookpost.php:
<?
error_reporting(E_ALL);
ini_set('display_errors','on');
require 'facebook-php-sdk-master/src/facebook.php';
$facebook = new Facebook(array(
'appId' => '***************',
'secret' => '*******************************',
));
//$applicationurl = 'http://testdrive.nl/facebook.php';
// Get User ID
$user = $facebook->getUser();
if(empty($user))
{
echo 'invalid user';
}
$args = array(
'message' => $_GET['status2'],
'link' => 'http://apps.facebook.com/geordie-status/',
'caption' => 'Translate from English to Geordie'
);
$facebook->api("/$user/feed", "post", $args);
echo 'posted to your wall';
<form style="text-align:center;" id="paypalform" action="https://www.paypal.com/cgi-bin/webscr" method="POST">
<input type='hidden' name='cmd' value='_xclick'>
<input type='hidden' name='business' value='payment#xxx.com'>
<input type='hidden' name='item_name' value='201001114262121'>
<input type='hidden' name='amount' id="amount" value='1.00'>
<input type='hidden' name='currency_code' value='CAD'>
<input type='hidden' name='return' value='http://www.xxx.com/paypal_process.php'>
<input type='hidden' name='invoice' value='82'>
<input type='hidden' name='charset' value='utf-8'>
<input type='hidden' name='no_shipping' value='1'>
<input type='hidden' name='no_note' value=''>
<input type='hidden' name='notify_url' value='http://www.xxx.com/return.php'>
<input type='hidden' name='rm' value='82'>
<input type='hidden' name='cancel_return' value='http://www.xxx.com/index.html'>
</form>
Anyone knows?
<?php
if(isset($_POST['submit']))
{
function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if($optional_headers != null)
{
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = #fopen($url, 'rb', false, $ctx);
if (!$fp)
{
throw new Exception("Problem with $url, $php_errormsg");
}
$response='';
while (!feof($fp))
{
$response = $response.fgets($fp);
}
if ($response === false)
{
throw new Exception("Problem reading data from $url, $php_errormsg");
}
fclose($fp);
return $response;
}
$host = 'http://mydomain.com';
$url = 'http://mydomain.com/formHandler.php';
$username = 'admin';
$password = '123456';
$data = array ('action' => 'login','lgname' => $username, 'lgpassword' => $password, 'format' => 'txt');
$data = http_build_query($data);
$reply = do_post_request($url, $data);
echo "**********Response*********<pre>";
echo var_dump($reply);
#header('location:'.$host);
#exit;
} else {
echo '<form method="post" enctype="multipart/form-data" action="'.$_SERVER['PHP_SELF'].'"><input type="text" name="uname" /><br><input type="password" name="password" /><input type="submit" name="submit"></form>';
}
?>
Try this
If you're wanting this form to submit as soon as the page is loaded, you can add this to the bottom of the page if you're determined in using PHP to submit the form:
<?
echo "<script type=\"text/javascript\">
window.onload=function(){
document.forms['paypalform'].submit();
}
</script>";
?>
But that seems like a long way around it. You could just write the javascript into the page... maybe I'm not sure what you're wanting to do, but I thought I'd throw this out.
Using javascript you can submit the form inside PHP code like this:
(trick is in last line )
$paypalURL = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
$paypalID = 'xyz-merchant#gmail.com';
$form = "<form id='paypal' action='". $paypalURL."' method='post'>";
$form .='<input type="hidden" name="business" value="'. $paypalID.'">';
$form .='<input type="hidden" name="cmd" value="_xclick">';
$itemDetail = "Detail goes here";
$orderId = 4444;
$totalAmountWithFee = 55;
$form .='<input type="hidden" name="item_name" value=" '.$itemDetail.'">
<input type="hidden" name="item_number" value="'.$orderId.'">
<input type="hidden" name="amount" value="'.$totalAmountWithFee.'">
<input type="hidden" name="currency_code" value="USD">';
$form .="<input type='hidden' name='cancel_return' value='http://localhost/public/cancel.php'> <input type='hidden' name='return' value='http://localhost/success.php'>";
$form.="<script type=\"text/javascript\"> document.forms['paypal'].submit();</script>";
echo $form;
If someone has a good idea pls share.
You can submit an HTML form from php with fsubmit PHP library https://github.com/randomsymbols/fsubmit
require_once 'fsubmit.php';
$html = '<form action="backend.aspx" method="post"><input type="text" name="question"></form>';
$form = new Fsubmit();
$form->url = 'http://the_url_must_contain_action_url_base'; // If form action is a relative link, then url is a required parameter, if form action is an absolute link, then this parameter can be omitted
$form->html = $html;
$form->params = ['question' => 'To code or not to code?', 'extra_question' => 'In what language?'];
$answer = $form->submit();
echo $answer['content'];
You can submit an HTML form from a PHP script with cURL or this library (that is based on cURL and simple html dom).