Cakephp : Validate recaptcha - php

I have downloaded a recaptchalib and successfully implemented the recaptcha and its displaying the recaptcha on my page but i am not able to validate it ... how can i validate the recaptcha
In View File
<div id="recaptcha_div"></div>
<script type="text/javascript">
$(function(){
Recaptcha.create("<?php echo Configure::read("recatpch_settings.public_key")?>", 'recaptcha_div', {
theme: "red",
callback: Recaptcha.focus_response_field});
});
</script>
Controller's Login action
public function login() {
App::import('Vendor', 'recaptchalib', array('file' => 'recaptchalib/recaptchalib.php'));
$resp = recaptcha_check_answer (Configure::read("recatpch_settings.private_key"),
$_SERVER["REMOTE_ADDR"],
$this->params['form']["recaptcha_challenge_field"],
$this->params['form']["recaptcha_response_field"]);
pr($resp);
exit();
if (!$resp->is_valid) {
$this->Session->setFlash('The reCAPTCHA wasn\'t entered correctly. Please, try again.');
} else {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Your username/password combination was incorrect');
}
}
}
}
I am not able to validate the captcha. I want to login the user if i types the correct captcha and obviously username and password.

I know that this is a very old question by now but I'll just go ahead and answer for those who might be looking into implementing this.
Add the Site/Secret key to your app/config/bootstrap.php file.
//Recaptcha Config
Configure::write('Recaptcha.SiteKey','YourSiteKey');
Configure::write('Recaptcha.SecretKey','YourSecretKey');
Adding the reCaptcha widget to your view/form:
<div>
<div class="g-recaptcha"
data-sitekey="<?php echo Configure::read('Recaptcha.SiteKey'); ?>">
</div>
<?php echo $this->Html->script('https://www.google.com/recaptcha/api.js"'); ?>
</div>
Verifying the user's response (reusable function inside your controller):
private function __checkRecaptchaResponse($response){
// verifying the response is done through a request to this URL
$url = 'https://www.google.com/recaptcha/api/siteverify';
// The API request has three parameters (last one is optional)
$data = array('secret' => Configure::read('Recaptcha.SecretKey'),
'response' => $response,
'remoteip' => $_SERVER['REMOTE_ADDR']);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
// We could also use curl to send the API request
$context = stream_context_create($options);
$json_result = file_get_contents($url, false, $context);
$result = json_decode($json_result);
return $result->success;
}
You check response by calling the above function after submitting a form containing the widget:
if($this->__checkRecaptchaResponse($this->request->data['g-recaptcha-response'])){
// user solved the captcha
} else {
// user failed to solve the captcha
}
Useful resources:
https://developers.google.com/recaptcha/docs/display
https://developers.google.com/recaptcha/docs/verify

Google has been introduced new reCaptcha API which is Are you a robot? A new design captcha system. This protects your website for robots and spammers, in this post I had implemented new reCaptch API system with HTML login form using CakePHP. Please take a look quick look at the demo.
Get reCaptcha Key
Click here to create a Google reCaptcha application.
Register Your Website
Give your website domain details without http:
Google Site Key
You will use this in HTML code.
Google Secret Key
This will help your website to communication with Google.
HTML code
Contains HTML code with Google reCaptcha snippet. You have to modify the GOOGLE_SITE_KEY value.
<html>
<head>
/* Google reCaptcha JS */
<script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<body>
<form action="" method="post">
<label>Username</label>
<?php echo $this->Form->text('User.username', array('maxlength' => 32))?>
<label>Password</label>
<?php echo $this->Form->password('User.password', array('maxlength' => 32))?>
<div class="g-recaptcha" data-sitekey="GOOGLE_SITE_KEY"></div>
<input type="submit" value="Log In" />
</form>
</body>
</html>
Create new Vendor in Vendor file:
curl.php
<?php
function getCurlData($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16");
$curlData = curl_exec($curl);
curl_close($curl);
return $curlData;
}
?>
Using in controller, You have to modify the GOOGLE_SECRET_KEY value.
$recaptcha = $this->data['g-recaptcha-response'];
$google_url = "https://www.google.com/recaptcha/api/siteverify";
$secret = 'GOOGLE_SECRET_KEY';
$ip = $_SERVER['REMOTE_ADDR'];
$url = $google_url . "?secret=" . $secret . "&response=" . $recaptcha ."&remoteip=" . $ip;
App::import('Vendor', 'curl');
$res = getCurlData($url);
$res = json_decode($res, true);
if(empty($res['success'])){
//if success not empty
//some code here
}
Hope it's useful.

