Link to home
Start Free TrialLog in
Avatar of kmgish
kmgish

asked on

PHP script hanging when connecting to 3rd party API

Is there a reliable way to force a php script to exit, or the connection to a 3rd party site to quit, after a certain period of time?  I need to display updated stock data on our intranet. Since the Yahoo Finance API recently disappeared, I'm now using an API provided by Alphavantage. I don't want to directly display 3rd party data on our site. So my system works in two parts: The first script (fired by a cron, every 15 minutes) gets CSV data, via their API call and stores it in a temp DB. (All tables are truncated at the end of the night.) The second script queries the DB and displays it on our site. Most of the time everything goes smoothly. But occasionally the first script hangs, causing the CPU usage to start increasing, eventually crashing the site.  But I don't understand how the script is running longer than 30 seconds, because "max_execution_time" in my php.ini is set to 30 seconds?  Below is my script. Thank you in advance for any insight you can offer!

<?php

function getData($theTable, $theSymbol) {
	
$theKey = 'ourApiKey';
include('db.php');

// Get the csv file from Alphavantage and parse the data, starting at row 2. (Row one contains the column names)
$theFile = 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=' . $theSymbol . '&interval=15min&apikey=$theKey&datatype=csv';

if($theFile) {

$con = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);

$start_row = 2; //define start row
$end_row = 100; //define start row
$i = 1; //define row count flag
$file = fopen($theFile, "r");
while (($row = fgetcsv($file)) !== FALSE) {
    if(($i >= $start_row) && ($i <= $end_row)) {
$theArray = ($row);
$theArray = array_values($theArray);
// assign variables to column values 
		$timestamp = htmlspecialchars($theArray[0], ENT_QUOTES);
		$open = htmlspecialchars($theArray[1], ENT_QUOTES);
		$high = htmlspecialchars($theArray[2], ENT_QUOTES);
		$low = htmlspecialchars($theArray[3], ENT_QUOTES);
		$close = htmlspecialchars($theArray[4], ENT_QUOTES);
		$volume = htmlspecialchars($theArray[5], ENT_QUOTES);
			
		$timestamp1 = date('Y-m-d', strtotime($timestamp));
		$today = date('Y-m-d');
		if($timestamp1 == $today ) {
		
$query = "INSERT INTO $theTable (timestamp,open,high,low,close,volume) values('$timestamp','$open','$high','$low','$close','$volume')";
mysqli_query($con,$query);
		
}
}
    $i++;	
}


if ($con->connect_errno) {
    printf("Connect failed: %s\n", $con->connect_error);
    exit();
}

$con->close();
fclose($file);

}
}
?>

Open in new window

Avatar of David Favor
David Favor
Flag of United States of America image

Run your script in an IDE or simply place logging statements in your code to identify where the hang occurs.

If the problem is in your code, fix your code.

If the problem is in the Alphavantage API, open a ticket with them. My guess is they'll fix the problem immediately.

If you require a quick solution, then you can always process the ALARM signal.

http://www.linuxformat.com/wiki/index.php/PHP_-_Alarm_functions is one resource coving how to approach this.

Basically you start an alarm prior to a section of code running... say 5 seconds... then run your code section + at the end of the section disable the ALARM signal. If all goes well + your code section runs in <5 seconds, nothing happens.

If your code section runs >5 seconds, an ALARM signal is thrown + you can process it however seems best, like doing an error exit of completing the rest of your remaining code.
Avatar of kmgish
kmgish

ASKER

Thanks!  I'll take a look at the alarm function.  I believe the issue is the script is occasionally failing to download one of the CSV files and then trying to get the next one, without finishing the first.  Right now I'm separating the execution of each stock quote with the sleep function. Hopefully that will solve the problem.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.