Php Codeigniter - improve execution time - php

Actually, i have this script
public function getsbstock()
{
if ($_SERVER['REMOTE_ADDR'] !== $this->localhost) {echo $_SERVER['REMOTE_ADDR'];}
else{
$datetimenow = (new DateTime())->format('Y-m-d');
$url = get_integration_url('smartbill');
$this->db->select('user_id');
$this->db->where('sb_get_stock',1);
$this->db->where('is_smartbill',1);
$this->db->where('is_active',1);
$resArr = $this->db->get('ci_users')->result_array();
foreach ($resArr as $row){
$user_id = $row['user_id'];
$auth = base64_encode(get_sb_email($user_id) . ":" . get_sb_token($user_id));
$cif = get_sb_cif($user_id);
$sbwh = preg_replace('/\s+/', '+', get_sb_warehouse($user_id));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => ''. $url .'stocks?cif=' . $cif . '&date=' . $datetimenow . '&warehouseName=' . $sbwh . '',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Authorization: Basic ' . $auth . ' '
),
));
$content = curl_exec($curl);
$prodArr = json_decode($content, true);
foreach($prodArr['list'][0]['products'] as $key => $val){
$productCode = $val['productCode'];
$quantity = $val['quantity'];
$updatedata = array('quantity' => $quantity,);
$this->db->where('sbCode',$productCode);
$this->db->where('user_id', $user_id);
$this->db->update('ci_products', $updatedata);
}
}
}
}
All works fine here, and to make a brifley description, i get from db every users which is active, then for each i m calling an api (different apikeys) and grab data. Api responded me with 1k prod and 2-3 prod for other (just tests), then i update quantity in my database (ci_products) where i have around 15k rows. I see that execution is taking a bit long and i'm not sure if it's normal and if this can be improved somehow :-? it's taking around 20-30 seconds to perform this function.

Related

Loop through and assign variables for each value in array, then run function for each variable

What I'm trying to accomplish is taking a simple array ($territories)
$territories = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
And assign each value as a variable, so that it can be used inside another function, and needs to run for each value in the first array.
The function being called is getting its data from another api, so that variable is required to correctly call the function.
Most of what I've done so far is working, except it's only running the function once.
The function needs to run all 18 times, and return 18 separate arrays.
The complete end goal here is to check the user's current zipcode against each array, and then to perform a function if there's a match to each array.
Below is what I have so far. I've left out API credentials for confidentiality.
//get territories in Nitro API
function get_territories(){
$url = 'https://nitro.powerhrg.com/admin/api/v1/territories.json';
$token = '';
// Nitro API request via cURL
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Authorization: '. $token.'',
),
));
// store response as string and return it
$result = json_decode(curl_exec($curl), true);
curl_close($curl);
return $result;
}
//get zipcodes from territory ID in Nitro API
function get_zipcodes($territory_id){
$url = 'https://nitro.powerhrg.com/directory/api/v1/zip_codes.json?territory_id='.$territory_id;
$token = '';
$body = array(
'id' => $territory_id,
);
// Nitro API request via cURL
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Authorization: '. $token.'',
),
CURLOPT_POSTFIELDS => json_encode($body)
));
// store response as string and return it
$result = json_decode(curl_exec($curl), true);
curl_close($curl);
return $result;
}
// show JSON array of all territory data by id (testing)
function display_zipcodes_raw(){
// get list of territory IDs
$territories = get_territories();
$values = [];
foreach ($territories as &$territory) {
$values[] = $territory['id'];
$id = 0;
foreach ($values as $key=>$value) {
$id = $value;
}
$zipcodes = get_zipcodes($id);
$results = [];
foreach ($zipcodes as &$zip) {
$results[] = $zip['zip_code'];
}
return 'zipcode results: '.json_encode($results).'<br>';
}
}
add_shortcode( 'display_zipcodes_raw', 'display_zipcodes_raw' );
Try the below
function display_zipcodes_raw()
{
$zipcodes = [];
foreach (get_territories() as $territory) {
$zipcodes[$territory['id']] = array_column(get_zipcodes($territory['id']), 'zip_code');
}
return json_encode($zipcodes);
}
As a recommendation, global functions that reference other global functions that serve a single responsibility like you have here should probably be collected together and placed into a class, object-orientated programming is truly a beautiful thing. Good luck on your adventure!
You have l unnecessary variables and loops, it's much more simple:
// show JSON array of all territory data by id (testing)
function display_zipcodes_raw(){
// get list of territory IDs
$territories = get_territories();
$results = [];
foreach ($territories as $territory) {
$zipcodes = get_zipcodes($territory['id']);
foreach ($zipcodes as $zip) {
$results[] = $zip['zip_code'];
}
}
return 'zipcode results: '.json_encode($results).'<br>';
}

How can I pass a bunch of form in only one curl

