Could anyone help me figure out how to post to tumblr using php.
I tried googling for a library or a sample code but couldn't find one. all I can find is this here https://github.com/alexdunae/tumblr-php/blob/master/Tumblr.php and it doesnt seem to work also I looked and tried the code on v1 api at tumblr website that doesnt work either ....
function post($data){
if(function_exists("curl_version")){
$data["email"] = $this->email;
$data["password"] = $this->password;
$data["generator"] = $this->generator;
$request = http_build_query($data);
$c = curl_init('http://www.tumblr.com/api/write');
curl_setopt($c,CURLOPT_POST,true);
curl_setopt($c,CURLOPT_POSTFIELDS,$request);
curl_setopt($c,CURLOPT_RETURNTRANSFER,true);
$return = curl_exec($c);
$status = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if($status == "201"){
return true;
}
elseif($status == "403"){
return false;
}
else{
return "error: $return";
}
}
else{
return "error: cURL not installed";
}
}
Thanks for the help
I just noticed that this is showing up as Featured for Tumblr and I want to say this: As of 2012, you should IGNORE the above answer by Tuga because it DOES NOT work with the newest Tumblr API.
What you need is TumblrOAuth which is built from OAuth Sandbox.
It is only setup to read and write Tumblr posts, so if you want to do more than that, you'll need to alter the code. I used it as my code base for Followr.
Stolen from http://www.tumblr.com/docs/en/api
// Authorization info
$tumblr_email = 'info#davidville.com';
$tumblr_password = 'secret';
// Data for new record
$post_type = 'regular';
$post_title = 'The post title';
$post_body = 'This is the body of the post.';
// Prepare POST request
$request_data = http_build_query(
array(
'email' => $tumblr_email,
'password' => $tumblr_password,
'type' => $post_type,
'title' => $post_title,
'body' => $post_body,
'generator' => 'API example'
)
);
// Send the POST request (with cURL)
$c = curl_init('http://www.tumblr.com/api/write');
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $request_data);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
// Check for success
if ($status == 201) {
echo "Success! The new post ID is $result.\n";
} else if ($status == 403) {
echo 'Bad email or password';
} else {
echo "Error: $result\n";
}
?>
$conskey = "CONSUMER KEY";
$conssec = "CONSUMER SECRET";
$tumblr_blog = "myblog.tumblr.com";
$to_be_posted = "This is the text to be posted";
$oauth = new OAuth($conskey,$conssec);
$oauth->fetch("http://api.tumblr.com/v2/blog/".$tumblr_blog."/post", array('type'=>'text', 'body'=>$to_be_posted), OAUTH_HTTP_METHOD_POST);
$result = json_decode($oauth->getLastResponse());
if($result->meta->status == 200){
echo 'Success!';
}
This code will let you post to your tumblr blog using tumblr API.
I hope this code helps.
The api example provided by Tuga is working for me (on Wordpress)...so I think your problem lies elsewhere, and not with the example provided. I would also be very appreciative if you guys got a version 2 api working if you could post it.
Related
i have created a form in codeigniter and given a google captcha v2, i have created the site key and secret key added it to config files, and also added the js and the recaptcha div including my site key. the following is my captcha function in controller:
public function validate_captcha() {
$recaptcha = trim($this->input->post('g-recaptcha-response'));
$userIp= $this->input->ip_address();
$secret='xxxxxxxxxxxx'; (i have given my scret key here)
$secretdata = array(
'secret' => "$secret",
'response' => "$recaptcha",
'remoteip' =>"$userIp"
);
$verify = curl_init();
curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($verify, CURLOPT_POST, true);
curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($secretdata));
curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($verify);
$status= json_decode($response, true);
if(empty($status['success'])){
return FALSE;
}else{
return TRUE;
}
}
the following is my register form function in same controller:
public function ajaxRegAction() {
$this->load->library('session');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
$this->load->library('form_validation');
$utype='W';
$dhamu = $this->validate_captcha();
$createddate = date('Y-m-d h:i:s');
$createdby = '0';
$mobile = $this->input->post('phone');
$form_data = array(
'type' => $utype,
'unique_id' => $this->mainModel->generateIndividualID(),
'phone_num' => $mobile,
'email' => $this->input->post('email'),
'first_name' => $this->input->post('firstname'),
'last_name' => $this->input->post('lastname'),
'created_by' => $createdby,
'created_date' => $createddate,
);
$name = $this->input->post('firstname')." ".$this->input->post('lastname');
$access_info = array('user_type'=>$utype);
$check = $this->mainModel->checkUserAvail($this->input->post('phone'),$this->input->post('email'));
$checkauser = $this->mainModel->checkAjaxUser($this->input->post('phone'),$this->input->post('email'));
if($check==0) {
if($dhamu==1){
$insert = $this->mainModel->ajaxRegInsertUser($form_data, $access_info,$this->input->post('password'));
$message="Dear ".$this->input->post('firstname').", You have successfully registered with Book The Party. Thank You for coming On-Board. Contact us at 9666888000 for any queries - Team BTP";
$email_message=$message;
$message=rawurlencode($message);
$this->mainModel->sendOtptoCustomer($mobile,$message);
$this->mainModel->sendmailtoCustomer($this->input->post('email'),$email_message);
echo "success";
}
else{ echo "Captcha Error";}
}
else{
echo "Registration Failed !";
}
even if i check the google recaptcha box and press register, the form is showing "Captcha Error", values are not being added to the database also. can anyone please tell me what could be wrong here, thanks in advance
Step 1:
Make sure you have added localhost in your domain in Google Captcha V2 dashboard.
Step 2:
I am modifying your function you can use it like this:
public function validate_captcha()
{
if(isset($_POST['g-recaptcha-response']))
{
$captcha=$_POST['g-recaptcha-response'];
}
$secretKey = "Put your secret key here";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
// should return JSON with success as true
if($responseKeys["success"]) {
return TRUE;
} else {
return FALSE;
}
}
instead of CURL
Do let me know if this works
I'm trying to implement Google ReCaptcha V2 in a PHP form.
Here is my code :
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//form submitted
//check if other form details are correct
//verify captcha
$recaptcha_secret = "";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['g-recaptcha-response'], false, stream_context_create($arrContextOptions));
$response = json_decode($response, true);
if($response["success"] === true)
{
echo "Logged In Successfully";
}
else
{
echo "You are a robot";
}
}
?>
When i submit my form, it always return
You are a robot
.
My public key is correct, and my private key too.
I don't know what i'm doing wrong ?
I'm working as localhost.
Thanks.
Just integrated 2 days ago the V2 recaptcha from Google
Try my code below, explicitly to see if is solving your problem:
I can see u do file_get_contents, and i think here is your issues, u have to make POST, please use my code below
if($_SERVER["REQUEST_METHOD"] === "POST"){
// prepare post variables
$post = [
'secret' => $secret,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => 'is optional, but i pass it',
];
$ch = curl_init('https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
$response = json_decode($response, true);
// check result
if(isset($response['success']) && $response['success'] == true){
echo "Logged In Successfully";
}else{
echo "You are a robot";
}
}
what am trying to do is check if the video entered by the users really exists or not , I have searched a lot and found this : ReRetrieving_Video_Entry , but it looks like it deprecated, so how is it possible using Google APIs Client Library for PHP to check if video exists or not?
I have fixed it using this technique, which doesn't require any use of API:
$headers = get_headers('https://www.youtube.com/oembed?format=json&url=http://www.youtube.com/watch?v=' . $key);
if(is_array($headers) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',$headers[0]) : false){
// video exists
} else {
// video does not exist
echo json_encode(array('Error','There is no video with that Id!'));
}
Here's what I'm using, it works pretty well. Youtube API v2. Deprecated
$video = "cK3N2DC3Fds";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://gdata.youtube.com/feeds/api/videos/'.$video);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
curl_close($ch);
if ($content && $content !== "Invalid id" && $content !== "No longer available") {
$xml = new SimpleXMLElement($content);
}else {
//Doesn't exist
}
You can check if a video exists using YouTube Data API (v3). Download/clone the API from here.
And here's a script I made that check if a video exists given a youtube video ID.
require_once dirname(__FILE__).'/../google-api/src/Google/autoload.php'; // or wherever autoload.php is located
$DEVELOPER_KEY = 'yourkey';
$client = new Google_Client();
$client->setDeveloperKey($DEVELOPER_KEY);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
$video = "cK3N2DC3Fds"; //Youtube video ID
$searchResponse = $youtube->search->listSearch('id', array(
'q' => $video, //The search query, can be a name or anything,
'maxResults' => 1, //Query result limit
"type" => "video"
));
$exists = false;
foreach ($searchResponse['items'] as $searchResult) {
//if type is video, this will always be "youtuve#video"
if($searchResult['id']['kind'] == "youtube#video"){
if($video == $searchResult['id']['videoId']){
$exists = true;
}
}
}
if(!$exists){
echo "video not found";
}else echo "video found";
I've been able to successfully log a user in and return their details. The next step is to get them to post a comment via my app.
I tried modifying code from the reddit-php-sdk -- https://github.com/jcleblanc/reddit-php-sdk/blob/master/reddit.php -- but I can't get it to work.
My code is as follows:
function addComment($name, $text, $token){
$response = null;
if ($name && $text){
$urlComment = "https://ssl.reddit.com/api/comment";
$postData = sprintf("thing_id=%s&text=%s",
$name,
$text);
$response = runCurl($urlComment, $token, $postData);
}
return $response;
}
function runCurl($url, $token, $postVals = null, $headers = null, $auth = false){
$ch = curl_init($url);
$auth_mode = 'oauth';
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 10
);
$headers = array("Authorization: Bearer {$token}");
$options[CURLOPT_HEADER] = false;
$options[CURLINFO_HEADER_OUT] = false;
$options[CURLOPT_HTTPHEADER] = $headers;
if (!empty($_SERVER['HTTP_USER_AGENT'])){
$options[CURLOPT_USERAGENT] = $_SERVER['HTTP_USER_AGENT'];
}
if ($postVals != null){
$options[CURLOPT_POSTFIELDS] = $postVals;
$options[CURLOPT_CUSTOMREQUEST] = "POST";
}
curl_setopt_array($ch, $options);
$apiResponse = curl_exec($ch);
$response = json_decode($apiResponse);
//check if non-valid JSON is returned
if ($error = json_last_error()){
$response = $apiResponse;
}
curl_close($ch);
return $response;
}
$thing_id = 't2_'; // Not the actual thing id
$perma_id = '2daoej'; // Not the actual perma id
$name = $thing_id . $perma_id;
$text = "test text";
$reddit_access_token = $_SESSION['reddit_access_token'] // This is set after login
addComment($name, $text, $reddit_access_token);
The addComment function puts the comment together according to their API -- http://www.reddit.com/dev/api
addComment then calls runCurl to make the request. My guess is that the curl request is messed up because I'm not receiving any response whatsoever. I'm not getting any errors so I'm not sure what's going wrong. Any help would really be appreciated. Thanks!
If you are using your own oAuth solution, I would suggest using the SDK as I said in my comment, but extend it to overwrite the construct method.
class MyReddit extends reddit {
public function __construct()
{
//set API endpoint
$this->apiHost = ENDPOINT_OAUTH;
}
public function setAuthVars($accessToken, $tokenType)
{
$this->access_token = $accessToken;
$this->token_type = $tokenType;
//set auth mode for requests
$this->auth_mode = 'oauth';
}
}
You just need to make sure that you call setAuthVars before running any api calls.
I have already tried below code,
function upload_content(){
// Authorization info
$tumblr_email = 'email-address#host.com';
$tumblr_password = 'secret';
// Data for new record
$post_type = 'text';
$post_title = 'Host';
$post_body = 'This is the body of the host.';
// Prepare POST request
$request_data = http_build_query(
array(
'email' => $tumblr_email,
'password' => $tumblr_password,
'type' => $post_type,
'title' => $post_title,
'body' => $post_body,
'generator' => 'API example'
)
);
// Send the POST request (with cURL)
$c = curl_init('api.tumblr.com/v2/blog/gurjotsinghmaan.tumblr.com/post');
//api.tumblr.com/v2/blog/{base-hostname}/post
//http://www.tumblr.com/api/write
//http://api.tumblr.com/v2/blog/{base-hostname}/posts/text?api_key={}
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $request_data);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
// Check for success
if ($status == 201) {
echo "Success! The new post ID is $result.\n";
} else if ($status == 403) {
echo 'Bad email or password';
} else {
echo "Error: $result\n";
}
}
You need to use the proper Tumblr endpoint:
http://www.tumblr.com/api/write
I'm pretty sure the others won't work.
Obviously make sure that your user and pass are correct, other than that, this looks fine - it's pretty much exactly what I'd write.