Related

Synchronous XMLHttpRequest on the main thread is deprecated / AJAX & API

I am looking to create an ajax function with the MailChimp list API however I am facing the following error 'Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects '. PHP code works fine but when I try to introduce ajax it all goes wrong.
Honestly, I don't know where to start with this as have little experience in using ajax with API.
Could someone please be kind enough to review the below code and give me their thoughts?
$(document).ready(function() {
$("#subCard").submit(function(event) {
event.preventDefault();
var emailSub = $("#emailSub").val();
var fNameSub = $("#fNameSub").val();
var lNameSub = $("#lNameSub").val();
var subSubmit = $("#subSubmit").val();
$(".form-message").load("action.php", {
emailSub: emailSub,
fNameSub: fNameSub,
lNameSub: lNameSub,
subSubmit: subSubmit
});
});
});
<?php
session_start();
if(isset($_POST['subSubmit'])){
$emailSub = $_POST['emailSub'];
$fNameSub = $_POST['fNameSub'];
$lNameSub = $_POST['lNameSub'];
if(!empty($emailSub) && !filter_var($emailSub, FILTER_VALIDATE_EMAIL) === false){
// MailChimp API credentials
$apiKey = 'user API key';
$listID = 'user list ID';
// MailChimp API URL
$memberID = md5(strtolower($emailSub));
$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' => $emailSub,
'status' => 'subscribed',
'merge_fields' => [
'FNAME' => $fNameSub,
'LNAME' => $lNameSub
]
]);
// 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);
// store the status message based on response code
if ($httpCode == 200) {
$_SESSION['msg'] = '<p style="color: #ffffff">You have successfully subscribed to AquaCodeStudio.</p>';
} else {
switch ($httpCode) {
case 214:
$msg = 'You are already subscribed.';
break;
default:
$msg = 'Sorry a problem occurred, please try again.';
break;
}
$_SESSION['msg'] = '<p style="color: #EA4335">'.$msg.'</p>';
}
}else{
$_SESSION['msg'] = '<p style="color: #EA4335">Please enter a valid email address.</p>';
}
}
// redirect to homepage
header('location:about.php');
?>
.load in itself is synchronous, unless something else is specified in the global jQuery AJAX settings.
The redirect to the about.php page after processing the form data seems to be the culprit here.
It actually redirects the AJAX request in the background - so first the data is send to load.php and processed there, and then the browser makes another (GET) request for about.php. What is then inserted into your original document is the content of the latter. Not sure how exactly this causes the “Synchronous…” warning, but maybe that page itself contains code that makes AJAX requests again, or something like that. (.load, when executed without a suffixed selector expression, executes <script> elements contained in the loaded HTML automatically.)

Fix request failed using php

