I have the following code, but it doesn't update my status (the username and password has been removed for this snippet) and it throws the error eeek. Any ideas why it's not working?
EDIT:
Apparently Twitter NEEDS OAuth instead now. I have been following this tutorial here: http://ditio.net/2010/06/07/twitter-php-oauth-update-status/
I have registered my App and copied both the Library and Tokens over.
BUT I'm not sure how to get this working with my current code, ie. what needs changing/adding/removing.
My Updated code:
<?php
function postToTwitter($username,$password,$message)
{
require_once 'TwitterOAuth.php';
define("CONSUMER_KEY", "???");
define("CONSUMER_SECRET", "???");
define("OAUTH_TOKEN", "???");
define("OAUTH_SECRET", "???");
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
$content = $connection->get('account/verify_credentials');
$connection->post('statuses/update', array('status' => date(DATE_RFC822)));
// GET the API url via web authentication
// add 'status' param to send a message to Twitter
$host = "http://api.twitter.com/1/statuses/update.xml?status=".urlencode(stripslashes(urldecode($message)));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
// Go for it!!!
$result = curl_exec($ch);
// Look at the returned header
$resultArray = curl_getinfo($ch);
// close curl
curl_close($ch);
//echo "http code: ".$resultArray['http_code']."<br />";
if($resultArray['http_code'] == "200"){
echo "<br />OK! posted to http://twitter.com/".$username."/<br />";
} else {
echo "eek! yegads! error posting to Twitter";
}
// debug the result
// echo "<pre>";
// print_r($resultArray);
// echo "</pre><hr>";
// $sResult = htmlentities($result);
// $sResult = str_replace("><","><br /><",$sResult);
// echo "<pre>";
// print $sResult;
// echo "</pre>";
}
if(isset($_POST['submit']))
{
$textmessage = $_POST['message'];
postToTwitter("whiningwall","u0558234",$textmessage);
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=1024">
<title></title>
<link rel="stylesheet" type="text/css" href="master.css" media="screen" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<form id="post" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<label for="textArea">What's on your mind?</label>
<textarea id="textArea" name="message" maxlength="140"></textarea>
<div class="submit">
<span class="charsRemaining"></span>
<input type="submit" name="submit" value="Share" />
</div>
</fieldset>
</form>
<script type="text/javascript" src="jquery.maxlength.js"></script>
<script type="text/javascript">
$('#textArea').focus();
</script>
</body>
</html>
I believe that CURLOPT_USERPWD is for Apache's basic authentication, which Twitter does not use. I don't know much about the Twitter API but I think you'll be better off using OAuth to tell Twitter who you are.
Edit to add: There's GPL twitter library at http://code.google.com/p/php-twitter/ that you might try looking at (or even using).
Related
The Mailchimp API returns error 400 if I try to subscribe a user that is already subscribed. Then I found that if I unsubscribe and attempt to resubscribe again I also get error 400. Is there a way to differentiate between these cases?
Mailchimp's error documentation says that 400 is returned for different reasons (bad request, invalid resource, invalid action, JSON parse exception). There doesn't seem to be a way to get more specific messages, and certainly no way to determine whether the issue is that user is already subscribed vs. recently unsubscribed.
Any idea how to return more useful error messages?
Here is my test code (based on this reference):
<?php
$statusMsg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['subscribe'])) {
if (!empty($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
// input sanitation
array_walk_recursive($_POST, function(&$value) {
$value = htmlspecialchars(stripslashes(trim($value)));
});
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
// MailChimp API credentials
$apiKey = '<my test API key>';
$listId = '<my list id>';
// MailChimp API URL
$dataCenter = substr($apiKey,strpos($apiKey,'-') + 1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/';
// member information
$json = json_encode([
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => [
'FNAME' => $fname,
'LNAME' => $lname
]
]);
// 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, 'POST');
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) {
$statusMsg = '<p style="color: #34A853">You have successfully subscribed.</p>';
} else {
switch ($httpCode) {
case 400: // problem: this also happens when user is unsubscribed
$msg = 'You are already subscribed.';
break;
default:
$msg = 'Some problem occurred, please try again. Error code ' . $httpCode . '.';
break;
}
$statusMsg = '<p style="color: red;">'.$msg.'</p>';
}
} else {
$statusMsg = '<p style="color: red;">Please enter valid email address.</p>';
}
}
?>
<!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>Mailchimp API Test</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<div id="container">
<h1>Subscribe to our Newsletter</h1>
<?php echo $statusMsg; ?>
<form method="post">
<input type="text" name="subscribe" value="subscribe" aria-hidden="true" readonly hidden>
<p><label for="fname"> First Name:</label><br>
<input id="fname" type="text" name="fname" /></p>
<p><label for="lname"> Last Name:</label><br>
<input id="lname" type="text" name="lname" /></p>
<p><label for="email"> Email address:</label><br>
<input id="email" type="text" name="email" /></p>
<input type="submit" value="Submit" />
</form>
</div>
</main>
</body>
</html>
I created a php script to interact with an API to fetch balance of my account but its not working so I want to see the entire raw curl response with all headers, title and body. How can I achieve this?
I'm very new to php so kindly consider this before answering.
<?php
$url = 'https://myapi.com';
$curl = curl_init($url . '?' . http_build_query($query_params));
$params =array();
$secret = "secret";
$post_data = '{}' ;
$checksum = build_checksum($params, $secret, $t, $r,$post_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_HTTP_CONTENT_DECODING, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'X-API-CODE:"api_code"',
"X-CHECKSUM: {$checksum}",
'Content-Type: application/json'
]);
$response = curl_exec($curl);
curl_close($curl);
$data =json_decode($response);
}
?>
<!DOCTYPE html>
<html lang="en">
<body>
<h2>My wallet</h2>
<br>
<br>
<form method="post">
<input type="submit" name="balance" value ="Check Balance"/>
</form>
<br>
<?php
echo "<h3>Your balance is: </h3>".$data->balance;
echo $data;
?>
</div>
</body>
</html>
I have added this basic login page to server for testing curl form submitting:
<?php
if(isset($_POST['submit'])){
$email = $_POST['email'];
$password = $_POST['password'];
if($email == "email#gmail.com"){
if($password == "123456"){
echo "Correctamundo!";
}else{
echo "Wrong pass";
}
}else{
echo "Wrong Email";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<form method="POST" action="">
<input type="email" name="email" value="">
<input type="password" name="password" value="">
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
So if the email equals to email#gmail.com && the password was 123456, the Correctamundo message appears on the page.
Now with curl at another file I've added this:
<?php
$data = array(
"email" => "email#gmail.com",
"password" => "123456",
"form" => "submit"
);
$ch = curl_init("http://sitename.com/login.php");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Allow Redirections
curl_setopt($ch, CURLOPT_POST, true); // Making a POST request
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); // COOKIE-jar: To save data for cookie created for login process
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // TRUE means Don't just echo output the data instead we can store the Request response in some variable
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
Now as you can see I have passed the correct credentials as $data array. But when I load the page, I don't get the Correctamundo message as success message.
So why is that? What am I doing wrong here?
i have an script and its work without problems on local host.
here is my code ...
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<?php
if(isset($_POST['username'])){
$username=$_POST['username'];
//echo $username;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.instagram.com/$username/?__a=1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
// curl_setopt($ch, CURLOPT_FAILONERROR,true);
// curl_setopt($ch, CURLOPT_ENCODING,"");
// curl_setopt($ch, CURLOPT_VERBOSE, true);
// curl_setopt($ch, CURLINFO_HEADER_OUT, true);
// curl_setopt($ch, CURLOPT_HEADER, true);
$result = curl_exec($ch);
curl_close($ch);
$json=json_decode($result);
//var_dump($json);
$insta_profile_picture= $json->graphql->user->profile_pic_url_hd;
}
else{
}
?>
<form method="post" action="">
<input type="text" name="username" placeholder="Type Your Username of Instagram " style="width:300px;height: 30px;border-radius: 4px;">
<input type="submit" name="submit" style="width:300px;height: 35px;border-radius: 4px;">
</form>
<?php
if(isset($_POST['username'])){
if($insta_profile_picture){
//echo $insta_profile_picture;
$imageData = base64_encode(file_get_contents($insta_profile_picture));
echo '<img src="data:image/jpeg;base64,'.$imageData.'">';}
else{
echo "something wrong";
}
}
else{
echo "please select your username on top input for checking profile photo";
}
?>
</body>
</html>
but it not work on my server and with tracking the result i understand its redirect to https://www.instagram.com/accounts/login/
please help me
tnx a lot for your helping
I am trying to connect to a web service with cURL and PHP. This is my code, along with the form for the user input.:
<?php
if (isset($_POST['submit'])) {
date_default_timezone_set('Europe/Sofia');
$hotelID = 1;
$userName = 'admin';
$password = 'admin';
$url = 'http://serviceurl.com/someservice/freerooms.svc';
$requestTime = date('d.m.Y H:m:s');
$tempFromDate = date_create($_POST['fromDate']);
$tempToDate = date_create($_POST['toDate']);
$fromDate = date_format($tempFromDate, 'd.m.Y H:m:s' );
$toDate = date_format($tempToDate, 'd.m.Y H:m:s' );
$data = array(
'fromDate' => $fromDate,
'toDate' => $toDate,
'hotelID' => $hotelID,
'requestTime' => $requestTime,
'userName' => $userName,
);
$token = md5(md5($password . $requestTime));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
echo $token . '<br>';
echo curl_setopt($ch, CURLOPT_HTTPHEADER, array('Bearer: ' . $token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
$response = curl_exec($ch);
if (!$response) {
$error = curl_error($ch);
}
curl_close($ch);
$result = json_decode($response,true);
print_r($result);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Site</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div id="wrapper" class="col-md-10 col-md-offset-1" style="position: absolute; top: 40%; left: 20%;">
<div id="form-messages">
<?php
if(isset($error)) {
echo '<b>Error: </b>' . $error;
} else {
$error = null;
}
?>
</div>
<form action="" method="post" class="form-inline" id="form">
<div class="form-group">
<input type="date" name="fromDate" required>
</div>
<div class="form-group">
<input type="date" name="toDate" required>
</div>
<button type="submit" name="submit">Submit</button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
</body>
</html>
Problem is, I don't have access to the service from the back end. All the person that maintains it has told me, is the format of the data that should be submitted, and that the response will be in JSON format. This is for hotel room reservation. I am told that I should submit the data in the headers along with the token. When I submit this code, I get an empty response, with an error, stating that the token is INVALID. It's the first time I've been working with cURL and RESTful services, so any help is welcome.