Tweet image with Twitter API not posting - php

I'm trying to create a simple app that sends a tweet of an image with a caption upon form submission. The test appears to be working at http://5starvintage.com/tweet/, but the tweet is never posted.
Any idea as to why the submitted tweet isn't posting?
Here's the form...
<form method="post" action="<?php echo bloginfo('template_directory');?>/tweet/start.php" enctype="multipart/form-data" onsubmit="FSV.initTweetValidate()" >
<div id="tweetWrap" class="clearfix">
<div id="imageDrop">
<span class="desc">Upload Image</span>
<input type="file" name="img" id="img"/>
</div>
<div id="tweetText">
<textarea type="text" name="txt" id="txt" maxlength="140" onkeyup="FSV.initCountChar(this)" placeholder="#5StarVintage..."></textarea>
<div id="charNum">140</div>
</div>
</div>
<input type="submit" name="sub" class="tweet" id="sub" value="Submit"/>
</form>
Here is the form action code, start.php..
<?php
require './config.php';
require './tmhOAuth.php';
/////// upload the photo
$img = $_FILES["img"]["name"];
move_uploaded_file($_FILES["img"]["tmp_name"],$img);
////////// generate *temp* access token and save it in cookie for callback page
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => API_KEY,
'consumer_secret' => API_SEC,
'curl_ssl_verifypeer' => false
));
$tmhOAuth->request('POST', $tmhOAuth->url('oauth/request_token', ''));
$response = $tmhOAuth->extract_params($tmhOAuth->response["response"]);
$txt = $_POST['txt'];
$temp_token = $response['oauth_token'];
$temp_secret = $response['oauth_token_secret'];
$time = $_SERVER['REQUEST_TIME'];
setcookie("Temp_Token", $temp_token, $time + 3600 * 30, '/tweet/');
setcookie("Temp_Secret", $temp_secret, $time + 3600 * 30, '/tweet/');
setcookie("Img_Url", $img, $time + 3600 * 30, '/tweet/');
setcookie("Tweet_Txt", $txt, $time + 3600 * 30, '/tweet/');
///////// redirect to twitter page for user authincation
$url = $tmhOAuth->url("oauth/authorize", "") . '?oauth_token=' . $temp_token;
header("Location:".$url);
// after user give the required authrization he will be redirect to callback.php on your serve
exit();
?>
Here's the callback.php..
<?php
require './config.php';
require './tmhOAuth.php';
require './tmhUtilities.php';
/// retrive temp access token from cookie
$token = $_COOKIE['Temp_Token'];
$secret = $_COOKIE['Temp_Secret'];
$img = $_COOKIE['Img_Url'];
$txt = $_COOKIE['Tweet_Txt'];
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => API_KEY,
'consumer_secret' => API_SEC,
'user_token' => $token,
'user_secret' => $secret,
'curl_ssl_verifypeer' => false
));
/// Ask Twitter for correct access token
$tmhOAuth->request("POST", $tmhOAuth->url("oauth/access_token", ""), array(
// pass the oauth_verifier received from Twitter
'oauth_verifier' => $_GET["oauth_verifier"]
));
$response = $tmhOAuth->extract_params($tmhOAuth->response["response"]);
$tmhOAuth->config["user_token"] = $response['oauth_token'];
$tmhOAuth->config["user_secret"] = $response['oauth_token_secret'];
$img = './'.$img;
$code = $tmhOAuth->request('POST', 'https://api.twitter.com/1.1/statuses/update_with_media.json',
array(
'media[]' => "#{$img}",
'status' => "$txt" // Don't give up..
),
true, // use auth
true // multipart
);
if ($code == 200){
tmhUtilities::pr(json_decode($tmhOAuth->response['response']));
echo '<h1>Your image tweet has been sent successfully</h1>';
}else{
// display the error
tmhUtilities::pr($tmhOAuth->response['response']);
return tmhUtilities;
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tweet an Image</title>
</head>
<body>
</body>

Related

how can i request or insert multiple recipient without calling the first array?

[insert multiple numbers same as the image][1]
[1]: https://i.stack.imgur.com/LkpWd.png
how do I call the array that contains (from, to, text) multiple times depends of how many number inserted to textbox.my problem is these first array (apikey, apisecret, messages) i need this to be called 1 time only every request. the error I'm getting is "Too many requests".its working if 1 number is inserted only but if multiple number it keep saying the too many request which is why i need to follow what's on the image.
Example request i need to do:
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
\"apiKey\": \"<apiKey>\",
\"apiSecret\": \"<apiSecret>\",
\"messages\": [
{
\"from\": \"<senderId>\",
\"to\": \"<recipient>\",
\"text\": \"<message>\"
},
{
\"from\": \"<senderId>\",
\"to\": \"<recipient>\",
\"text\": \"<message>\"
},
{
\"from\": \"<senderId>\",
\"to\": \"<recipient>\",
\"text\": \"<message>\"
}
Below is my Code:
<?php
$apikey = "**************";
$apisecret = "**************";
if (isset($_POST['send'])) {
$sender = $_POST['sender'];
$numb = $_POST['number'];
$txt = $_POST['message'];
//**this $key should not be called multiples times 1 time only**
$key = array("apiKey" => $apikey,"apiSecret" => $apisecret);
foreach (explode(",", $numb) as $phone) {
$numx = array("messages" =>array([
"from" => $sender,
"to" => $phone,
"text" => $txt]));
$merge = array_merge($key,$numx);
$data = json_encode($merge);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://rest-portal.smsapihide.com/api/batchsms',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>$data,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response.'<br>';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="for.php" method="post">
<label for="">Sender</label><br>
<input type="text" name="sender" id=""><br>
<label for="">Numbers</label><br>
<textarea name="number" id="" cols="30" rows="10"></textarea><br>
<label for="">Message</label><br>
<textarea name="message" id="" cols="30" rows="10"></textarea><br>
<input type="submit" value="Send" name="send">
</form>
</body>
</html>

How do I setup recaptcha with a form which uses the php_self action

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);

How to validate Google reCAPTCHA v3 on server side?

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>

how can i post on a wall using onclick attribute?

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';

how to resolve OAuthException: (#100)

I use my recently develop fb app to post on my wall and its shows the following error
Uncaught OAuthException: (#100) picture URL is not properly formatted thrown in
you can also see this directly *https://apps.facebook.com/hack-proof_pages/1gp.html
using two files "1gp.html" and "gp1.php"
1gp.html code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="gp1.php">
<p>message
<textarea style="width:300px; height:50px;" name="message1"></textarea>
</p>
<p>link
<input type="text" style="width:300px;" name="link1" />
</p>
<p>
Picture
<input type="text" name="picture1" />
</p>
<p>
name
<input type="text" style="width:300px;" name="name1" />
</p>
<p>
Caption
<input type="text" style="width:300px;" name="caption1" />
</p>
<p>Description
<textarea style="width:300px; height:50px;" name="description1"></textarea>
</p>
<p>
<input type="submit" name="Submit" value="Submit" />
</p>
</form>
</body>
</html>
gp1.php code
<?php
require_once 'library/facebook.php';
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => '149865361795547',
'secret' => 'shhhh seceret :)',
'cookie' => true,
));
$app_id = '149865361795547';
$canvas_page = "https://apps.facebook.com/hack-proof_pages/gp1.php";
//get data for post
$message1 = $_POST['message1'];
$picture1 = $_POST['picture1'];
$name1 = $_POST['name1'];
$link1 = $_POST['link1'];
$caption1 = $_POST['caption1'];
$description1 = $_POST['description1'];
// compile the post for for user
$WallPost = array(
'message' => $message1,
'link' => $link1,
'picture' => $picture1,
'name' => $name1,
'caption' => $caption1); // you can also use 'picture', 'link', 'name', 'caption', 'description', 'source'....
//http://developers.facebook.com/docs/reference/api/
$auth_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page) . ("&scope=email,read_stream,publish_stream,offline_access,publish_actions,manage_pages,user_groups&response_type=token");
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
//getting the userid and some other data for verification
//get the user id
$UserId = $data["user_id"];
echo 'UserId;' . $UserId;
//get the user access token
$atoken = $facebook->getAccessToken();
echo "</br>" . 'User Access_Token:' . $atoken;
//set default access token and profile
//$facebook->setAccessToken($atoken);
//$user_profile = $facebook->api('/me');
//get the user name and email
$user_id = $facebook->getUser();
$user_profile = $facebook->api('/me','GET');
$user_name = $user_profile['name'];
echo "Name: " . $user_name;
$user_email = $user_profile['email'];
echo "email: " . $user_email;
// post to user wall
$response = $facebook->api('/me' . '/feed','POST',$WallPost);
//posting to groups wall with sleeping time support poster.xls
}
?>
*Note: my app use self signed certificate SSL so that if you want to test this above URL you need to allow my site and store its certificate and one more info that sometimes google chrome shows error due to google chrome one weak point that chrome needs to store self signed certificate in internet explorer means if you want to check this in chrome you need to first open this site in internet explorer and allow my site self signed certificate and store permanently so that its also work in chrome
Please check your picture url, you need to give the full url of the photo not the relative url and facebook should be able to access the picture url, i.e. it should not be of your locally hosted application, try placing a fully qualified sample url of any picture in ur code and check.

Categories