What causes this delay in PHP? - php

I have a question about a PHP script that I wrote to connect to a collect statistics from IRC servers, as a test as I am new to PHP and still learning.
Here is the script:
<?php
set_time_limit(0);
$servers = array(
"irc.icq.com",
"irc.quakenet.org"
);
function get_statistics ($server, $port) {
$nick = 'IRCDir' . rand(1000, 9999);
$irc = fsockopen($server, $port);
fputs($irc,"USER $nick 0 * :$nick\n");
fputs($irc,"NICK $nick\n");
while ($data = fgets($irc, 128)) {
$ex = explode(' ', $data);
if (isset($ex[0]) && $ex[0] == "PING") {
fputs($irc, "PONG ".$ex[1]."\n");
}
if (count($ex) > 0) {
if (isset($ex[1]) && $ex[1] == "001") {
$network = $ex[6];
echo date('h:i:s') . " network: " . $server;
echo "\n";
}
if (isset($ex[1]) && $ex[1] == "002") {
$server = str_replace(',', '', $ex[6]);
echo date('h:i:s') . " server: " . $server;
echo "\n";
}
if (isset($ex[1]) && $ex[1] == "251") {
$users = $ex[5] + $ex[8];
$servers = $ex[11];
echo date('h:i:s') . " users: " . $users;
echo "\n";
echo date('h:i:s') . " servers: " . $servers;
echo "\n";
}
if (isset($ex[1]) && $ex[1] == "252") {
$ircops = $ex[3];
echo date('h:i:s') . " ircops: " . $ircops;
echo "\n";
}
if (isset($ex[1]) && $ex[1] == "254") {
$channels = $ex[3];
echo date('h:i:s') . " channels: " . $channels;
echo "\n";
}
}
}
fclose($irc);
}
foreach ($servers as $server) {
echo date('h:i:s') . " getting statistics for " . $server;
echo "\n";
get_statistics($server, '6667');
}
exit;
?>
Here is the output:
root#li140-48:~# php bot.php
11:04:23 getting statistics for irc.freenode.net
11:04:24 network: irc.freenode.net
11:04:24 server: sendak.freenode.net
11:04:24 users: 90601
11:04:24 servers: 26
11:04:24 ircops: 22
11:04:24 channels: 50958
11:05:25 getting statistics for irc.icq.com
11:05:26 network: irc.icq.com
11:05:26 server: irc-k01a.orange.icq.com
11:05:26 users: 2671
11:05:26 servers: 3
11:05:26 ircops: 16
11:05:26 channels: 810
11:06:26 getting statistics for irc.quakenet.org
11:06:28 network: irc.quakenet.org
11:06:28 server: blacklotus.ca.us.quakenet.org
11:06:28 users: 37648
11:06:28 servers: 40
11:06:28 ircops: 67
11:06:28 channels: 26711
root#li140-48:~#
My question is what causes the delay between the servers being indexed?
At 10.24:19 it has completed the index of irc.icq.com so at this point it should disconnect and immediately index the next server in the array, but instead of that it is waiting exactly a minute before doing so, but I have not mentioned a minute in the script?
Hoping some PHP gurus can lend a hand!

60 seconds is the default socket timeout. You're continuing to try an read from the stream after you've already got all the information you're going to get - up until the timeout is finally reached.

Related

PHP and Child Processes

