hello my teacher has given me this weeks work and i need to get my json data from a url and display it as php using json_decode, the php json file which i access with the url displays the songs as an json array and works fine, and i copied my teachers curl example to access the url, but it fails to display anything what have i done wrong ?
Edit: i do need to enter a password and username to access the url so i changed the code as told, but still nothing displays, i changed the password and username for security but the format and length are the same
<?php
$username = "2foobar90";
$password = "123456";
// Initialise the cURL connection
$connection = curl_init();
curl_setopt($connection, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($connection, CURLOPT_USERPWD, $username . ":" . $password);
// Specify the URL to connect to - DOUBLE CLICK link to test
curl_setopt($connection, CURLOPT_URL, "https://edward2.solent.ac.uk/~martine/year3/hits.php?artist=David+Bowie");
// This option ensures that the HTTP response is *returned* from curl_exec(),
// (see below) rather than being output to screen.
curl_setopt($connection,CURLOPT_RETURNTRANSFER,1);
// Do not include the HTTP header in the response.
curl_setopt($connection,CURLOPT_HEADER, 0);
// Actually connect to the remote URL. The response is
// returned from curl_exec() and placed in $response.
$response = curl_exec($connection);
// Close the connection.
curl_close($connection);
$data = json_decode($response, true);
for($i=0; $i<count($data); $i++)
{
echo "Song id " . $data[$i]["songid"] . " " .
"Title " . $data[$i]["title"] . " " .
"Artist " . $data[$i]["artist"] . " " .
"Chart position " . $data[$i]["chart"] . "<br/>";
}
?>
The link requires basic authentication. Your browser remembers your username/password when you click the link. You can see request headers with chrome inspector.
Click link
Open your browser inspector
Click Network section
Find document
You can see Authorization data under the Request Headers
If you want to use authorization with curl add this:
curl_setopt($connection, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($connection, CURLOPT_USERPWD, $username . ":" . $password);
Related
How would I used CURL to send a form of order information to PayPal (https://www.sandbox.paypal.com/cgi-bin/webscr), instead of the user doing so, but allowing the user to be sent to the URL that CURL would redirect to?
I can successfully code the manual form version of this code. This is where the user fills in a form that has unseen database data in hidden form fields, and when the user submits it, this form is POST to "https://www.sandbox.paypal.com/cgi-bin/webscr". They are then redirected to a page such as "https://www.sandbox.paypal.com/webapps/hermes?token=XXXXXXXX&useraction=commit&mfid=XXXXXXXXX_XXXXXXXX". It should be noted that this URL can then be accessed from anyone at any location to complete the process, if it is not completed by the user it was first given to.
In my attempt to recreate this with CURL, the following happens: The user submits a form of data, and that data is sent to a secondary page where it is combined with the unseen database data, and used as the CURLOPT_POSTFIELDS. The cURL is then executed, but for some reason it is redirected to the URL: "https://www.sandbox.paypal.com/home" instead of the expected URL that contains a unique token and mfid.
Here is a reduced version of the code I tried so far:
<?php
$post_data['business'] = PAYPAL_ID;
//other data also here
$i = 1;
foreach($_SESSION['basket'])
{
//retrieve information from basket and insert into data
$post_data["item_name_$i"] = $name;
$post_data["amount_$i"] = $price;
$post_data["quantity_$i"] = $qty;
$post_data["item_number_$i"] = $id;
$i++;
}
//other data also here
$post_data['notify_url'] = PAYPAL_NOTIFY_URL;
//create string with format "key1=value1&key2=value2&key3=value3" etc.
foreach ($post_data as $key => $value)
{
$post_items[] = urlencode($key) . "=" . urlencode($value);
}
$post_string = implode('&', $post_items);
$curl_connection =
curl_init(PAYPAL_URL);
curl_setopt($curl_connection, CURLOPT_POST, 1);
curl_setopt($curl_connection, CURLOPT_HEADER, 0);
curl_setopt($curl_connection, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($curl_connection, CURLOPT_FORBID_REUSE, 1);
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT_MS, 30000);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($curl_connection);
print_r(curl_getinfo($curl_connection));
echo ("<br> curl errors: <br>");
echo curl_errno($curl_connection) . '-' .
curl_error($curl_connection);
echo ("<br> end curl errors; <br>");
echo ("getinfo: <br>" . curl_getinfo($curl_connection));
echo ("<br> The post string is: $post_string");
echo ("<br> effective URL is: <br>");
echo curl_getinfo($curl_connection, CURLINFO_EFFECTIVE_URL);
echo ("<br> The result string is: $result <br>");
curl_close($curl_connection);
?>
In my "debugging", I am always greeted with cURL error "0", and an empty "curl_error($curl_connection);". The post string looks correct, in the format "key1=value1&key2=value2", with all the keys and values successfully having the special characters URL encoded. (e.g. "#" becomes "%40). Also, the [redirect_count] value from "print_r(curl_getinfo($curl_connection));" is "1", which I believe means only 1 redirect occurs, and is not the URL I expected. The result string is "1".
What am I doing wrong?
If you want to automate the user's form post you should be automating their browser with javascript, not attempting to do a curl form post from your server. That's not going to work.
I am trying to get output of this API using php. It's a Australia Post Freight calculator. I am not sure what is wrong with it, can some one please suggest. It will be really helpful.
// Set your API key: remember to change this to your live API key in production
$apiKey = API_KEY;
// Set the URL for the Domestic Parcel Size service
$urlPrefix = URL_PREFIX;
$parcelTypesURL = 'https://' . $urlPrefix . '/postage/parcel/domestic/size.json';
// Lookup domestic parcel types (different kinds of standard boxes etc)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $parcelTypesURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('AUTH-KEY: ' . $apiKey));
$rawBody = curl_exec($ch);
// Check the response: if the body is empty then an error occurred
if(!$rawBody){
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
// All good, lets parse the response into a JSON object
$parcelTypesJSON = json_decode($rawBody);
curl_init() is disabled for security reasons...
This means that the server has disabled that function.
If you have control of the server, then enable curl_init() in the php.ini.
More information here.
If you do not, try using file_get_contents(). more information here
There is all the relevant information present in broken form in the following links on owncloud related websites and from stackoverflow itself:
User Provisioning Api - Owncloud
PHP + curl, HTTP POST sample code
Create user on ownCloud using Ajax Jquery
User Provisioning - php Authentication error
I am trying to do something very simple :
I have setup an owncloud server in my localhost,
I have an html page that takes in string values of user name and password
I send the page request to be processed by the following php script.
<?php
echo "Begun processing credentials , first it will be stored in local variables" . "<br/>";
// Loading into local variables
$userName = $_POST['username'];
$RRpassword = $_POST['password'];
echo "Hello " . $userName . "<br/>";
echo "Your password is " . $RRpassword . "<br/>";
// Add data, to owncloud post array and then Send the http request for creating a new user
$ownCloudPOSTArray = array('username' => $userName, 'password' => $RRpassword );
$url = 'http://localhost/owncloud/ocs/v1.php/cloud/users';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $ownCloudPOSTArray);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo "<br/>Created a new user in owncloud";
?>
I get the output like:
Begun processing credentials , first it will be stored in local
variables Hello Frank Your password is frankspassword
failure 997 Unauthorised Created a new user in owncloud
I also tried to login to own cloud using following php script:
// Login As Admin
$ownAdminname = 'ownAdmin';
$ownAdminpassword = 'ownAdminPassword';
$ch = curl_init('http://localhost/owncloud');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$ownAdminname:$ownAdminpassword");
$output = curl_exec($ch);
curl_close($ch);
echo $output;
Even this one fails.
So in short it doesn't work. I am also unable to login via similar script to owncloud. What is the proper way to do this ? What settings am I missing ? Can someone help please ?
Since this question pertains to owncloud specifically, I created an account and posted a question linking this one to it in owncloud forum.
There I was suggested by the owncloud master #RealRancor, the following,
Just had another look, maybe its just easy to replace:
$url = 'http://localhost/owncloud/ocs/v1.php/cloud/users';
with
$url =
'http://adminuser:adminpass#localhost/owncloud/ocs/v1.php/cloud/users';
as shown in the documentation.
And amazingly it worked like a charm. So here is the entire modified php script:
<pre>
<?php
echo "Begun processing credentials , first it will be stored in local variables" . "<br/>";
// Loading into local variables
$userName = $_POST['username'];
$RRpassword = $_POST['password'];
echo "Hello " . $userName . "<br/>";
echo "Your password is " . $RRpassword . "<br/>";
// Login Credentials as Admin
$ownAdminname = 'ownAdmin';
$ownAdminpassword = 'ufi2016%%';
// Add data, to owncloud post array and then Send the http request for creating a new user
$url = 'http://' . $ownAdminname . ':' . $ownAdminpassword . '#localhost/owncloud/ocs/v1.php/cloud/users';
echo "Created URL is " . $url . "<br/>";
$ownCloudPOSTArray = array('userid' => $userName, 'password' => $RRpassword );
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $ownCloudPOSTArray);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo "Response from curl :" . $response;
echo "<br/>Created a new user in owncloud<br/>";
// Add to a group called 'Users'
$groupUrl = $url . '/' . $userName . '/' . 'groups';
echo "Created groups URL is " . $groupUrl . "<br/>";
$ownCloudPOSTArrayGroup = array('groupid' => 'Users');
$ch = curl_init($groupUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $ownCloudPOSTArrayGroup);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo "Response from curl :" . $response;
echo "<br/>Added the new user to default group in owncloud";
?>
</pre>
And here is the output:
Begun processing credentials , first it will be stored in local variables
Hello Frank
Your password is frankspassword
Created URL is http://ownAdmin:ufi2016%%#localhost/owncloud/ocs/v1.php/cloud/users
Response from curl : ok 100
Created a new user in owncloud
Created groups URL is http://ownAdmin:ufi2016%%#localhost/owncloud/ocs/v1.php/cloud/users/Frank/groups
Response from curl : ok 100
Added the new user to default group in owncloud
The owncloud documentation states that authentication is done by means of a basic HTTP Authentication header. What you are currently doing is sending the credentials as parameters to the API call. You need to add the following line:
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $RRpassword);
There's also a typo in CURLOPT_RETURNTRANSFER ($curl instead of $ch).
As your linked post (Create user on Owncloud) shows you need to an basic auth header with some credentials. You need to provide the admin credentials, afaict.
I am trying to connect to the Marketo.com REST API using curl.
I can't get a response from the identity service. I only get an error message
"[curl] 6: Couldn't resolve host 'MY_CLIENT_ENDPOINT.mktorest.com'
,
but I can print the constructed url and paste it into a browser address bar and this will provide the expected response with the access_token element.
I can use curl in php and in a terminal to access my gmail account so curl is able to access an https service.
I have tried sending the parameters in the curl url as a get request and also by declaring them with curl's -F option as a post request
My application uses dchesterton/marketo-rest-api available on github, but I have also tried a simple php curl request just to get the access token.
private function getToken() {
$url = "$this->client_url/identity/oauth/token?grant_type=client_credentials&client_id=$this->client_id&client_secret=$this->client_secret";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$errors = curl_error($ch);
curl_close($ch);
file_put_contents($this->logDir . 'access_token_response' . date('Y-m-d') . '.txt', $url . "\n" . $response . "\n", FILE_APPEND);
if ($errors) {
file_put_contents($this->logDir . 'access_token_errors' . date('Y-m-d') . '.txt', $errors . "\n", FILE_APPEND);
}
return $response['access_token'];
}
Again, this fails with the same error but produces a perfectly formed url that I can paste into the browser and get a valid response.
I have also tried this using post instead of get as I have for every other test mentioned, and these have been tried on my localhost and on a test server.
Can anyone explain to me why this would fail?
Does Marketo block curl on a per account basis?
I was trying to implement something similar but my code wasn't working. I'm not sure exactly what is failing but I tried your code and it seems to work perfectly after some slight modifications:
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($request_data));
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($curl);
$errors = curl_error($curl);
curl_close($curl);
I hope this helps.
I am dragging my hair out over this one right now. I have followed the following example:
http://developer.force.com/cookbook/recipe/interact-with-the-forcecom-rest-api-from-php
but here the user is being sent to the login form and needs to login. Instead I would like to post that data in my code and not have the user login but my app do that automatically.
If anyone could post an example on how to do that with oAuth I would really appreciate it as I am not eager on using that bloated SOAP implementation.
Cheers guys!
It seems after some more tinkering my attempts have been a success::
$loginurl = "https://login.salesforce.com/services/oauth2/token";
$params = "grant_type=password"
. "&client_id=" . CLIENT_ID
. "&client_secret=" . CLIENT_SECRET
. "&username=" . USER_NAME
. "&password=" . PASSWORD;
$curl = curl_init($loginurl);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 200 ) {
die("Error: call to URL failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
echo $json_response;
Now all that is left to do is store the
access_token & instance_url from that response into a session var
and work away on our objects.
I hope the above helps someone else with similar issues.
Answer for 2018:
https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_understanding_username_password_oauth_flow.htm
Make an POST request with:
grant_type: Must be password for this authentication flow.
client_id: The Consumer Key from the connected app definition.
client_secret: The Consumer Secret from the connected app definition. Required unless the Require Secret for Web Server Flow setting is not enabled in the connected app definition.
username: End-user’s username.
password: End-user’s password.
Example:
grant_type=password&client_id=3MVG9lKcPoNINVBIPJjdw1J9LLM82Hn
FVVX19KY1uA5mu0QqEWhqKpoW3svG3XHrXDiCQjK1mdgAvhCscA9GE&client_secret=
1955279925675241571&username=testuser%40salesforce.com&password=mypassword123456
See above link for more details.