Sample twitter application - php

<?php
function updateTwitter($status)
{
// Twitter login information
$username = 'xxxxx';
$password = 'xxxxxx';
// The url of the update function
$url = 'http://twitter.com/statuses/update.xml';
// Arguments we are posting to Twitter
$postargs = 'status='.urlencode($status);
// Will store the response we get from Twitter
$responseInfo=array();
// Initialize CURL
$ch = curl_init($url);
// Tell CURL we are doing a POST
curl_setopt ($ch, CURLOPT_POST, true);
// Give CURL the arguments in the POST
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postargs);
// Set the username and password in the CURL call
curl_setopt($ch, CURLOPT_USERPWD, $username.':'.$password);
// Set some cur flags (not too important)
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_NOBODY, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// execute the CURL call
$response = curl_exec($ch);
// Get information about the response
$responseInfo=curl_getinfo($ch);
// Close the CURL connection curl_close($ch);
// Make sure we received a response from Twitter
if(intval($responseInfo['http_code'])==200){
// Display the response from Twitter
echo $response;
}else{
// Something went wrong
echo "Error: " . $responseInfo['http_code'];
}
}
updateTwitter("Just finished a sweet tutorial on http://brandontreb.com");
?>
I get the following output
Error: 0
Please help.

The libcurl documentation says http_code is set to 0 on failure (no server response code). You should check response before calling curl_getinfo, and call curl_error if it is FALSE. Also, there's no point in storing an empty array in responseInfo. You can set it to null instead.

Might be a mistake or he forgot to eliminate it from the post, but curl_close($ch) is never called. Maybe that is what is holding up the response? I'll test more when I get home.

Related

PHP cURL hyperlink issue

I've written some simple code which should enable the retrieval of a given webpage, in this case Google.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.google.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
?>
Although it works, I've noticed when I click some of the hyperlinks, for instance the 'Privacy' hyperlink, I get redirected to http://mywebsite.com/intl/en/policies/privacy/ which obviously doesn't exist. Why does this happen? And is it possible to get redirected to the correct link?
<?php
function cURL() {
// Create a new cURL resource
$curl = curl_init();
if (!$curl) {
die("Couldn't initialize a cURL handle");
}
// Set the file URL to fetch through cURL
curl_setopt($curl, CURLOPT_URL, "http://ctrlq.org/");
// Set a different user agent string (Googlebot)
curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
// Follow redirects, if any
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
// Fail the cURL request if response code = 400 (like 404 errors)
curl_setopt($curl, CURLOPT_FAILONERROR, true);
// Return the actual result of the curl result instead of success code
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Wait for 10 seconds to connect, set 0 to wait indefinitely
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
// Execute the cURL request for a maximum of 50 seconds
curl_setopt($curl, CURLOPT_TIMEOUT, 50);
// Do not check the SSL certificates
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
// Fetch the URL and save the content in $html variable
$html = curl_exec($curl);
// Check if any error has occurred
if (curl_errno($curl))
{
echo 'cURL error: ' . curl_error($curl);
}
else
{
// cURL executed successfully
print_r(curl_getinfo($curl));
}
// close cURL resource to free up system resources
curl_close($curl);
}
?>

wont allow post request - 405 error

I found a script and modified it, hoping to returrn the contents of a login page. However, it seems that the page won't let me log in.
using var_dump($_POST); and print_r($_POST); gives me a blank array:
array(0) {
}
Array
(
)
So I don't know how to do it. The website is https://create.kahoot.it/login
This is the code I am running:
<?php
$username = 'USERNAME';
$password = 'PASSWORD';
$loginUrl = 'https://create.kahoot.it/login';
//init curl
$ch = curl_init();
//Set URL
curl_setopt($ch, CURLOPT_URL, $loginUrl);
//HTTPS
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// ENABLE HTTP POST
curl_setopt($ch, CURLOPT_POST, 1);
//try to echo post variables
var_dump($_POST);
print_r($_POST);
//Set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, 'user='.$username.'&pass='.$password);
//Handle cookies
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
//Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
// to return the results as a string return value
//from curl_exec() instead of the usual true/false.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//login
$store = curl_exec($ch);
//put page details in file
file_put_contents("test.txt",$store);
?>
--EDIT--
response headers + authentication page stuff
by changing the postman from POST to GET it returns {"error":"Authentication failed","exception":"Authentication failed","error_description":"Authentication token of type [class no.mobitroll.core.security.shiro.tokens.SessionToken] could not be authenticated by any configured realms. Please ensure that at least one realm can authenticate these tokens.","timestamp":1499789957919,"duration":0,"errorCode":0}
first use this code and debug your issue.
$info = curl_getinfo($ch);
print_r( $info );
if you are requesting HTTPS check
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
405 error probably for un-permitted methods. e.g. Making a GET call, when only POST is permitted, or vice versa.

