Codeigniter phpexcel validation array before import - php

i want to import excel as json data in Codeigniter with validation for each row.
excel column
|A |B |C
|demo|DM1|11231
|demo|DM2|87128
...
my code for get array from excel
//start loop excel from 2nd row. Row 1 is title row
for ($j=2; $j < $lastRow; $j++ ){
$myArray[] = array(
'site_id' => $objWorksheet->getCell('B'.$j)->getValue(),
'site_name' => $objWorksheet->getCell('A'.$j)->getValue(),
'id_site_doc'=> $objWorksheet->getCell('C'.$j)->getValue()
}
//validate the array
$this->form_validation->set_data($myArray);
$this->form_validation->reset_validation();
foreach ($myArray as $key => $value) {
$columnB = $myArray[$key]['site_id'];
$columnA = $myArray[$key]['site_name'];
$columnC = $myArray[$key]['id_site_doc'];
}
if (empty($columnB )){
$this->form_validation->set_rules('mr_submit_target', 'site_id on row ' . $j, 'required');
}
else if (empty($columnA )){
$this->form_validation->set_rules('short_desc', 'site_name on row ' . $j, 'required');
}
else if (empty($columnC )) {
$this->form_validation->set_rules('cd_id', 'id_site_doc on row ' . $j, 'required');
}
if ($this->form_validation->run() == FALSE){
$errorArray[$j]=$this->form_validation->error_array();
print_r($errorArray[$j]);
}else{
//post to endpoint
$data_to_post = json_encode($myArray);
$curl = curl_init('http://myendpoint/implementation_bom_op');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_to_post))
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_to_post);
// Send the request
$result = curl_exec($curl);
echo $result;
}
}
my expectation
the data will be post only if have full validation, when there are blank cell in one of each cell it will throw error. is that possible? or it should be on endpoint side?

//start loop excel from 2nd row. Row 1 is title row
for ($j=2; $j < $lastRow; $j++ ){
$columnB = $objWorksheet->getCell('B'.$j)->getValue();
$columnA = $objWorksheet->getCell('A'.$j)->getValue();
$columnC = $objWorksheet->getCell('C'.$j)->getValue();
//validate the array
$error = 0;
if($columnB == ""){
$errorArray[$j][] = 'your-error-here';
$error +=1;
}
if($columnA == ""){
$errorArray[$j][] = 'your-error-here';
$error +=1;
}
if($columnC == ""){
$errorArray[$j][] = 'your-error-here';
$error +=1;
}
if($error != 0){
continue; //do something with the error
}else{
$myArray['site_id'] = $columnB;
$myArray['site_name'] = $columnA;
$myArray['id_site_doc'] = $columnC;
}
}
//post to endpoint
$data_to_post = json_encode($myArray);
$curl = curl_init('http://myendpoint/implementation_bom_op');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_to_post))
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_to_post);
// Send the request
$result = curl_exec($curl);
echo $result;
This should work for you.

Related

running curl in a for loop blocks access to website

