I am building a CMS/CRM and want to let users install this software on their server using their databases.
I would like to track some of the data from that installation, like version, so I can send updates to that installation if it is out of date. Like when Wordpress tells you a new version is available.
I also want to be able to track the number of users to be able to charge for the installation.
I am using PHP, MySQL(PDO).
Can you let me know what this process is called and any references to this process would be fantastic.
In your application you may have an array of data you'd like to track; something like this
$data = array(
'domain' => 'http://example.com',
'version' => '1.4.35',
'date_added' => '2014-08-20',
'last_update' => '2014-08-22'
);
Then you could send a request to your server to see if is anything new out there; using cURL or any other method for sending an HTTP request
$curl = curl_init("http://your-server.com/your-service/");
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // convert it to JSON format
$json = curl_exec($curl);
curl_close($curl);
// this is your feedback, in JSON format
$response = json_decode($json, true);
It would be good to check the status, like this, but before the curl_close() call
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($status == 201){
// ... all fine
}else{
// otherwise, do something but don't use exit() or die() in this case
}
The $response value, after decoding, could look something like this
array(
'some_key' => 'some_value',
'another_key' => 'another_value'
...
);
Now, according to the response, echo a message to the user, like this
if(isset($response['some_key']) && $response['some_key'] == 'some_value')){
echo "An update is out there, Check it out";
}
Related
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've got an online store and I make use of an online accounting software where I manually post orders to. The online accounting software has a very big api and I would like to send orders over automatically when a customer places an order.
Once an order is completed the customer lands up on the Success Page, i.e. successpage.php
In this page I've got the following:
$sendOrder = file_get_contents("https://myonlinestore.com/sendorder.php?order=1234");
On sendorder.php, I receive the $_GET parameter "order" which is the order number, and the I process several SQL requests to retrieve data of the order from the database.
Once I've got all this data, I then initiate a CURL post to send the data using the API of the accounting system.
Here is a watered-down version of my code that contains the essential parts:
$orderNum = htmlspecialchars($_GET["order"]) // SENT OVER FILE_GET_CONTENTS
// bOf process SQL here and get order info stored in various variables
// EXECUTE SQL HERE
// eOf process SQL here and get order info stored in various variables
$invoice = array(
'customer_id' => $custaccount,
'estimate_number' => $orderRef,
'reference_number' => $orderNum
// MANY OTHER VARIABLES ENTERED HERE, BUT LEFT OUT TO KEEP THINGS SHORT
);
$jsonInvoice = json_encode($invoice);
$url = 'https://ACCOUTINGAPP.com/api/v2/orders';
$data = array(
'authtoken' => '***********',
'JSONString' => $jsonInvoice,
'company_id' => '***********'
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded") );
$response = false;
$response = curl_exec($ch);
curl_close($ch);
// TEST RESPONSE
if($response !== false) {
var_dump($response);
}
else
{
echo "oops error hehehe";
}
MY MAIN CONCERN:
I expect the user to immediately close the tab or page once they're on successpage.php.
But I would like to ensure that the successpage.php's $sendOrder = file_get_contents() and the code that it executes on sendorder.php continues running regardless of user connection.
So my question is, where would I put:
ignore_user_abort(TRUE);
Also, should I use output buffering? I'm only asking because I read a post about this on some other website and it advised this.
And lastly, should I include:
set_time_limit(0);
Call ignore_user_abort(TRUE); as soon as you can. And you do not need output buffering as noone is going to see your output once browser tab is closed anywyay, so you just need to ensure your script continues if it was already doing anything.
I am trying to get the weather data from NOAA and parse it to get the current temperature, humidity, and other values. I am trying to get the JSON data from its website, which uses the latitude, and longitude values to get the weather data of location. I am getting trouble to get the data, and I found out we have to use CURl to get it done, and I have no idea on using CURL.
this is the URL i am using to get the data
"https://api.weather.gov/points/$latitude,$longitude/forecast".
This is what I tried, based on one example I found here. I want to know how to pass the latitude, and longitude, and add the forecast at the end in the url
<?php
/**
* Created by PhpStorm.
*/
$url='https://api.weather.gov/points/'; //noaa url of choice
$params=array('39.7456','-97.0892','forecast');
$curl = curl_init();
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $params);
curl_setopt($curl, CURLOPT_URL, $url);
$result = curl_exec($curl);
$data = json_decode($result);
curl_close($curl);
echo "<pre>";
echo json_encode($data, JSON_PRETTY_PRINT);
echo "<pre>";
?>
Simply append the coordinates to the URL.
<?php
$ch = curl_init('https://api.weather.gov/points/39.7456,-97.0892/forecast');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSLVERSION => 6,
CURLOPT_USERAGENT => 'Firefox',
]);
$response = curl_exec($ch);
if($response === false)
exit(curl_error($ch));
print_r(json_decode($response));
A few notes about the code :
Passing the URL to curl_init is the same as setting it with curl_setopt(CURLOPT_URL
curl_exec returns false on failure, hence the $response === false test. I used === in this case otherwise PHP may interpret an empty string as false, which doesn't make sense in this context.
The network connection would fail unless I set the SSL version to 6 (or CURL_SSLVERSION_TLSv1_2)
The API would forbid me from accessing the data unless I specified a believable user-agent, in this case Firefox.
I have an existing PHP script, which essentially connects to 2 databases each on a different server and performs a few MySQL queries on each. The ultimate results are stored in a data array which is used to write said results into a JSON file.
All of this works perfectly. The data is inserted into the mysql table correctly and the JSON file is exactly the way it should be.
However, I need to add a block to the end of my script that makes a POST request to one of our affiliate's API and upload the info there. We're currently manually uploading this JSON file to the api instance but we have the configuration data for their server to use in a POST request now so that when this script is run it automatically sends the data rather than us having to manually update it.
The main thing is I'm not exactly sure how to go about that. I've started with code for doing this but I'm not familiar with cURL so I don't know the best way to structure this in php.
Here is an example the affiliate gave me in cURL command line syntax:
curl \
-H "Authorization: Token AUTH_TOKEN" \
-H "Content-Type: CONTENT_TYPE" \
-X POST \
-d '[{"email": "jason#yourcompany.com", "date": "8/16/2016", "calls": "3"}]'
\
https://endpoint/api/v1/data/DATA_TYPE/
I have my auth token, my endpoint URL and my content type is JSON, which can be seen in my code below. Also, I have an array instead of the example for the body above.
and here's the affected part of my code:
//new array specifically for the final JSON file
$content2 = [];
//creating array for new fetch since it now has the updated extension IDs
while ($d2 = mysqli_fetch_array($data2, MYSQLI_ASSOC)) {
// Store the current row
$content2[] = $d2;
}
// Store it all into our final JSON file
file_put_contents('ambitionLog.json', json_encode($content2, JSON_PRETTY_PRINT ));
//Beginning code to upload to Ambition API via POST
$url = 'endpoint here';
//Initiate CURL
$ch = curl_init($url);
//JSON data
$jsonDataEncodeUpload = json_encode($content2, JSON_PRETTY_PRINT);
//POST via CURL
curl_setopt($ch, CURLOPT_POST, 1);
//attach JSON to post fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncodeUpload);
//set content type
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//execuate request
$postResult = curl_exec($ch);
So, like I said, nothing about the file or the data needs to be changed, I just need to have this cURL section take the existing array that's being written to a JSON file and upload it to the API via post. I just need help making my php syntax for curl match the command line example.
Thanks for any possible help.
Have you tried with file_get_contents ( http://en.php.net/file_get_contents ).
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
I have found the answer on stackoverflow How to post data in PHP using file_get_contents?
Here is worked example of code. Check $err may be it will be helpful.
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST('data'));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
$result = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
I am making a command line application. I need to send out multiple POST requests via cURL simultaneously after I have performed log in procedures - meaning outgoing requests must send session id etc.
The chain of events is as follows:
I open cURL connection with curl_init
I log in to remote site sending POST request with curl_exec and get returned HTML code as response
I send multiple POST requests to same site simultaneously.
I was thinking of using something like that:
// Init connection
$ch = curl_init();
// Set curl options
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, 1);
// Perform login
curl_setopt($ch, CURLOPT_URL, "http://www.mysite/login.php");
$post = array('username' => 'username' , 'password' => 'password');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$result = curl_exec($ch);
// Send multiple requests after being logged on
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1);
for($i = 0 ; $i < 10 ; $i++){
$post = array('myvar' => 'changing_value');
curl_setopt($ch, CURLOPT_URL, 'www.myweb.ee/changing_url');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_exec($ch);
}
But this doesn't seem to work as only the first request in loop seems to be sent.
Using curl_multi_init would probably one solution but I don't know if i can pass it the same cURL handle multiple times with changed options for each.
I don't need any response from server for those simultaneous requests but it would be awesome if it also can be done somehow.
It would be perfect if someone could push me in the right direction how to do it.
You'll need to create a new curl handle for every request, and then register it with http://www.php.net/manual/en/function.curl-multi-add-handle.php
here is some code i ripped out and adapted from my code base, have in mind that you should add error checking in there.
function CreateHandle($url , $data) {
$curlHandle = curl_init($url);
$defaultOptions = array (
CURLOPT_COOKIEJAR => 'cookies.txt' ,
CURLOPT_COOKIEFILE => 'cookies.txt' ,
CURLOPT_ENCODING => "gzip" ,
CURLOPT_FOLLOWLOCATION => true ,
CURLOPT_RETURNTRANSFER => true ,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $data
);
curl_setopt_array($curlHandle , $defaultOptions);
return $curlHandle;
}
function MultiRequests($urls , $data) {
$curlMultiHandle = curl_multi_init();
$curlHandles = array();
$responses = array();
foreach($urls as $id => $url) {
$curlHandles[$id] = CreateHandle($url , $data[$id]);
curl_multi_add_handle($curlMultiHandle, $curlHandles[$id]);
}
$running = null;
do {
curl_multi_exec($curlMultiHandle, $running);
} while($running > 0);
foreach($curlHandles as $id => $handle) {
$responses[$id] = curl_multi_getcontent($handle);
curl_multi_remove_handle($curlMultiHandle, $handle);
}
curl_multi_close($curlMultiHandle);
return $responses;
}
There's a faster, more efficient option ... that doesn't require that you use any curl at all ...
http://uk3.php.net/manual/en/book.pthreads.php
http://pthreads.org
See github for latest source, releases on pecl ....
I will say this, file_get_contents may seem appealing, but PHP was never designed to run threaded in this manner, it's socket layers and the like give no thought to consumption you might find that it's better to fopen and sleep inbetween little reads to conserve CPU usage ... however you do it it will be much better ... and how you do it depends on what kind of resources you want to dedicate the task ...