So I've been developing PHP for a bit now and have been attempting to troubleshoot why exec with a redirection of standard IO is still hanging the main thread.
exec(escapeshellcmd("php ".getcwd()."/orderProcessing.php" . " " . $Prepared . " " . escapeshellarg(35). "> /dev/null 2>&1 &"));
The code provided is what I've been trialing with, and I can't seem to get it to not hang until the other script completes. The reason I am doing this is in this paticular case, processing an order can take upto 30 seconds, and I don't want the user on the frontend to wait for that.
Can I only spawn child processes with php-fpm?
Is there something I have misconfigured?
Am I just misunderstanding how child processes work?
Setup is:
Centos 7 with Apache HTTPD and PHP 8.1.11
Any help appreciated!
Yes, it is possible in PHP. With proc_open() function, you can send command without wait another process. With handle opened stream, you can catch process status and check it consistently. For example:
$max = 5;
$streams = [];
$command = 'php ' . __DIR__ . '/../../process runSomeProcessCommand';
while (true) {
echo 'Working :' . count($streams) . "\n";
for ($i = 0; $i < $max; $i++) {
if (!isset($streams[$i])) {
$descriptor = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w']
];
echo "proc opened $i \n";
$streams[$i]['proc'] = proc_open($command . ":$i", $descriptor, $pipes);
$streams[$i]['pipes'] = $pipes;
$streams[$i]['ttl'] = time();
usleep(200000);
} else {
$info = proc_get_status($streams[$i]['proc']);
if ($info['running'] === false) {
echo "Finished $i . TTL: (" . (time() - $streams[$i]['ttl']) . " sec.).Response: " . stream_get_contents($streams[$i]['pipes'][1]) . " \n";
fclose($streams[$i]['pipes'][1]);
if ($error = stream_get_contents($streams[$i]['pipes'][2])) {
echo "Error for $i. Error: $error " . PHP_EOL;
fclose($streams[$i]['pipes'][2]);
}
proc_close($streams[$i]['proc']);
unset($streams[$i]);
} else {
echo "Running process (PID {$info['pid']}) - $i: \n";
}
# $return_value = proc_close($streams[$i]);
}
}
sleep(3);
}
There are 5 threads in same time which are doesn't wait one another.

CSV Data not Writing to Database, SuiteCRM, Custom Import Script