I have the following code which basically runs a bunch of curl request in a for loop
This is a background system job.. however when this code is running.. i can't access the website, website is just loading until this task/function is finished
public function endcount() {
$order_list = $this->order_model->get_rows([
'where' => [
"status IN ('Processing', 'In Progress') AND service_id = 1"
],
'order_by' => 'quantity ASC',
'limit' => '200'
]);
foreach ($order_list as $key => $value) {
$start_count = $value['start_count'];
//service id = 1 is for followers
if ($value['service_id'] == '1' || $value['service_id'] == '3' || $value['service_id'] == '5') {
$end_count = 0;
try {
$username = $value['target'];
$proxy = '139.99.54.49:10163';
$proxyauth = 'username:password';
$url = 'https://www.instagram.com/'. $username .'/?__a=1&__d=dis';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PROXY, $proxy); // PROXY details with port
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth); // Use if proxy have username and password
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json') );
$data = curl_exec($ch);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
var_dump($error_msg);
}
$json_data = json_decode($data, true);
if ($json_data && array_key_exists('graphql', $json_data)) {
$end_count = $json_data['graphql']['user']['edge_followed_by']['count'];
} else {
var_dump($username . ' data ga bisa');
$end_count = 0;
}
curl_close($ch);
} catch(Exception $e) {
var_dump($e->getMessage());
$end_count = 0;
}
if ($end_count == -666) {
$end_count = $start_count + 5;
}
$total_followers = $start_count + $value['quantity'];
$remains = $total_followers - $end_count;
if ($remains <= 10) {
$status = 'Success';
} else {
$status = 'Partial';
}
var_dump('end count of ' . $value['target'] . ' ' . $end_count . ' WITH REMAINS: ' . $remains);
if ($status == 'Success') {
$update_order = [
'remains' => $remains,
'status' => $status,
'updated_at' => date('Y-m-d H:i:s'),
];
$update_order = $this->order_model->update($update_order, ['id' => $value['id']]);
if ($update_order == true) {
print('ID '.$value['id'].' => ['.$status.'] - [FINAL COUNT : '.$end_count.'] - [REMAINS : '.$remains.'] - [TARGET COUNT : '.$total_followers.']<br>');
} else {
print('Error..');
}
}
//var_dump($value['target']);
} else if ($value['service_id'] == '2') {
//service id = 2 is for likers
}
}
}
is there any way i can optimize this code so it is not blocking access to the site while running ?
try adding sleep(5); funtion to your code so server isn't overloaded with requests..
your code should look something like this :
foreach ($order_list as $key => $value) {
sleep(5);
$start_count = $value['start_count'];

get array out of loop

I need get array out of loop (I need used array, and not, last value)
loop
for ($x = 1; $x < $numero; $x++) {
$frase = $frase_script[$x];
$distrito1 = (explode(',',$frase));
echo $distrito1[0]}
Variable out
$ultimo_nome = $distrito1[0];
I need used array, and not, last value
echo "<br> I need print array, and not, last value".$ultimo_nome;
error: prints the last value and not an array.
Example
all code
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.geonames.org/searchJSON?username=country=pt&lang=pt&q=lisbon&fcode=ADM2&adminCode1=14&style=SHORT&maxRows=1000");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Accept: application/json"
));
$response = curl_exec($ch);
curl_close($ch);
$frase_script = (explode(',',$response));
$frase = $frase_script[0];
$palavra = (explode(':',$frase));
$numero = $palavra[1];
$frase_script = (explode('"name":',$response));
echo '[';
for ($x = 1; $x < $numero; $x++) {
$frase = $frase_script[$x];
$distrito1 = (explode(',',$frase));
echo $distrito1[0]; }
$ultimo_nome = $distrito1[0];
echo $ultimo_nome;
echo ']';
echo "<br> I need print array, and not, last value".$ultimo_nome;
if you need print all the elements but not the lasy you could use
$distrito1 = (explode(',',$frase));
$numElem = count($distrito1);
foreach ($distrito1 as $key => $value){
if ( $key < $numElem-1 ){
echo $value;
} else {
break;
}
}

504 gateway timeout with no output - php

I wrote a script that communicates with a popular game, called kahoot. It logs in and answer's each question, and then echo's when it is finished. Here is it working on the command line. However, when I add this functionality to my website, when I run it it gives me a 504 gateway timeout, even though before the timeout it should have produced some output and echoed it to the page.
Here is the website code:
Full execution code:
<html>
<head>
<title>Kahoot bot</title>
</head>
<body>
<?php
$username = 'kahootbot28#gmail.com';
$password = 'botkahoot28';
$loginUrl = 'https://create.kahoot.it/rest/authenticate';
$kahootId = $_GET['quizid'];
$type = $_GET['what'];
if ($type == "bot") {
$call = "~/www/reteps.tk/go/kahoot-auto " . $_GET['gamepin'] . " " . $_GET['username'] . " ";
echo($call);
}
$pageUrl = 'https://create.kahoot.it/rest/kahoots/' . $kahootId;
$loginheader = array();
$loginheader[] = 'content-type: application/json';
$loginpost = new stdClass();
$loginpost->username = $username;
$loginpost->password = $password;
$loginpost->grant_type = "password";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $loginUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($loginpost));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$loginheader);
$store = curl_exec($ch);
curl_close($ch);
$token = json_decode($store,true)["access_token"];
//get questions
$quizheader = array();
$quizheader[] = 'authorization: ' . $token;
$options = array(
'http' => array(
'method' => 'GET',
'header' => "Authorization: ".$token."\r\n"
)
);
$pairs = array(
0 => "red",
1 => "blue",
2 => "yellow",
3 => "green",
);
$context = stream_context_create($options);
$raw_result = file_get_contents($pageUrl, false, $context);
$result = json_decode($raw_result,true)["questions"];
echo("<a href='kahoot_bot'>back</a><br>");
foreach($result as $value) {
if ($type == "text") {
echo($value['question']." ");
}
$choices = $value['choices'];
for($i=0;$i<count($choices);$i++) {
if ($choices[$i]['correct'] == true) {
if ($type == "text") {
echo($choices[$i]['answer']."<br>");
} elseif ($type == "bot") {
$call .= $i;
} else {
echo($pairs[$i].", ");
}
break 1;
}
}
}
if ($type == "bot") {
$old_result = "";
$handle = popen($call . " 2>&1", "r");
$result = fread($handle, 2096);
echo($result);
while ((strpos($result, "end") !== false) != true) {
$result = fread($handle, 2096);
sleep(1);
if ($result != $old_result) {
echo($result);
$old_result = $result;
}
}
pclose($handle);
}
?>
</body>
</html>

