I'm trying to get together a basic example of how to use Google Closure to minify JS. I can't seem to get this to work at all.
I'm trying to follow these examples:
https://developers.google.com/closure/compiler/docs/gettingstarted_api
http://closure-compiler.appspot.com/home
When working on API's and/or AJAX code, the first thing I try to is get the variables and values setup properly using just Advanced Rest Client Applications - a Chrome Extension. Whenever I send this data, though, I get an empty response (image below).
Trying to insert the same code into my PHP code, no matter what I send in the $postData variable, I get an empty (null) response.
PHP Code:
$postData =
http_build_query(
[
'output_info' => 'compiled_code',
'output_format' => 'text',
'compilation_level' => 'SIMPLE_OPTIMIZATIONS',
'js_code' => urlencode("function hello(name) { // Greets the user alert('Hello, ' + name); } hello('New user');")
]
);
$ret = $this->ci->curl->simple_post(
$url,
$postData,
$options
);
var_dump($ret);
die();
Response:
string ' ' (length=1)
I'm 99% confident that I'm missing something to use the Closure API like a key or something, but I have no idea how to proceed.
After many, many, many attempts, I found that if I used rawurlencode() instead of urlencode(), it works. Here's the final function.
// use google closure to get compiled JS
$encoded = rawurlencode($js);
$postData =
'output_info=compiled_code&' .
'output_format=text&' .
'compilation_level=WHITESPACE_ONLY&' .
'js_code=' . $encoded
;
$options = [];
$call = curl_init();
curl_setopt_array(
$call,
array(
CURLOPT_URL => 'http://closure-compiler.appspot.com/compile',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HEADER => 0,
CURLOPT_FOLLOWLOCATION => 0
)
);
$jscomp = curl_exec($call);
return $jscomp;
Related
CoinMarketCap Api offer a lot of data by making calls to different links. Every time you make a call it cost 1 credit and of course, if that call return 5,000 coins then it cost 25 credits. So, I can't make call to different link every minute. How can I make a call to at least 4 links such as:
https://pro-api.coinmarketcap.com/v1/cryptocurrency/trending/latest
https://pro-api.coinmarketcap.com/v1/cryptocurrency/trending/gainers-losers
https://pro-api.coinmarketcap.com/cryptocurrency/listings/latest?limit=5000
https://pro-api.coinmarketcap.com/v2/cryptocurrency/info
and here is the code that CoinMarketCap offer and it works (tested):
$url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest';
$parameters = [
'start' => '1',
'limit' => '5000',
'convert' => 'USD'
];
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: *********-****-****-****-***********'
];
$qs = http_build_query($parameters); // query string encode the parameters
$request = "{$url}?{$qs}"; // create the request URL
$curl = curl_init(); // Get cURL resource
//Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
print_r(json_decode($response)); // print json decoded response
curl_close($curl); // Close request
you can use the curl_multi_init to handle the multiple curl request asynchronously. you can read here more about multi curl
I have a PHP loop where i need to call another PHP file in the background to insert/update some information based on a variable send to it. I have tried to use CURL, but it does not seem to work.
I need it to call SQLupdate.php?symbol=$symbol - Is there another way of calling that PHP with the paramter in the background - and can it eventually be done Synchronously with a response back for each loop?
while(($row=mysqli_fetch_array($res)) and ($counter < $max))
{
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => "SQLinsert.php",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => array(
'symbol' => $symbol,
)
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
}
I'm going to weigh in down here in hopes of getting this one "away & done".
Although it isn't entirely clear from your post, it seems you're trying to call your PHP file via an HTTP(s) protocol.
In many configurations of PHP, you could do this and avoid some potential cURL overhead by using file_get_contents() instead:
while(($row=mysqli_fetch_array($res)) and ($counter < $max)) {
$postdata = http_build_query(
array(
'symbol' => $row['symbol']
)
);
$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/SQLinsert.php', false, $context);
$counter++; // you didn't mention this, but you don't want a everloop...
}
That's pretty much a textbook example copied from the manual, actually.
To use cURL instead, as you tried to do originally, and in truth it seems pretty clean with one call to curl_setopt() inside the loop:
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => "http://example.com/SQLinsert.php",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array($ch, $curlConfig);
while(($row=mysqli_fetch_array($res)) and ($counter < $max)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, array('symbol' => $row['symbol']));
$result = curl_exec($ch);
$counter++; //see above
}
// do this *after* the loop
curl_close($ch);
Now the actual and original problem may be that $symbol isn't initialized; at least, it isn't in the example you have provided. I've attempted to fix this by using $row['symbol'] in both my examples. If this isn't the name of the column in the database then you would obviously need to use the correct name.
Finally, be advised that it's almost always better to access a secondary resource via the fastest available mechanism; if "SQLinsert.php" is local to the calling script, using HTTP(s) is going to be terribly under-performant, and you should rewrite both pieces of the system to work from a local (e.g. 'disk-based') point-of-view (which has already been recommended by a plethora of commenters):
//SQLinsert.php
function myInsert($symbol) {
// you've not given us any DB schema information ...
global $db; //hack, *cough*
$sql = "insert into `myTable` (symbol) values('$symbol')";
$res = $this->db->query($sql);
if ($res) return true;
return false;
}
//script.php
require_once("SQLinsert.php");
while(($row=mysqli_fetch_array($res)) and ($counter < $max)) {
$ins = myInsert($row['symbol']);
if ($ins) { // let's only count *good* inserts, which is possible
// because we've written 'myInsert' to return a boolean
$counter++;
}
}
So my client needs a REST API using PHP that provides output as per the conditions on the URL parameters
So now there are three URL's basically which is currently needed and they are done.
so they are
localhost/newapi/client/<AuthKey> - for authorizing
localhost/newapi/client/<clientid>/categories/ - to get all the categories
localhost/newapi/client/<clientid>/categories/<categoryid> - to get all items in a category
used .htaccess for fancy URL
So now he requested that AuthKey need to be added to HTTP header not the URL. So the AuthKey must be passed as header and the rest as URL parameters
So my question is how this can be done. and how to retrieve the AuthKey from the request?
Any tutorials or comments regarding this question is welcome
you can tell the client when he request your api he add a header as below:
AuthKey: your-api-auth-key
or
Token: your-api-token
and then in your php code make
$headers = getallheaders();
$token = $headers['Token'] or ['AuthKey'];
then you check if the key in database and then process your code
Note:
your client can add Header with PHP cURL
curl_setopt($curl-handle, CURLOPT_HEADER, array(
'Token' => 'client-auth-token', //or
'AuthKey' => 'client-auth-token'
));
you can use this code to connect with rest in php
$url = 'localhost/newapi/client/';
$opts = array('http' =>
array(
'method' => 'POST',
'header' => "Content-Type: application/json\r\n"."Authorization: Basic ".<authkey>."\r\n",
'content' => $data,
'timeout' => 60
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context, -1, 40000);
return $result;
I'm creating a function to untilize NameCheap's API for registering domain names. The registration process worked out smoothly, now I'm looking to set the proper DNS Hosts.
When I create a pure POST request with something like POSTMAN this works fine and returns the expected XML response. However when I try to pass the data through PHP's CURL functions it breaks. I've narrowed the problem the the '#' symbol that needs to be passed to the DNS Host. If i put anything else there the request goes through. I've tried to url_encode the symbol but the API does not accept that.
Any suggestions?
public function setDNSHost($name, $server){
list($domain,$tld) = explode('.',$name,2);
$request = $this->request_URL;
$curl = curl_init();
$args['ApiUser'] = $this->API_User;
$args['ApiKey'] = $this->API_Key;
$args['UserName'] = $this->API_User;
$args['Command'] = 'namecheap.domains.dns.setHosts';
$args['ClientIP'] = $this->Client_IP;
$args['SLD'] = $domain;
$args['TLD'] = $tld;
$args['HostName1'] = utf8_encode('#');
$args['RecordType1'] = 'A';
$args['Address1'] = $server;
$args['HostName2'] = 'www';
$args['RecordType2'] = 'CNAME';
$args['Address2'] = $name;
$args['HostName3'] = '*';
$args['RecordType3'] = 'CNAME';
$args['Address3'] = $name;
curl_setopt_array($curl, array(
CURLOPT_URL => $request,
CURLOPT_USERAGENT => 'API',
// CURLOPT_FAILONERROR => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $args,
CURLOPT_TIMEOUT => 15
));
$response = curl_exec($curl);
curl_close($curl);
// $oXML = new SimpleXMLElement($response);
return $response;
}
Some caracters are not allowed to be in the string. To avoid such problems you could use http_build_query on your data before you use the curl function.
I'm trying to write a phing build task that will upload a asset to github here. Unfortunately this means I need to write it in a PHP file rather than in CLI (This is the release API for GitHub http://developer.github.com/v3/repos/releases/#upload-a-release-asset). Effectively this is building the CLI query here but in PHP Releasing a build artifact on github
So I've got a generic curl post function and am now customizing the hell out of it
/**
* Send a POST request using cURL
*
* #param UriInterface $url The url and request containing the post information
* #param array $options Extra options for cURL. This can also override the defaults
*
* #return string The response of the object
*/
private function curl_post(UriInterface $url, array $options = array())
{
$this->log('Attempting to upload file with URL ' . $url->toString(), Project::MSG_INFO);
$defaults = array(
CURLOPT_POST => 1,
CURLOPT_HEADER => 1,
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_TIMEOUT => 4,
CURLOPT_POSTFIELDS => $url->getQuery(),
);
// Initiate CURL
$ch = curl_init($url->toString());
// Create the full params
$params = array_merge($options, $defaults);
curl_setopt_array($ch, $params);
if(!$result = curl_exec($ch))
{
$this->log(curl_error($ch), Project::MSG_ERR);
return curl_error($ch);
}
curl_close($ch);
return $result;
}
For the sake of this post it doesn't really matter about UriInterface I've checked it's giving the correct result :)
Then I call this with:
$pageUrl = "https://uploads.github.com/repos/" . $this->owner . '/' . $this->repo . "/releases/" . $this->version . "/assets?name=";
$fullUrl = $pageUrl . $filename;
$headers = array(
'Content-Type: ' . $header,
'Accept: application/vnd.github.manifold-preview',
'Authorization: token TOKEN',
);
$options = array(
CURLOPT_SSL_VERIFYPEER => false, // Despite SSL is 100% supported to suppress the Error 60 currently thrown
CURLOPT_HTTPHEADER => $headers,
CURLOPT_BINARYTRANSFER => 1 // --data-binary
);
// Create the Uri object
$url = new Uri($fullUrl);
$url->setQuery(array('file' => "#$filename"));
$response = $this->curl_post($url, $options);
The first log outputs Attempting to upload file with URL https://uploads.github.com/repos/JoomJunk/Accordion/releases/3.0.2/assets?file=#mod_accordion-3.0.2.zip
Which looks like the correct URL from what I've read about the curl function and based on the API (please feel free to say if this isn't true!) however I'm hitting an error Failed connect to uploads.github.com:1; No error in the log of the curl_error() function.
Does anyone have any ideas/help they can give? If you want more information the full Phing task can be found at https://github.com/JoomJunk/Accordion/blob/development/build/phingext/GituploadTask.php
Your API doc says Send the raw binary content of the asset as the request body. So your POSTFIELDS should be:
CURLOPT_POSTFIELDS => file_get_contents("file.zip"),
You didn't mention what you have in your $header variable. It should be application/zip
// 'Content-Type: ' . $header,
'Content-Type: application/zip',