PHP LDAP queries bring back different results every time - php

I am using PHP4 (cannot upgrade) to query around 2,000 accounts but it's bringing back different results each time I refresh the page. If I shrink the number down to around 800 the results are still different each time, if I move down to around a dozen then I get the same results each time. Please can anyone advise?
<?php
set_time_limit(0);
$user = "CN=Account Name,OU=Users,OU=Helpdesk,OU=Group IT,DC=domain,DC=co,DC=uk";
$psw = "PasswordHere";
$csv = file('AD-Managers.csv');
foreach ($csv as $line){
$names = explode(",",$line);//explode by commas
$managerExists = "0";
$managerUPN = $names[4];
$managerSearch = "userprincipalname=".$managerUPN;
$search = "userprincipalname=".$userUPN;
$server = "jpr-ads-01s.jpress.co.uk";
$dn = "DC=domain,DC=co,DC=uk";
$ds=ldap_connect($server) or die("Could not connect to {$ldaphost}");
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION,3);
ldap_set_option($ds, LDAP_OPT_REFERRALS,0);
if($r=ldap_bind($ds, $user , $psw)){ //using bind as I will be updating accounts once I get it working
$sr=ldap_search($ds, $dn, $managerSearch);
$data = ldap_get_entries($ds, $sr);
//array shift as the first result in the array is NULL
$daa = array_shift($data);
foreach($data as $userData){
if (strpos($userData["dn"], 'Google Apps') == false){//make sure it's not a contact
$managersName = $userData["distinguishedname"][0];
$managerExists = "1";
break; //stop the loop if the user is found
}
}
}
ldap_close($ds);
if($managerExists == "1"){
echo "manager: ".$managerUPN;
echo "<br />";
}
else{
echo "manager not found: ".$managerUPN;
echo "<br />";
}
}
?>
sample of CSV:
1234567,John Smith,JOHN SMITH,john.smith#domain.co.uk,johns.manager#domain.co.uk,ABC1234,1,,,,,,,,,,,,
8901234,Jane Doe,JANE DOE,jane.doe#domain.co.uk,janes.manager#domain.co.uk,DEF7890,2,,,,,,,,,,,,
Sample result 1:
manager not found: johns.manager#domain.co.uk
manager not found: janes.manager#domain.co.uk
But I could refresh the page instantly and get:
manager: johns.manager#domain.co.uk
manager: janes.manager#domain.co.uk

Related

Is there a way to run PHP long loop code faster?

