I'm using codeigniter and I want to send an add request to openfire, but i don't really understand what I have to do. I'm a beginner, I read this guide User Service and i tried to add a new user with curl Curl lib, but I'm stuck. Openfire is correctly configured because if I make request from browser the add works
This is my code
$this->load->library('curl');
$username='usertest';
$password='password';
$header='Authorization';
$content='mykey';
$this->curl->create('http://myserver.net', 9090);
$this->curl->http_header($header, $content);
$this->curl->http_header('Content-Type', 'application/xml');
$this->curl->post(array('username'=>$username,'password'=>$password));
$this->curl->execute();
But users are not added
I'm sorry for my bad English
Here is one implementation of user service client (it is based on Curl but not on codeigniter):
$url = "http://localhost:9090/plugins/userService/users";
$xml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user>
<username>'.$user['username'].'</username>
<password>'.$user['password'].'</password>
<name>'.$user['name'].'</name>
<email>'.$user['email'].'</email>
</user>';
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER,true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: secret',
'Content-Type: application/xml'
));
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml );
#curl_setopt($ch,CURLOPT_POSTFIELDSPOST, count($fields));
#curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
ob_start(); // outer buffer
#echo "Code: $http_status | Username: {$user['name']}\n";
ob_end_flush();
//close connection
curl_close($ch);
if ($http_status == 201) {
return true;
}
else return false;
You should set the Content Type and and Authorization as array in a header.
And your XML content looks wrong. It is not only username / password in array.
Related
Trying to add some kind of value to each data point so I can send the response (numbers only) to an existing table . I've been searching online and no CURL API response seems to be this simple so I can find an answer. (sorry new to this, don't know the "lingo")
This is the response I've been able to echo on screen.
"{"price": 2049.27, "change_point": -5.76, "change_percentage": -0.28, "total_vol": "1.27M"}"
rest of php below
<html>
<?php
$url = 'https://realstonks.p.rapidapi.com/';
$collection_name = $_REQUEST["stock_name"];
$request_url = $url . '/' . $collection_name;
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'X-RapidAPI-Host: www.xyz.com',
'X-RapidAPI-Key: xxxxxxxxxxxxxxxxxxx',
'Content-Type: application/json']);
$response = curl_exec($curl);
curl_close($curl);
//Uncomment bellow to show data on screen
echo $response . PHP_EOL;
enter code here
//var_dump(json_decode($json));
//var_dump(json_decode($json, true));
// Initiate curl
$ch = curl_init();
// 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);
?>
I'm not much into PHP but here to here. If I'm not mistaken it, I think you want to store $response in <td> element. This resource can help https://www.daniweb.com/programming/web-development/threads/428730/how-to-display-php-variable-in-html
Im trying to connect to the API services of 2ba. Somehow I just can't connect. I get the error: error: "invalid_client"
I dont know what to try, it feels like I need to hash my cliend_secret or complete url but I dont see that in the documentation.
This is my code (PHP):
<?php
// ---- GET TOKEN ----
// Base url for all api calls.
$baseURL = 'https://authorize.2ba.nl';
// Specified url endpoint. This comes after the baseUrl.
$endPoint = '/OAuth/Token';
// Parameters that are required or/and optianal for the endPoint its request.
$parameters = 'grant_type=password&username=abc#abc.com&password=123abc&client_id=myClientID&client_secret=myClientSecret';
// All parts together.
$url = $baseURL . $endPoint . '?' . $parameters;
//Init session for CURL.
$ch = curl_init();
// Options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
// Init headers for access to the binance API signed data.
$headers = array();
$headers[] = 'Content-type: application/x-www-form-urlencoded';
$headers[] = 'Content-Length: 0';
// Setting headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
// Ends the CURL session, frees all resources and deletes the curl (ch).
curl_close($ch);
$result = json_encode($data);
echo($data);
exit();
?>
The authentication is oauth2 and I want to use the "Password Grant" flow since I can login automaticly this way. Also I see in the example code in C# that they encode the url, something im not doing yet but did try. It did not work.
// Using $encodedUrl like this: curl_setopt($ch, CURLOPT_URL, $encodedUrl); but does not work.
$encodedUrl = urlencode($url);
Alright so I fixed it. I now got my access token and am able to recieve data from the API. This is what I did:
// ---- GET TOKEN - FLOW: USER PSW ----
// No changes
$baseURL = 'https://authorize.2ba.nl';
// No changes
$endPoint = '/OAuth/Token';
// $parameters is now an array.
$parameters = array(
'grant_type' => 'password',
'username' => 'myUsername',
'password' => 'myPassword',
'client_id' => 'myClientID',
'client_secret' => 'myClientSecret'
);
// Removed the $parameter part
$url = $baseURL . $endPoint;
//Init session for CURL.
$ch = curl_init();
// Init headers for access to the binance API signed data.
$headers = array();
$headers['Content-Type'] = "application/x-www-form-urlencoded";
// NOTE: http_build_query fixed it.
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters)); // Automaticly encodes parameters like client_secret and id.
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
// Ends the CURL session, frees all resources and deletes the curl (ch).
curl_close($ch);
$result = json_encode($data);
echo($data);
exit();
I run an Apache webserver with mod_dav/mod_dav_fs on a windows server.
Users can edit certain files via WebDAV.
WebDAV is set up and running correctly so far...
The question is, how can I find out if and which files are currently opened via WebDAV?
Apache writes this info into its "DavLockDB".
Is there a way to read that file or to find out which files are currently locked?
I already tried it with via php:
$fp = fopen($file, 'c');
if (!flock($fp, LOCK_EX|LOCK_NB, $wouldblock)) {
// lock not obtained
echo 'file maybe open';
}
else {
// lock obtained
echo 'file is free';
}
This gives me a correct result if the file is opened locally on the server, but not if the file is opened via WebDAV.
Has anyone ever had a similar problem?
Kind regards
Thomas
I've been tied to and frustrated by WebDAV for some years, and I often had a need to be able to identify locked files and occasionally unlock them. I recently wrote a small tool in PHP to achieve this that you can see on Github.
Most of my answers were found in the RFC document & on the webdav.org site.I didn't encounter a solution using the DavLockDB and went the official route sending cURL requests to the DAV server as a real application would with HTTP verbs to get the info that I needed about files or directories.
In short you choose a file or directory as an endpoint and send PROPFIND request. If the endpoint is a directory you'll get a list of resources (files/directories) & their properties that are in that directory (and possibly under it depending on your DEPTH setting). If the endpoint is a file you'll get the file properties. In both cases the information is returned as XML and if any resource is locked the properties will include a LockToken.
Here's a PHP function that you could use based on a method in the repository noted above:
function propfind() {
$location = 'https://example.com:8000' // ROUTE TO SERVER
$endpoint = '/webdav/'; // FINAL DESTINATION
$auth = 'user:pass'; // BASE64 ENCODED USERNAME:PASSWORD
$url = $location.$endpoint;
$host = parse_url($location, PHP_URL_HOST);
$ch = curl_init();
// FIX LOCALHOST SSL CERTIFICATE ISSUES
if ($_SERVER['SERVER_NAME'] == 'localhost') curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+'); // CREATE A STREAM TO SAVE THE VERBOSE CONNECTION DATA
curl_setopt($ch, CURLOPT_STDERR, $verbose);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PROPFIND');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml; charset="utf-8"',
'Host: '.$host,
'Authorization: Basic '.$auth,
'Depth: 1',
));
/*
// OPTIONALLY LIMIT THE RESPONSE TO SPECIFIC PROPERTIES
$xml = '<?xml version="1.0" encoding="utf-8" ?><D:propfind xmlns:D="DAV:"><D:prop><D:creationdate/><D:getlastmodified/><D:getcontentlength/></D:prop></D:propfind>';
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
*/
$response = curl_exec($ch);
$curlInfo = curl_getinfo($ch);
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
if(curl_error($ch)) {
return array('error'=>curl_errno($ch).': '.curl_error($ch), 'response'=>print_r($curlInfo,1), 'verbose'=>$verboseLog);
}
curl_close($ch);
return array($response, $verboseLog);
}
A sample response might be:
<?xml version="1.0" encoding="utf-8"?>
<D:multistatus xmlns:D="DAV:">
<D:response xmlns:lp1="DAV:" xmlns:lp2="http://apache.org/dav/props/">
<D:href>/webdav/test.xlsx</D:href>
<D:propstat>
<D:prop>
<lp1:resourcetype/>
<lp1:creationdate>2020-04-11T20:30:58Z</lp1:creationdate>
<lp1:getcontentlength>9853</lp1:getcontentlength>
<lp1:getlastmodified>Thu, 06 Aug 2020 16:17:05 GMT</lp1:getlastmodified>
<lp1:getetag>"123456-789b-ab12345cd67e89"</lp1:getetag>
<lp2:executable>T</lp2:executable>
<D:supportedlock>
<D:lockentry>
<D:lockscope><D:exclusive/></D:lockscope>
<D:locktype><D:write/></D:locktype>
</D:lockentry>
<D:lockentry>
<D:lockscope><D:shared/></D:lockscope>
<D:locktype><D:write/></D:locktype>
</D:lockentry>
</D:supportedlock>
<D:lockdiscovery>
<D:activelock>
<D:locktype><D:write/></D:locktype>
<D:lockscope><D:exclusive/></D:lockscope>
<D:depth>infinity</D:depth>
<ns0:owner xmlns:ns0="DAV:"><ns0:href>Username</ns0:href></ns0:owner>
<D:timeout>Second-896</D:timeout>
<D:locktoken>
<D:href>opaquelocktoken:a12bc34d-567e-8901-23d4-5ab6cd7e8f90</D:href>
</D:locktoken>
</D:activelock>
</D:lockdiscovery>
<D:getcontenttype>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</D:getcontenttype>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
</D:multistatus>
Note the <D:locktoken> entry which indicates that the file is locked. In theory you could use the function recursively to map out the whole resource and highlight any locked files.
To unlock a file you need the credentials of the user that created the lock. Then send the request using UNLOCK as the HTTP verb:
function unlock () {
$lockToken = 'opaquelocktoken:a12bc34d-567e-8901-23d4-5ab6cd7e8f90';
$location = 'https://example.com:8000' // ROUTE TO SERVER
$endpoint = '/webdav/'; // FINAL DESTINATION
$auth = 'user:pass'; // BASE64 ENCODED USERNAME:PASSWORD
$url = $location.$endpoint;
$host = parse_url($location, PHP_URL_HOST);
$ch = curl_init();
// FIX LOCALHOST SSL CERTIFICATE ISSUES
if ($_SERVER['SERVER_NAME'] == 'localhost') curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'UNLOCK');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Host: '.$host,
'Authorization: Basic '.$auth,
'Lock-Token: <'.$lockToken.'>',
));
$response = curl_exec($ch);
$curlInfo = curl_getinfo($ch);
if(curl_error($ch)) {
$unlockStatus = 'ERROR: '.curl_error($ch).print_r($curlInfo,1);
}
else {
$unlockStatus = array(
'status' => ($curlInfo['http_code'] == '204' ? 'ok' : 'Fail'),
'response' => htmlentities($response),
'curlInfo' => $curlInfo,
);
}
curl_close($ch);
return $unlockStatus;
}
NB: In a more manual way you can get properties and unlock files from the command line with 2 cURL commands:
// GET RESOURCE PROPERTIES
curl -X PROPFIND '{path-to-resource}' -H 'Authorization:Basic {base64 encoded username:password}' -H 'Depth:1'
// UNLOCK A LOCKED FILE
curl -X UNLOCK '{path-to-resource}' -H 'Authorization: Basic {base64 encoded username:password}' -H 'Lock-Token: <{lock-token-from-first-request}>'
I would like to create new categories in CS-Cart through its API.
So far I have this code (running it through browser, just for testing):
$cfg = get_config(); //connection to DB
$product_data = array();
$product_data["category"] = "Category Test API";
$product_data["company_id"] = 1;
$product_data["status"] = "A";
//CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_USERPWD, 'USER EMAIL'.":".'YOUR API:KEY');
curl_setopt($ch, CURLOPT_URL, $cfg["cscart_store_url"]."api/categories/");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
)
);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($product_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
if( !curl_error($ch) ) {
echo "no error";
curl_close($ch);
return json_decode($server_output, TRUE);
}
else {
echo "error found!!!";
print_r("Error: ".curl_error($ch));
return 0;
}
There is a documentation here: https://docs.cs-cart.com/latest/developer_guide/api/entities/categories.html.
But I still couldn't make it work although I did not get any errors from curl_exec.
Your json is well encoded, your header have the Content-Type, i think your problem is your cscart_store_url who have a wrong url or your USERPWD isn't good (I believe you didnt put USER EMAIL in your auth
As long as I understood, cs-cart API has some required values in order to make an INSERT API call. Thus, the categories should be already be created inside cs-cart dashboard and match them somehow in the PHP script
On the other hand, if you want to UPDAtE a product for example, you could UPDAte only the specified values you send to API call, without the need of sending all the required API values.
Last but not least, there are more than one Authorizations methods to make the call. I used CURL in order to do the API call and there is a parameter CURLOPT_HTTPHEADER which I have added the below code:
...
CURLOPT_HTTPHEADER => array(
"Authorization: Basic XXXxxxxXXXXxxxXXXlzLmNvbS5ncjpKejMXXXxxxxXN0Y2MDQxenprbEXXXxxXXXE3Mg==",
"Content-Type: application/json",
"cache-control: no-cache"
),
...
Where Authorization is: Basic base64(user#example.com:API_KEY_taken_from_cscart)
Applying all the above the code and the API worked!
thanks everyone for the help and comments
I have been trying to figure out how to make a soap request using php/laravel. But from all the research on internet since two days now the only things that I can find are old rusty php codes to make soap requests non of them even worked:
Here is a snipped that I am trying to make it work so I have a general view of those soap requests but I only get errors not able to make a soapclient:
<?php
$aHTTP['http']['header'] = "User-Agent: PHP-SOAP/5.5.11\r\n";
$aHTTP['http']['header'].= "username: XXXXXXXXXXX\r\n"."password: XXXXX\r\n";
$context = stream_context_create($aHTTP);
$client=new SoapClient("http://www.thomas-bayer.com/axis2/services/BLZService?wsdl",array('trace' => 1,"stream_context" => $context));
$result = $client::__getFunctions();
var_dump($result);
since it looks super hard to me to find any info about the soap with php any idea ?
This is a sample of a soap request I currently make to a payment provider via php using curl statements. Basically map the xml request you want to make in a string. The string will be sent in the curl post fields and the response returned.
$soapdata="<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:tns='tns:ns'>
<soapenv:Header>
<tns:CheckOutHeader>
<MERCHANT_ID>$merchantid</MERCHANT_ID>
<PASSWORD>$password</PASSWORD>
<TIMESTAMP>$timestamp</TIMESTAMP>
</tns:CheckOutHeader>
</soapenv:Header>
<soapenv:Body>
<tns:processCheckOutRequest>
<MERCHANT_TRANSACTION_ID>$merchanttransactionid</MERCHANT_TRANSACTION_ID>
<REFERENCE_ID>$referenceid</REFERENCE_ID>
<AMOUNT>$amount</AMOUNT>
<MSISDN>$mobileno</MSISDN>
<!--Optional:-->
<ENC_PARAMS></ENC_PARAMS>
<CALL_BACK_URL>$callbackurl</CALL_BACK_URL>
<CALL_BACK_METHOD>$callbackmethod</CALL_BACK_METHOD>
<TIMESTAMP>$timestamp</TIMESTAMP>
</tns:processCheckOutRequest>
</soapenv:Body>
</soapenv:Envelope>";
//End Soap data
//We call the server for the first time
//end calling function
function makesoaprequest($url, $soapdata)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml', 'Authorization: Basic'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "$soapdata");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Begin SSL
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
//End SSL
$response = curl_exec($ch);
return $response;
curl_close($ch);
}