I make an api using Linkedin for website. After created all files, my application run fine but the only that has problem is when I try to allow the website, gives me this errors:
my purpose is to access in this page:
My code has error in this line:
init.php
<?php
SESSION_start();
$client_id="xxxxxxxxxxxxxx";
$client_secret="xxxxxxxxxxxxxxxx";
$redirect_uri="http://localhost/gmail-connect.php/callback.php";
$csrf_token = "random_int(1111111, 9999999)";
$scopes="r_basicprofile%20r_emailaddress";
function curl($url, $parameters)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($ch, CURLOPT_POST, 1);
$header =[];
$header[] = "Content-type:applicationx-www-form-urlencoded";
$result = curl_exec($ch);
return $result;
}
function getCallback()
{
$client_id="xxxxxxxxxxxxxx";
$client_secret="jxxxxxxxxxxxxxxxx";
$redirect_uri="http://localhost/gmail-connect.php/callback.php";
$csrf_token ="random_int(1111111, 9999999)";
$scopes="r_basicprofile%20r_emailaddress";
}
if(isset($_REQUEST['code'])) {
$code = $_REQUEST['code'];
$url = "https://www.linkedin.com/oauth/v2/accessToken";
$params = [
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
'code' => $code,
'grant_type' => 'authorization_code',
];
$accessToken = curl($url, http_build_query($params));
$accessToken = json_decode($accessToken)->access_Token;
$URL="https://api.linkedin.com/v1/people/~:(id,firstName,lastName,pictureUrls::(original),headline,publicProfileUrl,location,industry,positions,email-address)?format=json&oauth2_access_token=" .$accessToken;
$user = file_get_contents($url, false);
return(json_decode($user));
}
?>
Callback.php:
<?php
require_once "init.php";
$user = getCallback();
$_SESSION['user'] = $user;
header("location: landing.php");
?>
And this is the landing page:
<?php
require "init.php";
if(!isset($_SESSION['user'])) {
$user = 0;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>profile</title>
</head>
<body style="margin-top:200px; text-align:center;">
<div>
<h1>successful</h1>
<h1>here is describing your details info</h1>
<label style="font-weight:600">First Name</label><br>
<label><?php echo $user['firstName'] ?></label><br><br>
<label style="font-weight:600">Last Name</label><br>
<label><?php echo $user['lastName'] ?></label><br><br>
<label style="font-weight:600">Email address</label><br>
<label><?php echo $user['emailaddress'] ?></label><br><br>
<label style="font-weight:600">Headline</label><br>
<label><?php echo $user['headline'] ?></label><br><br>
<label style="font-weight:600">Industry</label><br>
<label><?php echo $user['industry'] ?></label><br><br>
<button>Log out</button>
</div>
</body>
</html>
the x it is for secure reason, I have put $client_secret="", $client_id="".
In this project I want to see my profile completed with details on landing page and not empty as it's show here for example in first name to be writen a name and ect.
how to fix those errors,thanks
The first error (Undefined property) is because the HTTP request didn't get a valid response ($accessToken) in:
$accessToken = curl();
This could be because the URL requested is invalid. You can:
Check if $params array is correctly set. Call print_r($params) or print_r(http_build_query($params)) before calling curl to check it.
Check if the curl() call has the right parameters (url and parameters) it could be better to use only a full url ($url . "?" . http_build_query($params)) if the request is using GET, but
The accessToken API must be requested as POST request (not GET), so make sure your cUrl call sends a POST request (See: https://developer.linkedin.com/docs/oauth2#)
The second error is related to the first one, because the access token is empty, you get a HTTP 400 error (bad request). So if you fix the first step the second could be fine.
try this code before $accessToken :
$context = stream_context_create(
array('http' =>
array('method' => 'POST',
)
)
);
return true;
this make solute the error message

Why No response from Google Invisible recaptcha?

Trying to achieve Google invisible recaptcha, but I am not getting any response after verification.
Here is my code:
invisible_recaptcha.php (form)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Recaptcha Demo</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
function onSubmit(token) {
document.getElementById("i-recaptcha").submit();
}
</script>
</head>
<body>
<!-- FORM GOES HERE -->
<form id='i-recaptcha' action="process_recaptcha.php" method="post">
<label for="fname">First Name*</label><br>
<input type="text" name="fname" id="fname" required autofocus><br><br>
<label for="lname">Last Name*</label><br>
<input type="text" name="lname" id="lname" required><br><br>
<label for="email">Email Address*</label><br>
<input type="email" name="email" id="email" required><br><br>
<button class="g-recaptcha" data-sitekey="XXXXXXmy_site_keyXXXXXXXXX" data-size="invisible" data-callback="onSubmit">
Submit
</button>
</form>
</body>
</html>
process_recaptcha.php (verify the recaptcha)
<?php
// Checks if form has been submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => 'XXXXXX_my_secret_key_XXXXXXXXX',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
//echo $user_response."<br><br><br><br>". $fields_string;exit;
$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 reCAPTCHA is not properly set up
echo 'reCAPTCHA error: Check to make sure your keys match the registered domain and are in the correct locations. You may also want to doublecheck your code for typos or syntax errors.';
} else {
// If CAPTCHA is successful...
// Paste mail function or whatever else you want to happen here!
echo '<br><p>CAPTCHA was completed successfully!</p><br>';
}
} ?>
It always gives me this message:
reCAPTCHA error: Check to make sure your keys match the registered domain and are in the correct locations. You may also want to doublecheck your code for typos or syntax errors.
Please try this One
try {
//Get google capcha details
if ($site_details['google_captcha_secret_key'] != '') {
$site_key = $site_details['google_captcha_secret_key'];
} else {
$site_key = GOOGLE_CAPTCHA_SECRET_KEY;
}
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => $site_key,
'response' => $captcha,
'remoteip' => $this->userIpAddress];
$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;
}
Make sure you double-check your code over for syntax errors. You are missing the left quote around your site key. You also have an extra parenthesis where it says json_decode.
Finally, you don't need to separate it into two PHP files if you are going to use this condition:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
So the php code in process_recaptcha.php can be embedded in invisible_recaptcha.php. You would then have to change the form's action attribute to itself (invisible_recaptcha.php). The condition will check if the form has been submitted yet. If is has, it will process your recaptcha code, if not, it will skip it.