I have a code that runs a query on an external (slow) API and loops through a lot of variables and inserts data, sends email, ect'.
This is the main function as an example:
// MAIN: Cron Job Function
public function kas_alert() {
// 0. Deletes all the saved data from the `data` table 1 month+ ago.
// $this->kas_model->clean_old_rows();
// 1. Get 'prod' table
$data['table'] = $this->kas_model->prod_table();
// 2. Go through each row -
foreach ( $data['table'] as $row ) {
// 2.2. Gets all vars from the first query.
$last_row_query = $this->kas_model->get_last_row_of_tag($row->tag_id);
$last_row = $last_row_query[0];
$l_aaa_id = $last_row->prod_aaa_id;
$l_and_id = $last_row->prod_bbb_id;
$l_r_aaa = $last_row->dat_data1_aaa;
$l_r_and = $last_row->dat_data1_bbb;
$l_t_aaa = $last_row->dat_data2_aaa;
$l_t_and = $last_row->dat_data2_bbb;
$tagword = $last_row->tag_word;
$tag_id = $last_row->tag_id;
$country = $last_row->kay_country;
$email = $last_row->u_email;
$prod_name = $last_row->prod_name;
// For the Weekly report:
$prod_id = $last_row->prod_id;
$today = date('Y-m-d');
// 2.3. Run the tagword query again for today on each one of the tags and insert to DB.
if ( ($l_aaa_id != 0) || ( !empty($l_aaa_id) ) ) {
$aaa_data_today = $this->get_data1_aaa_by_id_and_kw($l_aaa_id, $tagword, $country);
} else{
$aaa_data_today['data1'] = 0;
$aaa_data_today['data2'] = 0;
$aaa_data_today['data3'] = 0;
}
if ( ($l_and_id != 0) || ( !empty($l_and_id) ) ) {
$bbb_data_today = $this->get_data1_bbb_by_id_and_kw($l_and_id, $tagword, $country);
} else {
$bbb_data_today['data1'] = 0;
$bbb_data_today['data2'] = 0;
$bbb_data_today['data3'] = 0;
}
// 2.4. Insert the new variables to the "data" table.
if ($this->kas_model->insert_new_tag_to_db( $tag_id, $aaa_data_today['data1'], $bbb_data_today['data1'], $aaa_data_today['data2'], $bbb_data_today['data2'], $aaa_data_today['data3'], $bbb_data_today['data3']) ){
}
// Kas Alert Outputs ($SEND is echoed in it's original function)
echo "<h1>prod Name: $prod_id</h1>";
echo "<h2>tag id: $tag_id</h2>";
var_dump($aaa_data_today);
echo "aaa old: ";
echo $l_r_aaa;
echo "<br> aaa new: ";
echo $aaa_data_today['data1'];
var_dump($bbb_data_today);
echo "<br> bbb old: ";
echo $l_r_and;
echo "<br> bbb new: ";
echo $bbb_data_today['data1'];
// 2.5. Check if there is a need to send something
$send = $this->check_if_send($l_aaa_id, $l_and_id, $l_r_aaa, $aaa_data_today['data1'], $l_r_and, $bbb_data_today['data1']);
// 2.6. If there is a trigger, send the email!
if ($send) {
$this->send_mail($l_aaa_id, $l_and_id, $aaa_data_today['data1'], $bbb_data_today['data1'], $l_r_aaa, $l_r_and, $tagword, $email, $prod_name);
}
}
}
This CodeIgniter controller is runs every day and I get this running (Cronjob) for too long using almost nothing from the CPU and RAM (RAM is at 400M/4.25G and CPU at ONLY 0.7%-1.3%).
I wonder if there's an option to split all foreach loops to smaller threads (and I'm not sure if forking will do here) and run all the foreach loops in parallel but in a way that it wont get my server crashing.
I'm no DevOps and really interested learning - What should I do in this case?

php code of troubling getting multiple value

I have codes that should be getting value from mysql database, I can get only one value but I have while loop so it can get value and output data separated with comma. But I only get one value and cannot get multiple value. the result should be like this, // End main PHP block. Data looks like this: [ [123456789, 20.9],[1234654321, 22.1] ] here is the code:
<?php
// connect to MySQL
mysql_connect('localhost','','') or die("Can't connect that way!");
#mysql_select_db('temperature1') or die("Unable to select a database called 'temperature'");
if(ISSET($_GET['t']) && (is_numeric($_GET['t'])) ){
// message from the Arduino
$temp = $_GET['t'];
$qry = "INSERT INTO tempArray(timing,temp) VALUES(".time().",'$temp')";
echo $qry;
mysql_query($qry);
mysql_close();
exit('200');
}
// no temp reading has been passed, lets show the chart.
$daysec = 60*60*24; //86,400
$daynow = time();
if(!$_GET['d'] || !is_numeric($_GET['d'])){
$dayoffset = 1;
} else {
$dayoffset = $_GET['d'];
}
$dlimit = $daynow-($daysec*$dayoffset);
$qryd = "SELECT id, timing, temp FROM tempArray WHERE timing>='$dlimit' ORDER BY id ASC LIMIT 1008";
// 1008 is a weeks worth of data,
// assuming 10 min intervals
$r = mysql_query($qryd);
$count = mysql_num_rows($r);
$i=0;
$r = mysql_query($qryd);
$count = mysql_num_rows($r);
while($row=mysql_fetch_array($r, MYSQL_ASSOC)) {
$tid=$row['id'];
$dt = ($row['timing']+36000)*1000;
$te = $row['temp'];
if($te>$maxtemp) $maxtemp=$te; // so the graph doesnt run along the top
if($te<$mintemp) $mintemp=$te; // or bottom of the axis
$return="[$dt, $te]";
echo $return; //here I get all values [1385435831000, 21][1385435862000, 23][1385435892000, 22][1385435923000, 25][1385435923000, 22]
$i++;
if($i<$count) $return= ","; echo $return; // if there is more data, add a ',' however, it return me ,,,[1385435923000, 22]
$latest = "$dt|$te"; // this will get filled up with each one
}
mysql_close();
// convert $latest to actual date - easier to do it here than in javascript (which I loathe)
$latest = explode('|',$latest);
$latest[0] = date('g:ia, j.m.Y',(($latest[0])/1000)-36000);
?>
You're just assigning $return to the values from the last row your while loop grabbed instead of concatenating it. Try this
$return = "[";
while($row=mysql_fetch_array($r, MYSQL_ASSOC)) {
$tid=$row['id'];
$dt = ($row['timing']+36000)*1000;
$te = $row['temp'];
if($te>$maxtemp) $maxtemp=$te; // so the graph doesnt run along the top
if($te<$mintemp) $mintemp=$te; // or bottom of the axis
$return.="[$dt, $te]";
$i++;
if($i<$count) $return .= ", ";// if there is more data, add a ','
$latest = "$dt|$te"; // this will get filled up with each one
}
$return .= "]";