I'm writing a custom import script for SuiteCRM and I'm getting the error:
Warning: array_combine() expects parameter 2 to be array, boolean
given in /var/www/html/afscmedbv5test/custom/wimporter/newimporter.php
on line 162
My Script is as follows:
<?php
if (!defined('sugarEntry') || !sugarEntry) die ('Not a Valid Entry Point!');
$date = new DateTime();
echo '<H2>Wilderness Import Started</h2>';
echo $date->format('r').'<br>';
echo '-----------------------------------------------------------------------
--------------------------------------------------------------<br>';
require_once("include/utils/sugar_file_utils.php");
WildernessImportJob();
die();
function var_dump_ret($mixed = null) {
ob_start();
var_dump($mixed);
$content = ob_get_contents();
ob_end_clean();
return $content;
}
function time_elapsed()
{
static $first = null;
static $previous = null;
$now = microtime(true);
if ($first == null) $first = $now;
if ($previous != null)
echo '--- Partial ' . round(($now - $previous), 2) . ', Total ' . round(($now
- $first), 2) . ' ---'; // 109s
$ret = round(($now - $previous), 2);
$previous = $now;
return $ret;
}
function myLog ($str2log)
{
file_put_contents('./zlog_'.date("j.n.Y").'.txt', date("H:i:s", time())."
".$str2log.PHP_EOL, FILE_APPEND);
}
function calcDelta($a1, $a2)
{
//combine into a nice associative array:
$delta=Array();
foreach ($a1 as $key=>$value)
{
if ($a1[$key] != $a2->$key)
$delta[] = array($key => ("Was ". $a1[$key]. ", became " . $a2->$key));
}
$num = count($data);
if (empty($a1)) $delta[] = array("a1" => ("Was empty"));
if (empty($a2)) $delta[] = array("a2" => ("Was empty"));
return $delta;
}
require_once("include/utils/sugar_file_utils.php");
function fillPerson($record, &$person)
{
// $record is what is being imported from CSV
// $person is the bean about to be filled and going into the SuitCRM DB. It
may be new or not, depending on whether it exists in the DB previously.
// name: only updates if not existant yet, because it's the key we use for
search, and because names are more complex with parts
if ($person->full_name_c == "") {
$recordname = $record["FULL NAME"]; // != "") ? $record["FULL NAME"] : "
[To-be-filled]");
//echo $prefix;
$recordname = str_replace(" ", " ", $recordname);
echo $recordname;
$parts = explode(" ", $recordname);
$person->last_name = array_pop($parts);
$person->first_name = $parts[0];
$person->name = $person->first_name . " " . $person->last_name;
$person->full_name_c = $record["FULL NAME"]; // custom field created in
Studio
}
//$datanasc = DateTime::createFromFormat('!m/d/Y', $record["PPE"]);
// $datasnasc->setTime(0, 0);
// $person->ppe_date_c = ($datanasc == false) ? "" : $datanasc->format('m-d-
Y');
//$person->ppe_date_c = $record["PPE"];
//print_r($person);
var_dump($person);
}
// finish by making a complete analysis of what changed:
return calcDelta($person->fetched_row, $person);
function GetOrCreateMember ($the_name)
{
//Check if the fullname is null
if ($the_name != "")
{
$person = BeanFactory::getBean("locte_Members");
$person = $person->retrieve_by_string_fields(array('full_name_c' =>
$the_name));
if (is_null($person))
{
//get members bean
$person = BeanFactory::newBean("locte_Members");
//set full_name_c to the_name variable
$person->full_name_c = $the_name;
// $person->lcl_employee_id = $personEmployeeID;
$person_name = str_replace(" ", " ", $the_name);
$parts = explode(" ", $person_name);
$person->last_name = array_pop($parts);
$person->first_name = $parts[0];
//combine first and last name to populate the fullname field
$person->name = $person->first_name . " " . $person->last_name;
$person_id = $person->save();
// add new duespayment to member record
// $rosterDuesPayments = BeanFactory::getBean('Dues Payments')-
>retrieve_by_string_fields(array('name'=> $duesEmployeeID));
// $person->load_relationship('locte_Members_adues_dues'); //confirm
relationship name in cache
// $person->dues_payments->add($rosterDuesPayments->id);
}
return $person;
}
return null;
}
function WildernessImportJob()
{
try
{
time_elapsed();
$GLOBALS['log']->info('Wilderness Import');
$config = new Configurator();
$config->loadConfig();
$xmlDataDir = 'custom/wimporter/ToImport'; //$config->config['WildernessImporter_DataFilePath'];
$GLOBALS['log']->info("Wilderness Import: Scanning XML Data dir $xmlDataDir...");
echo("<h3>Wilderness Import: Scanning XML Data dir $xmlDataDir...<br /></h3>");
$directoryContent = scandir($xmlDataDir);
$GLOBALS['log']->info("Wilderness Import: Scanning XML Data dir $xmlDataDir... [Found " . count($directoryContent) . " files]");
echo("<h3>Wilderness Import: Scanning XML Data dir $xmlDataDir... [Found " . count($directoryContent) . " files]</h3><br />");
foreach ($directoryContent as $itemFile)
{
if (is_dir($xmlDataDir . DIRECTORY_SEPARATOR . $itemFile)) continue;
if (strcasecmp(substr($itemFile, -4), ".csv") != 0) continue;
$GLOBALS['log']->info("Wilderness Import: Processing $itemFile file...");
myLog("---------------------------------------------------");
myLog("Wilderness Import: Processing $itemFile file...");
myLog("----------------------------------------------------");
echo("<h4>---------------------------------------------------------------</h4>");
echo("<h4>Wilderness Import: Processing $itemFile file...</h4>");
echo("<h4>---------------------------------------------------------------</h4>");
$oFile = fopen($xmlDataDir . DIRECTORY_SEPARATOR . $itemFile, 'r');
if ($oFile !== FALSE)
{
// read entire file at once:
// expected separator is ",", expected encoding is UTF-8 without BOM (BOM is 3 weird characters in beginning of file)
while (($data[] = fgetcsv($oFile, 0, ',')) !== FALSE) { }
echo('File opened..... <br /> <br />');
fclose($oFile);
//combine into a nice associative array:
$arow=Array();
echo('Building CSV File Row Array <br /><br />');
$fields = array_shift($data);
echo('Building CSV Header Fields Array as shown below:<strong> <br /><br />');
echo implode(", ", $fields) . "</strong><br /><br />\n";
foreach ($data as $i=>$arow)
{
$GLOBALS['log']->info("Wilderness Import: array_combine " . $i);
$data[$i] = array_combine($fields, $arow);
}
unset($arow); // **********************************************! ! ! !! ! ! ! ! ! !! !
$num = count($data);
echo('Build Full Array of Roster to be Imported Complete. Entries to be imported are shown below <br /><br />');
for ($row=0; $row < $num - 1 ; $row++)
{ // normal bounds: from 0 to $num
//$num is the number of lines including header in csv file
echo "<strong>Filename: $itemFile | Roster Import, Row" . ($row + 1) . ":</strong><br />\n";
$GLOBALS['log']->info("Wilderness Import: Importing " . $data[$row]["FULL NAME"]);
// echo("<strong>Importing Roster Row #: ". ($row + 1) . "<br />" . "Local Number " . $data[$row]["AFFILIATE"] . "<br />" . "Employee: " . $data[$row]["FULL NAME"] . "</strong><br /><br />");
echo "<strong><table>\n";
foreach ($fields as $field) {
//echo "<tr><td>" . $field . "</td><td>" . $data[$row][$field] . "</td><td>" . $data[$row+1][$field] . "</td><td>" . $data[$row+2][$field] . "</td></tr>\n";
}
echo "</table>\n";
echo "File Row Data: ";
echo implode(", ", $data[$row]) . "</strong><br /><br />\n";
$Member = BeanFactory::getBean("locte_Members");
$FullName=$Member->full_name_c;
//$myfield_defs = $Member->getFieldDefinitions(); // just to help while developing
//foreach($myfield_defs as $def) echo $def["name"] . "<br />\n";
$Member=$Member->retrieve_by_string_fields(array('full_name_c' => $data[$row]["FULL NAME"]));
if (is_null($Member)) {
$Member = BeanFactory::newBean("locte_Members");
$delta = fillPerson($data[$row], $Member, ""); //->full_name_c, "FULL NAME");
}
if (count($delta)) {
$Member_id = $Member->save();
}
}
// Records have been saved: from this point on, only work on relationships:
$GLOBALS['log']->info('End: Wilderness Import');
myLog('End: Wilderness Import');
time_elapsed();
return true;
}
}
} catch (Exception $e)
{
$GLOBALS['log']->fatal("Wilderness Import: Exception " . $e->getMessage());
myLog("Wilderness Import: Exception " . $e->getMessage());
echo '\n\nCaught exception: ', $e->getMessage(), "\n";
return false;
}
}
It does return info from both the database and the csv file.
Image of error below.
Error - Capture from browser
Help always appreciated :)
This script is throwing error because the parameter $arow given to array_combine is not an array. So a check should be there to check whether $arow is an array or not.
Try code following:
foreach ($data as $i => $arow) {
$GLOBALS['log']->info("Wilderness Import: array_combine " . $i);
if (is_array($arow)) {
$data[$i] = array_combine($fields, $arow);
}
}
Read more about array_combine
Update
Code you are using to read csv need to be changed. Second parameter in fgetcsv must be greater than the longest line (in characters) to be found in the CSV file. So replace code
while (($data[] = fgetcsv($oFile, 0, ', ')) !== FALSE) {
}
with
while (($data[] = fgetcsv($oFile, 10, ', ')) !== FALSE) {
}
Read more about fgetcsv
This block is doing the saving of records using the beanfactory.... I think :|
$Member = BeanFactory::getBean("locte_Members");
$FullName=$Member->full_name_c;
//$myfield_defs = $Member->getFieldDefinitions(); // just to help while developing
//foreach($myfield_defs as $def) echo $def["name"] . "<br />\n";
$Member=$Member->retrieve_by_string_fields(array('full_name_c' => $data[$row]["FULL NAME"]));
if (is_null($Member)) {
$Member = BeanFactory::newBean("locte_Members");
$delta = fillPerson($data[$row], $Member->full_name_c, "FULL NAME");
var_dump($arow);
}
if (count($delta)) {
$Member_id = $Member->save();
}
}
// Records have been saved: from this point on, only work on relationships:
Here's the output of the script in the browser with field definition dump
Wilderness Import Started
Tue, 19 Jun 2018 02:05:56 -0400
Wilderness Import: Scanning XML Data dir custom/wimporter/ToImport...
Wilderness Import: Scanning XML Data dir custom/wimporter/ToImport... [Found 3 files]
Wilderness Import: Processing L1554v4.csv file...
File opened.....
Building CSV File Row Array
Building CSV Header Fields Array as shown below:
LAST NAME, FIRST NAME, FULL NAME
Build Full Array of Roster to be Imported Complete. Entries to be imported are shown below
Filename: L1554v4.csv | Roster Import, Row1:
LAST NAME BUTLER
FIRST NAME BRIANA
FULL NAME BUTLER BRIANA
File Row Data: BUTLER, BRIANA, BUTLER BRIANA
-id
-name
-date_entered
-date_modified
-modified_user_id
-modified_by_name
-created_by
-created_by_name
-description
-deleted
-securitygroup
-securitygroup_display
-created_by_link
-modified_user_link
-assigned_user_id
-assigned_user_name
-assigned_user_link
-additionalusers
-additionalusers_listview
-salutation
-first_name
-last_name
-full_name
-title
-photo
-department
-do_not_call
-phone_home
-email
-phone_mobile
-phone_work
-phone_other
-phone_fax
-email1
-email2
-invalid_email
-email_opt_out
-primary_address_street
-primary_address_street_2
-primary_address_street_3
-primary_address_city
-primary_address_state
-primary_address_postalcode
-primary_address_country
-alt_address_street
-alt_address_street_2
-alt_address_street_3
-alt_address_city
-alt_address_state
-alt_address_postalcode
-alt_address_country
-assistant
-assistant_phone
-email_addresses_primary
-email_addresses
-email_addresses_non_primary
-lcl_birthdate
-lcl_affiliate_number
-member_signature
-ssn
-staff_rep
-mem_join_date
-class_title
-steward
-olo_code
-enterprise_id
-member_card
-address_map
-member_status
-primary_language
-english_speaking
-annual_salary
-currency_id
-state_hire_date
-dues_frequency
-card_sent_date
-gender
-disabilities
-marital_status
-executive_board
-affiliate_type
-middle_name
-name_suffix
-mailableflag
-no_mailflag
-apt_number
-zip4
-infosrc
-lcl_phone_collected
-lcl_hasmobile
-lcl_hasemail
-lcl_member_status
-backofficeassistants
-backoffice_assistant_phonoe
-backoffice_assistant_email
-lcl_employercontact
-lcl_work_dept
-lcl_work_location
-lcl_jobclasstitle
-lcl_employee_id
-lcl_join_date
-lcl_sig_auth
-lcl_dues_status
-lcl_on_probation
-lcl_prob_end_date
-lcl_prob_term
-afs_signed_by
-afs_region_number
-afemp_employers_id_c
-afs_employer
-primary_address_county
-locte_members_adues_dues
-full_name_c
-locte_members_afcbu_cbu
-locte_members_afcbu_cbu_name
-locte_members_afcbu_cbuafcbu_cbu_idb
-ppe_date_c
--- Partial 0.01, Total 0.01 ---

Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL

