how to create curl commands on moodle - php

I'm recently started developing on moodle and one big problem is that whenever i build a plugin with a web page, it don't execute any of my curl commands, i hear that moodle has his own php library(an php file called filelib.php i suppose) with curl commands and i should be using its commands instead of mine, but i don't have much experience with moodle development and php so all that code make me very confused.
i tried this question before and a gentleman helped me with an example, i tried his code and it didn't work(it changed the output but still show an error message, i also tried changing the code to no avail) and i didn't get much of an explanation about how curl commands work on moodle(i'm still grateful for his help) or whats commands on filelib.php will substitue my code, can someone help me?
my code:
<?php
require_once(__DIR__.'/../../config.php');
require_once($CFG->libdir.'/filelib.php');
$PAGE->set_url(new moodle_url(url:'/local/iesde/selecionaraulas.php'));
$PAGE->set_context(\context_system::instance());
$PAGE->set_title('selecionar aulas');
$PAGE->requires->js_call_amd('local_iesde/tabelas', 'init');
echo $OUTPUT->header();
echo $OUTPUT->render_from_template('local_iesde/manageaulas', $templatecontext);
$api_server = 'url';
$api_http_user = 'user';
$api_http_pass = 'pass';
$key_acess = 'key';
$key_name = 'API-KEY';
$format = 'json';
$params = array(
'IDstudent' => 000000,
'IDcourse' => 000000,
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "{$api_server}/format/{$format}");
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($curl, CURLOPT_USERPWD, "{$api_http_user}:{$api_http_pass}");
curl_setopt($curl, CURLOPT_HTTPHEADER, array("{$key_name}:{$key_acess}"));
curl_setopt($curl, CURLOPT_NOBODY, 1);
curl_exec($curl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$output = curl_exec($curl);
var_dump(json_decode($output));
echo $output;
echo $OUTPUT->footer()
the purpose of this curl request is to print a list of ids that will be used on another curl request to generate a video file that will be executed on a videoplayer, the variables:
$api_server = 'url';
$api_http_user = 'user';
$api_http_pass = 'pass';
$key_acess = 'key';
$key_name = 'API-KEY';
$format = 'json';
$params = array(
'IDstudent' => 000000,
'IDcourse' => 000000,
);
Are all needed to execute the commands (one of the reasons i think the gentleman's example didn't work is that it didn't used all the variables of the code to get full validation).
well that is all, i'm very new to all of this so any explanation will help, thanks for the help.

Related

curl how to format a curl request with an api key in php

hi am new to curl but need it for a particular project could you help me format this code to work i would like to get the results and print out the raw JSON on the page here is the code i am using
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "curl -u api key: https://api.companieshouse.gov.uk/search/companies");
$x = curl_exec($curl);
curl_close($curl);
print($x);
this is a link to the api page i am trying to use
https://developer.companieshouse.gov.uk/api/docs/search/companies/companysearch.html
this is the example they give on the page
curl -uYOUR_APIKEY_FOLLOWED_BY_A_COLON:
https://api.companieshouse.gov.uk/search/companies
these are the parameters for the call if possible i would like to set them as well
q (required)
items_per_page (optional)
start_index (optional)
I simplified your request.you can try this by using below code.
$params = array("q"=>"<Some Value>","items_per_page"=>"<Some Value>","start_index"=>"<Some Value>");
$curl = curl_init();
curl_setopt($curl, CURLOPT_USERPWD, "api key:");
curl_setopt($curl, CURLOPT_URL, "https://api.companieshouse.gov.uk/search/companies?".http_build_query($params));
$x = curl_exec($curl);
curl_close($curl);
print($x);
Thanks for this opportunity to learn more of curl :-)
I tested the code below, it works. Of course you must be registered on the site and you must have got your API key. You will then provide it as username/password, but without username (this is written here on the site).
$searchvalue= 'Test';
$curl = curl_init("https://api.companieshouse.gov.uk/search/companies?q=$searchvalue");
curl_setopt($curl, CURLOPT_USERPWD, "your_api_key_provided_by_the_site");
// curl_setopt($curl, CURLOPT_HEADER, true); // when debugging : to show returning header
$rest = #curl_exec($curl);
print_r($rest);
if(curl_errno($curl))
{
echo 'Curl error : ' . curl_error($curl);
}
#curl_close($curl);

-F Curl option on PHP

I'm trying to run CURL command in PHP to upload image to an API
the code mentioned in the doc was:
curl -u 15:tokenkeyiskmzwa8awaa https://api.bukalapak.com/v2/images.json -F file=#product-image.png -X POST
Have tried using mac terminal running this curl command (with proper username and password) and successfully got the result as it is uploading, however was not successfully doing it on PHP.
My php code is :
<?php
$data = array('file'=> '#'.$imagePath );
// this is an absolute path, give something like D://folder/path/on/my/webserver/image.jpg
$user = '1234567';
$pass = '123456';
$ch = curl_init();
$curl_options[CURLOPT_URL] = 'https://api.bukalapak.com/v2/images.json';
$curl_options[CURLOPT_CAINFO] = storage_path('app/cacert.pem');
$curl_options[CURLOPT_HEADER] = "Content-Type: application/x-www-form-urlencoded";
$curl_options[CURLOPT_POST] = 1;
$curl_options[CURLOPT_USERPWD] = $user.':'.$pass;
$curl_options[CURLOPT_POSTFIELDS] = http_build_query($data);
curl_setopt_array($ch, $curl_options);
$content = curl_exec($->ch);`
Curl version : 7.47.1
PHP version : 5.6.21
any feedback is very appreciated.
You did not posted the complete script: $curl_options is undefined, storage_path is related to Laravel but there is no import, etc.
Something like the following script should work as you expect (I didn't tested it since I don't have an account on this service):
<?php
$imagePath = 'path/to/your/image.ext';
$user = 'youruser';
$pass = 'yourpass';
$file = curl_file_create($imagePath);
$body = ['file' => $file];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.bukalapak.com/v2/images.json');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, $user.':'.$pass);
curl_setopt($ch, CURLOPT_CAINFO, 'path/to/cacert.pem');
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$result = curl_exec($ch);
curl_close($ch);

Convert cURL from PHP to ruby code

I am trying to create a form for the user to buy product from my Ruby on Rails website by using their "Scratch Card for Mobile Phones".
The problem is that the service only provides Module code for PHP. So I have to convert it to Ruby to put into my website. Here are the codes I want to convert to Ruby:
$post_field = 'xyz=123&abc=456';
$api_url = "https://www.nganluong.vn/mobile_card.api.post.v2.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$api_url);
curl_setopt($ch, CURLOPT_ENCODING , 'UTF-8');
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_field);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
I have tried to convert them to Ruby code but always got confused. Can anyone help me convert these codes into working Ruby codes? Thanks in advance!
Here is my silly code so far:
RestClient.post($api_url, $post_field, "Content-Type" => "application/x-www-form-urlencoded")
Basically all that I need is a ruby version of the php curl code. I'm a newbie, not an experienced programmer, so please help.
Try something like this:
require 'rest-client'
require 'rack'
post_query = 'xyz=123&abc=456'
api_url = "https://www.nganluong.vn/mobile_card.api.post.v2.php"
query_hash = Rack::Utils.parse_nested_query(post_query)
begin
response = RestClient.post api_url, :params => query_hash
print response.code
print response.body
rescue Exception => e
print e.message
end
All the code is doing is sending a payload xyz=123&abc=456 through a POST request to a specified URL.
You might use e.g. the curb gem for this:
response = Curl.post("https://www.nganluong.vn/mobile_card.api.post.v2.php", {:xyz => 123, :abc => 456})
result = response.body_str
status = response.status

Upload file to Bitbucket via PHP script

I try to upload my database to bitbucket downloads section of my repository via a PHP script using curl library. Normally i go to my phpmyadmin and export my database to a folder, then going to my bitbucket account under downloads section of my repository and upload manually. I need a script that automates these tasks.
I tried using curl library like this:
// bitbucket username and password
define('USERNAME', 'my_username');
define('PASSWORD', 'my_password');
$url = 'https://bbuseruploads.s3.amazonaws.com/';
//This needs to be the full path to the file you want to send.
$file_name_with_full_path = realpath('apache_pb2.gif');
$post = array('extra_info' => '123456', 'file_contents' => '#' . $file_name_with_full_path); // image file example here
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, USERNAME . ":" . PASSWORD);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$resp = curl_exec($ch);
// validate CURL status
if (curl_errno($ch))
throw new Exception(curl_error($ch), 500);
The result:
<error><code>InvalidArgument</code>
<message>Unsupported Authorization Type</message>
<argumentvalue>Basic hash_code_here</argumentvalue>
<argumentname>Authorization</argumentname>
<requestid>hash_code_here</requestid>
<hostid>hash_code_here</hostid>
</error>
If you need further clarifications please let me know.
Just for the case someone finds this old corpse here:
I solved it by this funktion function:
/**
* Uploads a file to Bitbucket Download area of the configured repository
* Does the same as thi bash command:
* curl -X POST "https://USER:PW#api.bitbucket.org/2.0/repositories/owner/slug/downloads/" --form files=#"test.txt"
* #param string $filename
* #param string $apiEndpoint
* #param string $apiUser
* #param string $apiPassword
* #return bool|string
* #throws Deployer\Exception\Exception
*/
public static function sendFileToDownload(
string $filename,
string $apiEndpoint,
string $apiUser,
string $apiPassword
) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $apiEndpoint);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLAUTH_BASIC, 1);
curl_setopt($curl, CURLOPT_USERPWD, "$apiUser:$apiPassword");
$data = [
'files' => curl_file_create($filename),
];
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$erg = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($erg === false || $status > 300) {
throw new Deployer\Exception\Exception("Result: ".print_r($erg, true), $status);
}
curl_close($curl);
}
}
For me the most important point was this section:
$data = [
'files' => curl_file_create($filename),
];
This results in a local file been uploaded to my repos download area with the name $filename (filename path).
Had this same problem today. "Unsupported Authorization Type" response from an API CURL request.
I spent a long time consulting with Google. In the end, I discovered that my URL had two slashes in it together (accidentally). See, the API I'm connecting to has a URL, and then an API endpoint. Like this:
https://www.example.com/api/v2/foo -or-
https://www.example.com/api/v2/bar
But I accidentally was combining them like this:
curl_setopt($curl, CURLOPT_URL, $url ."/". $endpoint);
given my data:
$url = "https://www.example.com/api/v2/"
$endpoint = "foo"
I ended up with this:
"https://www.example.com/api/v2//foo"
Problem solved by removing the ."/". and just making it this: .
BONUS POSSIBILITY: Something else interesting I learned in the process was that the API folks prefer double-quotes around json data posted to them. I haven't verified it makes a difference, but instead of wrapping double-quotes in single-quotes (or visa-versa), escaping the internal double-quotes is how I left things. And it's working.

Using cURL to get Facebook Album jSON with PHP

I found a script in Web Designer magazine that enables you to gather Album Data from a Facebook Fan Page, and put it on your site.
The script utilizes PHP's file_get_contents() function, which works great on my personal server, but is not allowed on the Network Solutions hosting.
In looking through their documentation, they recommended that you use a cURL session to gather the data. I have never used cURL sessions before, and so this is something of a mystery to me. Any help would be appreciated.
The code I "was" using looked like this:
<?php
$FBid = '239319006081415';
$FBpage = file_get_contents('https://graph.facebook.com/'.$FBid.'/albums');
$photoData = json_decode($FBpage);
$albumID = $photoData->data[0]->id;
$albumURL = "https://graph.facebook.com/".$albumID."/photos";
$rawAlbumData = file_get_contents("https://graph.facebook.com/".$albumID."/photos");
$photoData2 = json_decode($rawAlbumData);
$a = 0;
foreach($photoData2->data as $data) {
$photoArray[$a]["source"] = $data->source;
$photoArray[$a]["width"] = $data->width;
$photoArray[$a]["height"] = $data->height;
$a++;
}
?>
The code that I am attempting to use now looks like this:
<?php
$FBid = '239319006081415';
$FBUrl = "https://graph.facebook.com/".$FBid."/albums";
$ch = curl_init($FBUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$contents = curl_exec($ch);
curl_close($ch);
$photoData = json_decode($contents);
?>
When I try to echo or manipulate the contents of $photoData however, it's clear that it is empty.
Any thoughts?
Try removing curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); I'm not exactly sure what that does but I'm not using it and my code otherwise looks very similar. I'd also use:
json_decode($contents,true); This should put the results in an array instead of an object. I've had better luck with this approach.
Put it in the works for me category.
Try this it could work
$ch = curl_init($FBUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$contents = curl_exec($ch);
$pageData = json_decode($contents);
//object to array
$objtoarr = get_object_vars($pageData);
curl_close($ch);
Use jquery get Json instead This tips is from FB Album downloader GreaseMonkey script

Categories