How to call this curl API request to get the highest 'likelihood' json field name?

I'm trying to use this API from this site fullcontact for normalizing a number of possible names into 'likelihood values' for name extraction.
Tried the following code but it can't run Undefined offset: 2 error: $index_name = $possible_names[$n];. Moreover, I'm was stuck with the logic of extracting the name. Can someone help? Thanks
$possible_names = array("Jimmy Frank", "Wall Street"); // In this case Jimmy Frank should be the output person name
if (count($possible_names) > 1)
{
for ($n = 0; $n <= count($possible_names); $n++)
{
$index_name = $possible_names[$n];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.fullcontact.com/v2/name/normalizer.json?q=$index_name");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$headers = array();
$headers[] = "X-Fullcontact-Apikey: APIKEY";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$namenormalizer_result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
else
{
$namejson_result = json_decode($namenormalizer_result, true);
$namejson_array[] = $namejson_result['likelihood'];
}
curl_close ($ch);
}
}
$possible_names is an array of size 2. Arrays are indexed from 0 so you need to remove the last index 2 which doesn't exist :
for ($n = 0; $n <= count($possible_names) - 1; $n++) {
}
or use strict condition :
for ($n = 0; $n < count($possible_names); $n++) {
}
For the extraction, you can use $namejson_result->nameDetails->fullName to extract fullName and $namejson_result->likelihood for likelihood :
$namejson_result = json_decode($result);
echo "likelihood for $index_name on " .
$namejson_result->nameDetails->fullName . " : " .
$namejson_result->likelihood . "\n";

Wrong distance in map

ok, i think i just fucked up everything because of my brain failure.
I followed Google's example of "phpsqlsearch_v3":
imported the sql file
change the query from showing miles to kilometers
testing by using this:
phpsqlsearch_genxml.php?lat=37.315903&lng=-121.977928&radius=40
everything works as charm...
going into website to get latlong, adding and changing some data in db
now, I'm changing the phpsqlsearch_genxml.php to....
phpsqlsearch_genxml.php?lat=59.627847&lng=17.838589&radius=40
...nothing... however, if i change radius to 8000 it will work but the distance for places around input will be like 5665.231121242624km but if i flip the input because I'm on the right side of the earth blink blink to
phpsqlsearch_genxml.php?lat=17.838589&lng=59.627847&radius=100
it will give me a more accurate result, however... the result should closer and around 1-2km...
suggestion what to do now?
function getAddress($lat, $lng) {
$use_curl = false;
if ($use_curl) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat . "," . $lng . "&sensor=true");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array (
"Content-type: application/binary"
));
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
if (curl_errno($ch))
return -1;
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$str = substr($response, $header_size);
curl_close($ch);
$data = json_decode($str, true);
if (isset($data["results"]) && is_array($data["results"])) {
$street = $data["results"][0]["formatted_address"];
$ac = $data["results"][0]["address_components"];
$len = count($ac);
$i = 0;
$city = "";
while ($i<$len) {
if (in_array("locality", $ac[$i]["types"])) $city = $ac[$i]["long_name"];
else if (in_array("country", $ac[$i]["types"])) $city .= ",".$ac[$i]["short_name"];
$i++;
}
$meta = array(
"status"=>200,
"message"=>"Succeed."
);
return array("meta"=>$meta, "response"=>array("address"=>$street, "city"=>$city));
} else {
$meta = array(
"status"=>406,
"message"=>"Address is not known."
);
return array("meta", $meta);
}
} else {
$str = #file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat . "," . $lng . "&sensor=true");
$data = json_decode($str, true);
if (isset($data["results"]) && is_array($data["results"])) {
$street = $data["results"][0]["formatted_address"];
$ac = $data["results"][0]["address_components"];
$len = count($ac);
$i = 0;
$city = "";
while ($i<$len) {
if (in_array("locality", $ac[$i]["types"])) $city = $ac[$i]["long_name"];
else if (in_array("country", $ac[$i]["types"])) $city .= ",".$ac[$i]["short_name"];
$i++;
}
$meta = array(
"status"=>200,
"message"=>"Succeed."
);
return array("meta"=>$meta, "response"=>array("address"=>$street, "city"=>$city));
} else {
$meta = array(
"status"=>406,
"message"=>"Address is not known."
);
return array("meta"=>$meta);
}
}
}

Categories