I'm trying to send test message with my PHP SOAP client. I'm using BeSimpleSoap library because I had problems with standard PHP SOAP calss and NuSOAP class. This is my script:
<?php
function __autoload($class_name) {
include "C:\\xampp\\htdocs\\NIAS\\BeSimpleSoap-master\\src\\" .$class_name . '.php';
}
$full_path="C:\\xampp\\htdocs\\NIAS\\Unload\\";
$destination="C:\\xampp\\htdocs\\NIAS\\Arhiva\\";
$OIB_URL="https://demo.apis-it.hr:8444/kpoib/kp_lista_aktiviranih_korisnika.txt";
//$OIB_list=file_get_contents($OIB_URL);
//echo $OIB_list;
$date_time = date("Y-m-d") . "T" . date("G") . ":" . date("i") . ":" . date("s");
$rows_lines="";
$input_file=scandir($full_path);
foreach ($input_file as $input_name){
if($input_name=="." || $input_name=="..")
continue;
$lines = file($full_path . $input_name);
//$flag=true; //flag for skiping lead row in file
foreach($lines as $line)
{
//if($flag) { $flag = false; continue; }//skip the first row in file
$line_row = explode(':', $line);
//$rows_lines .= implode(";",$line_row);
if(substr($input_name,0,7)=="naknade"){
if(empty($line_row[6])){
$IBAN_tmp=$line_row[7].$line_row[8].'172700';
$IBAN=IBAN_generator($IBAN_tmp);
}
else{
$IBAN=$line_row[6];
}
$compensation = number_format($line_row[2],2);
$title="Obavijest o uplati naknade plaće zbog privremene nesposobnosti za rad, rodiljne i roditeljske potpore";
echo $rows_lines ="Poštovana/i,\nNa Vaš račun " . $IBAN . " upućena je " . $line_row[5] . " u iznosu od " . $compensation . " kuna za " . $line_row[0] . ". mjesec " . $line_row[1] . ". godine." . "</br>";
}
else if(substr($input_name,0,9)=="za_e_grad"){
$title="Obavijest o isteku dopunskog osiguranja";
echo $rows_lines ="Poštovana/i,\nVaše dopunsko zdravstveno osiguranje, broj iskaznice " . $line_row[1] . ", ističe " . $line_row[2] . " godine.". "</br>";
}
/*
$par_data = new StdClass();
$par_data->encoding = "EMBEDDED";
$par_data->any = $par_data;
*/
$par_data=array("KorisnickiPretinacPoruka" =>
array("Zaglavlje"=>
array("IdPosiljatelja"=>"000000001","IdPoruke"=>"833362f-063f-11e2-892e-0802200c9a62","DatumVrijemeSlanja"=>$date_time,"RazinaSigurnosti"=>2),
"Poruka" =>array("PinPrimatelja"=>"012345678901","OznakaDrzave"=>"HR","Predmet"=>$title,"Sadrzaj"=>$rows_lines)));
$par_envelope=array( "GsbEnvelope" =>
array( "MessageHeader" =>
array("SenderId" => "000000001",
"ServiceId" => "000000002",
"MessageId" => "833362f-063f-11e2-892e-0802200c9a62",
"SenderTimeStamp" => $date_time),
"Content" => array("MimeType" =>"application/xml","Data" =>array("encoding"=>"EMBEDDED","any"=>$par_data))));
$client = new BeSimple\SoapClient\SoapClient("GSBService.wsdl", array(
"trace"=>1,
"exceptions"=>1,
"local_cert" =>"C:\\PKI\\democacert.cer",
"passphrase"=>"",
"connection_timeout" => 300));
print_r( $client->sendMessage($par_envelope));
echo "<p>Request :".htmlspecialchars($client->__getLastRequest()) ."</p>";
echo "<p>Response:".htmlspecialchars($client->__getLastResponse())."</p>";
echo "<p>Debug:".soapDebug($client)."</p>";
}
if (copy($full_path.$input_name, $destination.$input_name)) {
$delete1[] = $full_path.$input_name;
}
}
if (!empty($delete1)){
foreach ($delete1 as $file1) {
unlink($file1);
}
}
function IBAN_generator($acc){
if(strlen($acc)!=23)
return;
$temp_str=substr($acc,0,3);
$remainder =$temp_str % 97;
for($i=3;$i<=22;$i++)
{
$remainder =$remainder .substr($acc,$i,1);
$remainder = $remainder % 97;
}
$con_num = 98 - $remainder;
if ($con_num<10)
{
$con_num="0".$con_num;
}
$IBAN="HR".$con_num.substr($acc,0,17);
return $IBAN;
}
?>
I have enabled extension=php_openssl.dll in php.ini.
I'm getting this error:
Warning: DOMDocument::save(/tmp\wsdl_9429a1dff02ce405ba48d1992f82604d.cache): failed to open stream: No such file or directory in C:\xampp\htdocs\NIAS\BeSimpleSoap-master\src\BeSimple\SoapClient\WsdlDownloader.php on line 204
Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from '/tmp\wsdl_9429a1dff02ce405ba48d1992f82604d.cache' : failed to load external entity "/tmp/wsdl_9429a1dff02ce405ba48d1992f82604d.cache" in C:\xampp\htdocs\NIAS\BeSimpleSoap-master\src\BeSimple\SoapClient\SoapClient.php:113 Stack trace: #0 C:\xampp\htdocs\NIAS\BeSimpleSoap-master\src\BeSimple\SoapClient\SoapClient.php(113): SoapClient->SoapClient('/tmp\wsdl_9429a...', Array) #1 C:\xampp\htdocs\NIAS\HZZO-OKP-SOAP.php(76): BeSimple\SoapClient\SoapClient->__construct('GSBService.wsdl', Array) #2 {main} thrown in C:\xampp\htdocs\NIAS\BeSimpleSoap-master\src\BeSimple\SoapClient\SoapClient.php on line 113
(This was solved rather tersely in the comments, transcribed herein. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
I have solved it by editing PHP.ini with soap.wsdl_cache_dir="C:\xampp\htdocs\NIAS\tmp"

php script executes but no output

I have gone through all the similar questions and nothing fits the bill.
I am running a big script, which ran on chron on an old server but failed on the new so I am working on and testing in browser.
I have two functions, one pulls properties from the database, and then runs them through another which converts the price into 4 currencies, and if the value is different updates the row. The functions are as follows:
<?php
function convert_price($fore_currency, $aft_currency, $amount)
{
echo "going into convert<br/>";
$url = "http://www.currency.me.uk/remote/ER-ERC-AJAX.php?ConvertFrom=" . $fore_currency .
"&ConvertTo=" . $aft_currency . "&amount=" . $amount;
if (!is_int((int)file_get_contents($url))) {
//echo "Failed on convert<br/>";
return false;
} else {
//echo "Conversion done";
return (int)file_get_contents($url);
}
}
function run_conversion($refno = '', $output = false)
{
global $wpdb;
$currencies = array("GBP", "EUR", "TRY", "USD");
$q = "SELECT * FROM Properties ";
$q .= (!empty($refno)) ? " WHERE Refno='" . $refno . "'" : "";
$rows = $wpdb->get_results($wpdb->prepare($q), ARRAY_A);
$currencies = array("USD", "GBP", "TRY", "EUR");
//$wpdb->show_errors();
echo "in Run Conversion " . "<br/>";
foreach ($rows as $row) {
echo "In ROw <br/>";
foreach ($currencies as $currency) {
if ($currency != $row['Currency'] && $row['Price'] != 0) {
$currfield = $currency . "_Price";
$newprice = convert_price($row['Currency'], $currency, $row['Price']);
echo "Old Price Was " . $row['Price'] . " New Price Is " . $newprice . "<br/>";
if ($newprice) {
if ($row[$currfield] != $newprice) {
$newq = "UPDATE Properties SET DateUpdated = '" . date("Y-m-d h:i:s") . "', " .
$currfield . "=" . $newprice . " WHERE Refno='" . $row['Refno'] . "'";
$newr = $wpdb->query($newq);
if ($output) {
echo $newq . " executed <br/>";
} else {
echo "query failed " . $wpdb->print_error();
}
} else {
if ($output) {
echo "No need to update " . $row['Refno'] . " with " . $newprice . "<br/>";
}
}
} else {
echo "Currency conversion failed";
}
}
}
}
}
?>
I then run the process from a seperate file for the sake of chron like so:
require($_SERVER['DOCUMENT_ROOT'] . "/functions.php"); // page containing functions
run_conversion('',true);
If I limit the mysql query to 100 properties it runs fine and I get all the output in a nice stream. But when I try to run it in full the script completes (I can see from rows updated in db) but no output. I have tried upping the memory allowance but no joy. Any ideas gratefully received. Also, I get a 500 error when changing from Apache Module to CGI. Any ideas on that also well received as ideally I would like to turn site onto fastCGI.
You're running out of memory most likely. Probably in your DB layer. Your best bet is to unset your iterative values at the end of each loop:
foreach ( $rows as $row ) {
...
foreach ( $currencies as $currency ) {
...
unset( $currency, $newr, $currfield, $newprice );
}
unset( $row );
}
This will definitely help.
As another answer suggests you may be running out of memory, but if you make an HTTP call everytime the loop is running, and you have 100+ currencies, this may also cause the problem. Try limit it to 5 currencies for example.
If this is indeed the problem I would split the process, so a chunk of currencies have their respective value updated per cron job, instead of everything.

can't see describe queries in zend framework db profiler

I have zend database profiler set up and turned on in my development site. I can see all the queries except for the DESCRIBE queries, which I know it should be running each time I ask for a new table object. I'm using something like this to look at the queries:
$db = Zend_Registry::get('db');
$profiler = new Zend_Db_Profiler();
$profiler->setEnabled(true);
$db->setProfiler($profiler);
$i = 1;
$output = 'PROFILE FOR: '.$_SERVER['REQUEST_URI'] . "\n";
foreach ($profiler->getQueryProfiles() as $query) {
$output .= "Query ".$i++.": ".$query->getQuery(). "\n";
}
$output .= 'Average query length: ' . $totalTime / $queryCount .
' seconds' . "\n";
$output .= 'Queries per second: ' . $queryCount / $totalTime . "\n";
$output .= 'Longest query length: ' . $longestTime . "\n";
$output .= "Longest query: \n" . $longestQuery . "\n\n";
file_put_contents('/tmp/zend_profiler.log', $output, FILE_APPEND);
}
Not sure why I can't see the describe queries. Has anyone else run into this issue?
Maybe you have activated the metadata cache for you database connection (which usually is a very good thing especially in production). In that case the DESCRIBE queries won't be executed until the cache expires.
Verify it by executing this line somewhere in application after the bootstrap
if (null != Zend_Db_Table_Abstract::getDefaultMetadataCache()) {
echo "Cache is active, describe queries not run";
} else {
echo "Cache is not active";
}

Categories