Can you use curl to send a login post request to wordpress?

I am currently trying to set something up that allows me to sort of remote log into wordpress, im not sure if im going about it right or if it's possible but it seems to be from a few things i've read.
Im using the code below:
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://example.com/wp-login.php',
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
'log' => 'username',
'pwd' => 'password',
'wp-submit' => 'Log In',
'redirect_to' => 'http://example.com/wp-admin/',
'testcookie' => 1
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
die(var_dump($resp));
// Close request to clear up some resources
curl_close($curl);
When i die var_dump it the page returns this and nothing else: string(0) "" that is all.
but when i remove the "pwd" field from the curl request it returns the login page along with an error message stating that the password from the password field is missing
EDIT
New error on successful login:
ERROR: Cookies are blocked or not supported by your browser. You must
enable cookies to use WordPress.
I have no idea what this is or why its doing it
I think WordPress don't let you to do this because of missing security nonce or referrer page.
My suggestion is to install/develop a plugin that supports remote login and then send the login request to your website based on the plugin structure.
You can use following function for auto login
function auto_login( $username ) {
// log in automatically
if ( !is_user_logged_in() ) {
$user = get_userdatabylogin( $username );
$user_id = $user->ID;
wp_set_current_user( $user_id, $user_login );
wp_set_auth_cookie( $user_id );
do_action( 'wp_login', $user_login );
}
}
Then what you need is to just call it as following:
auto_login('admin');
Hope it helps.
I wasnt able to use cURL to log in, but i was able to do things a much much simpler way using the below code.
<html>
<head>
<title>Crunchify Login Page</title>
<script>
function loginForm() {
document.myform.submit();
document.myform.action = "http://www.example.com/wp-login.php";
}
</script>
</head>
<body onload="loginForm()">
<form action="http://www.example.com/wp-login.php" name="myform" method="post">
<input type="text" name="log" value="admin">
<input type="password" name="pwd" value="password">
<input type="submit" value="Login">
</form>
</body>
</html>
This automatically submitted a login request to Wordpress with no problems and logs the user in "Granted the correct details are submitted", simple and effective and also easily scalable using frameworks like VueJS.
Looks like wordpress returns back a cookie that it expects to be posted in the headers or else you get this error. I was able to avoid this by tricking it into thinking i got the cookie ahead of time:
$headers = array(
"Cookie: wordpress_test_cookie=WP+Cookie+check"
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
You also need to make sure you have the cookie options on
curl_setopt($curl, CURLOPT_COOKIESESSION, 1);
curl_setopt($curl, CURLOPT_COOKIEJAR, '/path/to/cookie.txt');
curl_setopt($curl, CURLOPT_COOKIEFILE, '/path/to/cookie.txt');

How to Upload Picture to Twitter Using Oauth, API , JSON and PHP, Help Required

I am very very new to twitter api, today i first time signup for twitter api in my life. my aim is to post pictures from my website with a message on twitter. I have download its current library from internet, it gives me following 2 files and some examples.
i have include those two files and get this code photo_tweet.php means tweet with photo
here is my code
<?php
require 'tmhOAuth.php';
require 'tmhUtilities.php';
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'ZlhOWeCWG2MS5Wxxxxxx',
'consumer_secret' => 'DIPjoKcIWjpGWmw5jGJSKGAOLxxxxxx',
'user_token' => 'xxxxx-OGtPyRSUOUaR6XQRLAFVuv14xxxxxx',
'user_secret' => 'xxxxxoimsrNFhlz7mPa9h5pyVSjxxxxxxx',
));
// we're using a hardcoded image path here. You can easily replace this with
// an uploaded image - see images.php in the examples folder for how to do this
// 'image = "#{$_FILES['image']['tmp_name']};type={$_FILES['image']['type']};filename={$_FILES['image']['name']}",
// this is the jpeg file to upload. It should be in the same directory as this file.
$image = 'a.jpg';
$code = $tmhOAuth->request(
'POST',
'https://upload.twitter.com/1/statuses/update_with_media.json',
array(
'media[]' => "#{$image};type=image/jpeg;filename={$image}",
'status' => 'Picture time',
),
true, // use auth
true // multipart
);
if ($code == 200) {
tmhUtilities::pr(json_decode($tmhOAuth->response['response']));
} else {
tmhUtilities::pr($tmhOAuth->response['response']);
}
?>
a.jpg is on my server.
here is my settings on twitter!
Request type: GET
Request URI:* https://api.twitter.com/1/
when I upload all this code and access my code it returns blank scree, when i echo $code; it returns 0
its all what i have observed and experienced. I am in need of your Kind help. I shall be very very thank full to you
Note: Event When I removed my consumer key and consumer secret this code does not show any error. just a blank screen. I want this to show errors in case of any problem but no error
Here is the code for status only it work for me
$consumerKey = $consumer_key;
$consumerSecret = $consumer_secret;
$OAuthToken = $user_token;
$OAuthSecret = $user_secret;
include "OAuth.php";
include "twitteroauth.php";
$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $OAuthToken, $OAuthSecret);
$image = 'a.jpg';
$optsArray['status'] = 'Hi';
if (isset($_GET['msg'])) {
$tweetmsg = $_GET['msg'];
$tweet->post('statuses/update',$optsArray);
if($tweet)
echo "Your message has been sent to Twitter.";
else
echo "Your message has not been sent to Twitter.";
} else {
echo "Your message has not been sent to Twitter.";
}
but it post only status when i use
update_with_media.json
and
$optsArray['#media[]'] = "#{$image}";
it does not work , please help me to figure out this issue
You might want to check this article out. It walks you through the steps and gives many examples.
The following methods are provided by the API.
twitpic logo Post pictures on twitpic API using PHP
METHOD: uploadAndPost (http://twitpic.com/api/uploadAndPost)
METHOD: upload (http://twitpic.com/api/upload)
Error codes
1001 – Invalid twitter username or password
1002 – Image not found
1003 – Invalid image type
1004 – Image larger than 4MB
Given above is the API description from twitpic’s API page. But you need not to get into those complicated details. Instead you can use a class which will let you post a picture on twitpic and update your twitter status on the same account. This is simple & easy to use. Check out the code below.
<?php
class twitpic
{
/*
* variable declarations
*/
var $post_url='http://twitpic.com/api/upload';
var $post_tweet_url='http://twitpic.com/api/uploadAndPost';
var $url='';
var $post_data='';
var $result='';
var $tweet='';
var $return='';
/*
* #param1 is the array of data which is to be uploaded
* #param2 if passed true will display result in the XML format, default is false
* #param3 if passed true will update status twitter,default is false
*/
function __construct($data,$return=false,$tweet=false)
{
$this->post_data=$data;
if(empty($this->post_data) || !is_array($this->post_data)) //validates the data
$this->throw_error(0);
$this->display=$return;
$this->tweet=$tweet;
}
function post()
{
$this->url=($this->tweet)?$this->post_tweet_url:$this->post_url; //assigns URL for curl request based on the nature of request by user
$this->makeCurl();
}
private function makeCurl()
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, $this->url);
curl_setopt($curl, CURLOPT_POST, 3);
curl_setopt($curl, CURLOPT_POSTFIELDS, $this->post_data);
$this->result = curl_exec($curl);
curl_close($curl);
if($this->display)
{
header ("content-type: text/xml");
echo $this->result ;
}
}
private function throw_error($code) //handles few errors, you can add more
{
switch($code)
{
case 0:
echo 'Think, you forgot to pass the data';
break;
default:
echo 'Something just broke !!';
break;
}
exit;
}
} //class ends here
?>
The above PHP class does all the trick to upload picture on twitpic and post status on the twitter. You can use this class with both using HTML form or using a PHP script to automatically upload the image and post the tweet. You can use the following HTML form and PHP script in combination to upload picture by taking
input from the user.
// This block of code should be written above the HTML and it will exit after the picture has been uploaded. If //you have turned display on (by passing 3rd param as true) then it will display the success message.
if($_POST)
{
$file=$_FILES['media'];
$postfields = array();
$postfields['username'] = $_POST['username'];
$postfields['password'] = $_POST['password'];
$postfields['message'] = $_POST['message'];
$postfields['media'] = "#$file[tmp_name]";
$t=new twitpic($postfields,true,true);
$t->post();
exit;
}
<style type="text/javascript">
*{font-family:verdana;}
span{font-size:12px;color:#393939;}
h3{font-size:14px;color:#5AAAF7;}
</style>
<body>
<h3>Upload your pic to twitpic, and post status on twitter</h3>
<form method="post" enctype="multipart/form-data" action="<?= $_SERVER[PHP_SELF] ?>" >
<p><span style="height:40px;font-weight:bold;margin-right:56px;">Twitter Username :</span><input type="text" name="username" /></p>
<p><span style="height:40px;font-weight:bold;margin-right:61px;">Twitter Password:</span><input type="password" name="password" /></p>
<p><span style="vertical-align:text-top;height:40px;font-weight:bold;margin-right:28px;">Message to be posted :</span> <textarea cols="35" rows="2" name="message"></textarea></p>
<p><span style="vertical-align:text-top;height:40px;font-weight:bold;">Choose an image to upload: </span><input type="file" name="media" /></p>
<p style="width:250px;text-align:right;margin-top:50px;"><input type="submit" value="Upload »" /> </p>
</form>
<sup>Script powered by www.digimantra.com</sup>
</body>
You can skip posting update to twitter by passing the third argument as false or just by skipping it. If you want to upload image programmatically, without the user input or the form then you can do it using the following code. Make sure the image path is correctly mention, else it will throw an error.
<?php
$file='file_to_be_uploaded.gif';
$postfields = array();
$postfields['username'] = 'twitter_username';
$postfields['password'] = 'twitter_password';
$postfields['message'] = 'Message to be posted' ;
$postfields['media'] = "#$file"; //Be sure to prefix #, else it wont upload
$t=new twitpic($postfields,true,true);
$t->post();
?>
This above class posts the image in the binary format as discussed in Send binary data using curl php. You can change the class to suit your need and you can also enhance it the way you like. Hope this post helped you learn something.

Categories