So what im doing is:
foreach ($textAr as $title) {
$title = str_replace("\r", '', $title);
echo nl2br($title . "\n");
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://a...',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => '{
"title":"' . $title . '",
"category_id":"' . $categorytxt . '",
"price":' . $pricetxt . ',...
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Authorization: Bearer ' . $_SESSION['access_token'] . ''
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
}
So for each title I put into a textarea it is going to do this curl request, but the problem is sometimes I have like 3000 title, so if i just foreach it cut my connection. Do u guys know another way so I can pass all curls just once, instead of one by one ?

Get users email from twitter for auth (https://api.twitter.com/1.1/account/verify_credentials.json)




I followed the tutorial from twitter (documentation), and got stuck at the last stage when I need to get user data with his mail (to make user authorization).



When I make a request without parameters, I get user data such as name, user ID, etc., I need to get the user's mail, but when I add the parameter "? Include_email = true" I get the error 32 "We cannot authenticate you".



I do not understand where I made a mistake (as I understand in the signature)



Thanks for attention


(Sorry for my English, this is not my native language)
$oauthParams = [
"oauth_consumer_key" => "...",
"oauth_token" => $requestOauthToken,
"oauth_signature_method" => "HMAC-SHA1",
"oauth_timestamp" => time(),
"oauth_nonce" => md5(uniqid()),
"oauth_version" => "1.0",
];
$baseURI = "https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true";
$baseString = $this->buildBaseStringGET($baseURI, $oauthParams);
$consumerSecret = '...';
$compositeKey = $this->getCompositeKey($consumerSecret, $requestOauthTokenSecret);
$oauthParams['oauth_signature'] = base64_encode(hash_hmac('sha1', $baseString, $compositeKey, true));
$header = $this->buildAuthorizationHeader($oauthParams);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $baseURI,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
$header,
),
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response, true)
private function buildBaseStringGET($baseURI, $oauthParams)
{
$baseStringParts = [];
ksort($oauthParams);
foreach ($oauthParams as $key => $value) {
$baseStringParts[] = "$key=" . urlencode($value);
}
return 'GET&' . urlencode($baseURI) . '&' . urlencode(implode('&', $baseStringParts));
}
private function buildAuthorizationHeader($oauthParams)
{
$authHeader = 'Authorization: OAuth ';
$values = [];
foreach ($oauthParams as $key => $value) {
$values[] = "$key=\"" . urlencode($value) . "\"";
}
$authHeader .= implode(',', $values);
return $authHeader;
}
If the user does not have an email address on their account, or if the email address is not verified, null will be returned.
https://developer.twitter.com/en/docs/twitter-api/v1/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials

laravel , How to return view html page from curl POST method

I'm using curl for post some variables from controller, the result is a page with HTML data which is exactly I want, the issue is how to show this html page after run the curl function
the result like this
public function OnlineBanking($amount,$response_url)
{
$prm_date = gmdate("Y-m-d H:i:s",time()+(8*60*60));
$prm_amount = $amount;
$prm_mrhref = "R".time(); //"Order-KAS-".time();
$prm_mrhid = *****; // test MID
$prm_mrhsKey = "*****;";// test secret key
$prm_payment_mrh_hash = sha1($prm_mrhsKey . $prm_mrhid . $prm_mrhref . str_replace('.', '', $prm_amount));
$prm_returnURL = $response_url; // return URL once tranx process completes.
$prm_POSTURL = "https://www.example.com/gateway.php"; //Payment gateway connecting page
$postData['ord_date'] = $prm_date;
$postData['ord_returnURL'] = $prm_returnURL;
$postData['ord_totalamt'] = $prm_amount;
$postData['ord_mercref'] = $prm_mrhref;
$postData['ord_mercID'] = $prm_mrhid;
$postData['merchant_hashvalue'] = $prm_payment_mrh_hash;
$res = self::curlRequest($prm_POSTURL,$postData);
return $res;
}
public static function curlRequest($url, $data = null)
{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_POSTFIELDS => http_build_query($data),
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST"
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
return $response;
}
you need to set CURLOPT_RETURNTRANSFER => true
you can read about it here
you would then simply need to echo your output
similar question
managing curl output in php

Twitter cookies expiring - PHP CURL

have this code that saves Twitter cookies so I can use it later, that is, I have a login system.
$obj = new stdClass;
$obj->cookies = '';
$obj->location = '';
$request = curl_init();
curl_setopt_array($request, [
CURLOPT_URL => 'https://twitter.com/',
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HEADER => true,
CURLOPT_COOKIEJAR => getcwd() . '/cookies/' . $username . '.txt',
CURLOPT_HEADERFUNCTION => function($curl, $header) use (&$obj) {
if (stripos($header, 'Set-Cookie:') === 0) {
if (preg_match('/^Set-Cookie: \s*([^=]*)=([^;]*)/mi', $header, $matches)) {
$obj->cookies .= $matches[1] . '=' . $matches[2] . '; ';
$obj->{$matches[1]} = $matches[2];
}
}
return strlen($header);
}
]
);
$response = curl_exec($request);
The problem is that when you purchase these cookies later, they do not work, they expire, how do I renew or do not expire?

Categories