php to pick up the specific query information from array

<?php
echo "Connecting Database <br>";
$server = 'UKVDEMO03'; //Here you're server
$database = 'smtpFetch';//here the database you want to connect to
$user = 'shoaibsg';//here te user WHO HAS THE RIGHT PERMISSIONS AT THE DATABASE
$pass = '1111111';//and here the user's password
$dsn = "Driver={SQL Server};Server=$server;Database=$database;";
$connect = odbc_connect($dsn, $user, $pass);
echo "Successfully connected....";
//getting subscribe user detail
$subQuery="select emailAddress, dataSet from userDetail";
$subRes=odbc_exec($connect, $subQuery);
$ix=odbc_num_rows($subRes);
//$newArray[]=$newArray array;
$row[]=array();
$newArrayD[]=$row;
$i=0;
$xc=0;
if($ix>0)
{
while($row=odbc_fetch_array($subRes))
{
$newArrayD[$row['emailAddress']] =$row['emailAddress'];
$newArrayD[$row['dataSet']] =$row['dataSet'];
}
}
foreach($newArrayD as $arrayD)
{ $i++;
echo "<br> -" . $arrayD;
echo "-i increment -" . $i;
}
?>
The above displays the below output
-Array
-shoaib#xyz.com
-SSCRUS_CS2002
-nick#xyz.com
-SSCE_CS2002
Now the problem: if I need to display only the emailAddress only in foreach loop it only displays the first character (I used below in foreach loop)
echo "<br> -" . $arrayD['emailAddress'];
such as above output displays as
-
-s
-S
-n
-S
I am baffled, please please help
Your code to generate the array is off. Try this:
while ($row=odbc_fetch_array($subRes))
{
$newArrayD[$row['dataSet']] = $row['emailAddress'];
// This would generate for example $newArrayD['SSCRUS_CS2002'] = 'shoaib#xyz.com'
}
Then, to display them, iterate through the array:
foreach ($newArrayD as $dataset=>$emailaddress)
{
echo "- $emailaddress<br />";
}
EDIT - To save both in seperate arrays:
$newArrayD = array('dataset' => array(), 'emails' => array());
while ($row=odbc_fetch_array($subRes))
{
$newArrayD['dataset'][] = $row['dataSet'];
$newArrayD['emails'][] = $row['emailAddress'];
}
To iterate through the emails:
foreach ($newArrayD['emails'] as $emailaddress)
{
// Code you wish to execute
}
To iterate through the datasets:
foreach ($newArrayD['dataset'] as $dataset)
{
// Code you wish to execute
}
Using this method, the $newArrayD['dataset'][0] will be the dataset linked to $newArrayD['emails'][0] etc.

Exporting Invoices from Magento