Getting data from Json url using CURL Returning NULL

i have a JSON link , i want to get data from it but it is returning NULL.
Code:
$url = 'https://cheddargetter.com/json/customers/search/orderBy/id/orderByDirection/asc/perPage/100/';
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
//var_dump(json_decode($result, true));
echo '<pre>abc'. print_r($result) . '</pre>';
your code looks correct. the problem is the url. I guess it ask for authentication to get the json data.
https://cheddargetter.com/?fwd=%2Fjson%2Fcustomers%2Fsearch%2ForderBy%2Fid%2ForderByDirection%2Fasc%2FperPage%2F100%2F#login

How to check login is successful fron curl in PHP?

I have written a php script to login to a site from curl. Below is my code:
<?php
// INIT CURL
$ch = curl_init();
// SET URL FOR THE POST FORM LOGIN
curl_setopt($ch, CURLOPT_URL, 'http://wordpress.dev/wp-login.php');
// ENABLE HTTP POST
curl_setopt ($ch, CURLOPT_POST, 1);
// SET POST PARAMETERS : FORM VALUES FOR EACH FIELD
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'log=admin&pwd=admin');
// IMITATE CLASSIC BROWSER'S BEHAVIOUR : HANDLE COOKIES
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
# Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
# not to print out the results of its query.
# Instead, it will return the results as a string return value
# from curl_exec() instead of the usual true/false.
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
// EXECUTE 1st REQUEST (FORM LOGIN)
$store = curl_exec ($ch);
var_dump($store);exit;
// CLOSE CURL
curl_close ($ch);
?>
If I give right password it gives string() " and if give wrong password it redirects me to the login page
How can check that login is successful?
You need to check response code as well. This might help you.
$contents = curl_exec($ch);
$httpcode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
var_dump($httpcode);
var_dump($contents);
In most cases HTTP code 200 is a valid authentication.
curl_exec() Returns TRUE on success or FALSE on failure.
<?php
//execute the request (the login)
$store = curl_exec($ch);
if($store){ //check for true/false
//Logged in
}else{
//Login failed
}
?>
UPDATE:
if you are on HTTPS, add this:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
UPDATE 2:
add this:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
you can check it with $store it will return true on success otherwise false.
check Storing the response of login using curl? . think it will solve your problem.
You should pay attention to status codes.
curl_exec would return true even if your login is not validated.
It simply means that the curl request is executed without error..
Make sure that status code is "200"..

PHP - How to fire HTTP get request on a secured URL (HTTPS)?

I am trying to fire a HTTP GET request on a secured URL which asks for username and password. This is fine when I am using that from browser but I am not sure how to do that using PHP.
I have tried using the two methods:
1) Using Curl as suggested in here: Make a HTTPS request through PHP and get response
2) Using the file_get_contents as suggested in here: How to send a GET request from PHP?
But the first one didn't give me any response back. And the second one gave me the following error:
failed to open stream: HTTP request failed
And this is my code for the curl:
$url="https://xxxxx.com";
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
and for the file_get_contents:
$url="https://xxxx.com";
$response=file_get_contents($url);
echo $response;
The URL will return a XML response for a API I am testing. Can someone point me to the right direction?
Thanks!
If we focus on the requirement to send a username and password because I suspect that's your main problem, try this
$ch = curl_init();
$url="https://xxxxx.com";
// OR - check with your server's operator
$url="http://xxxxx.com";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// or maybe
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
// - see http://stackoverflow.com/questions/4753648/problems-with-username-or-pass-with-colon-when-setting-curlopt-userpwd
// check the cURL documentation
$output = curl_exec($ch);
$info = curl_getinfo($ch);
// don't forget to check the content of $info, even a print_r($info) is better
// than nothing during debug
curl_close($ch);

Categories