I have been trying to export all of our invoices in a specific format for importing into Sage accounting. I have been unable to export via Dataflow as I need to export the customer ID (which strangely is unavailable) and also a couple of static fields to denote tax codes etc…
This has left me with the option of using the API to export the data and write it to a CSV. I have taken an example script I found (sorry can’t remember where in order to credit it...) and made some amendments and have come up with the following:
<?php
$website = 'www.example.com';
$api_login = 'user';
$api_key ='password';
function magento_soap_array($website,$api_login,$api_key,$list_type,$extra_info){
$proxy = new SoapClient('http://'.$website.'/api/soap/?wsdl');
$sessionId = $proxy->login($api_login, $api_key);
$results = $proxy->call($sessionId,$list_type,1);
if($list_type == 'order_invoice.list'){
/*** INVOICES CSV EXPORT START ***/
$filename = "invoices.csv";
$data = "Type,Account Reference,Nominal A/C Ref,Date,Invoice No,Net Amount,Tax Code,Tax Amount\n";
foreach($results as $invoice){
foreach($invoice as $entry => $value){
if ($entry == "order_id"){
$orders = $proxy->call($sessionId,'sales_order.list',$value);
}
}
$type = "SI";
$nominal = "4600";
$format = 'Y-m-d H:i:s';
$date = DateTime::createFromFormat($format, $invoice['created_at']);
$invoicedOn = $date->format('d/m/Y');
$invoiceNo = $invoice['increment_id'];
$subtotal = $invoice['base_subtotal'];
$shipping = $invoice['base_shipping_amount'];
$net = $subtotal+$shipping;
$taxCode = "T1";
$taxAmount = $invoice['tax_amount'];
$orderNumber = $invoice['order_id'];
foreach($orders as $order){
if ($order['order_id'] == $orderNumber){
$accRef = $order['customer_id'];
}
}
$data .= "$type,$accRef,$nominal,$invoicedOn,$invoiceNo,$net,$taxCode,$taxAmount\n";
}
file_put_contents($_SERVER['DOCUMENT_ROOT']."/var/export/" . $filename, "$header\n$data");
/*** INVOICES CSV EXPORT END ***/
}else{
echo "nothing to see here";
}/*** GENERIC PAGES END ***/
}/*** END function magento_soap_array ***/
if($_GET['p']=="1")
{
magento_soap_array($website,$api_login,$api_key,'customer.list','Customer List');
}
else if($_GET['p']=="2")
{
magento_soap_array($website,$api_login,$api_key,'order_creditmemo.list','Credit Note List');
}
else if($_GET['p']=="3")
{
magento_soap_array($website,$api_login,$api_key,'sales_order.list','Orders List');
}
else if($_GET['p']=="4")
{
magento_soap_array($website,$api_login,$api_key,'order_invoice.list','Invoice List');
}
?>
This seems to be working fine, however it is VERY slow and I can’t help but think there must be a better, more efficient way of doing it…
Has anybody got any ideas?
Thanks
Marc
i think on put break; would be okey. because only one key with order_id, no need to looping after found order_id key.
if ($entry == "order_id"){
$orders = $proxy->call($sessionId,'sales_order.list',$value);
break;
}
and you can gather all call(s) and call it with multicall as example:
$client = new SoapClient('http://magentohost/soap/api/?wsdl');
// If somestuff requires api authentification,
// then get a session token
$session = $client->login('apiUser', 'apiKey');
$result = $client->call($session, 'somestuff.method');
$result = $client->call($session, 'somestuff.method', 'arg1');
$result = $client->call($session, 'somestuff.method', array('arg1', 'arg2', 'arg3'));
$result = $client->multiCall($session, array(
array('somestuff.method'),
array('somestuff.method', 'arg1'),
array('somestuff.method', array('arg1', 'arg2'))
));
// If you don't need the session anymore
$client->endSession($session);
source

Looping through pages from API

I'm trying to get all the gameids for a particular player. The API I am working with only returns 24 games per page. I just cant figure out how to loop though the pages.
When a player no longer has anymore pages $mPages will be equal to false.
The problem is adding 1 to $iPages so it can get the next page..
My current script:
<?php
//incude sql database connection
include_once('sql.php');
//include api key
include_once('api.php');
//gamertag
$gamertag = "jam1efoster";
//variant- Valid values are "Campaign", "Firefight", "Competitive", "Arena", "Invasion", "Custom", "Unknown". "Unknown" returns all games.
$variant = "Unknown";
//page number 0 = most recent
$iPage = 0;
while(!$endPages == "stop"){
$iPage = $iPage++;
$GetGameHistory = "http://www.bungie.net/api/reach/reachapijson.svc/player/gamehistory/".$apiKey."/".rawurlencode($gamertag)."/".$variant."/".$iPage;
$output = file_get_contents($GetGameHistory);
$obj = json_decode($output);
echo $output;
$mPages = $obj->HasMorePages;
if($mPages == false){$endPages = "stop";}
foreach($obj->RecentGames as $recentgames) {
$gameid = $recentgames->GameId;
echo $gameid."<br/>";
}
}
?>
Perhaps a while loop?
while (!endOfPages) {
getMoreGames();
}

Categories