9 Replies - 509 Views - Last Post: 21 February 2018 - 08:23 PM Rate Topic: -----

#1 Yhym   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 48
  • Joined: 08-December 13

Localhost PHP Loading Speed Very Slow

Posted 18 February 2018 - 08:19 AM

Some people have mentioned to me that my site is quite inefficient and given that it's taking ~17secs to load now, I'd like to change that but I've no idea how. I've tried Gzip to compress it but it didn't help. I got rid of some "" and have used '' instead as well as got rid of some html blank spaces but that's about it. Below is most of my code, excluding some JS to save space. Either way, when I do F12 on my site, Google shows that it's the php file itself that takes so long to load, not JS so that's why I'm just showing that below. It's just this one page that's loading slowly, all others sites are very quick. I'd love some tips on how to make this more efficient. Thank you!

<?php
    require('includes/connection.php');
    require('includes/config.php'); 
        // Page name
    $title = 'Portfolio';
    // Include the header template
    require('layout/header.php'); 

    // If for some reason, not logged in then redirect to login page
    if(!$user->is_logged_in()){ header('Location: login.php'); exit(); }
?> 
<div>
    <h2><?php echo htmlspecialchars($_SESSION['username'], ENT_QUOTES); ?></h2>
    <button id="opener" class='btn btn-success' >Advanced Company Data</button>
    <div id="dialog" title="Advanced Company Data"><a href="http://www.nasdaq.com/symbol/aapl">Exchange Information</a>
    </div>
    </div>
    <script>
        $("#dialog").dialog({
            autoOpen: false
        });
        $("#opener").click(function() {
            $("#dialog").dialog("open", "modal", true );
        });
    </script>
    </div>
<?php
    $spy = file_get_contents('https://api.iextrading.com/1.0/stock/spy/stats/year1ChangePercent');  
    $spy = json_decode($spy,TRUE); 
    // Initialising variables to store extracted information
    $name = [];
    $symbol = [];
    $open = [];
    $close = [];
    $high = [];
    $low = [];
    $lastprice = [];
    $y = 0;
    $z = '';
    $key = '93dcc722279c3a7577f248b09ef6167f';

    // Retreiving information from database
    $memberid = $_SESSION['memberID'];
    $sql = "SELECT * FROM portfolio WHERE memberID = $memberid";
    $result = mysqli_query($conn, $sql);

    // Check if databse is empty
    if (mysqli_num_rows($result) > 0) 
    {
        while($row = mysqli_fetch_assoc($result)) 
        {
            $sym[$y] = $row['stocks_symbol'];
            $pri[$y] = $row['price'];
            $vol[$y] = $row['quantity'];
            $id[$y] = $row['memberid'];
            $y += 1;
        }
    }
    // If database empty
    else 
    {
        echo 'Portfolio Empty';
        die();
    }
    mysqli_close($conn);

    // Adding all stock names in one variable to enable API call
    for($a=0;$a<$y;$a++)
    {
        $z = $z.$sym[$a].',';
    }
    $z = rtrim($z,',');

    // API call
    $contents = file_get_contents("http://marketdata.websol.barchart.com/getQuote.json?key=$key&symbols=$z&mode=R");
    $contents = json_decode($contents, true);
    // Check successfull API call
    if($contents['status']['code'] == 200) 
    {
        foreach($contents['results'] as $result) 
        {
            array_push($name,$result['name']);
            array_push($symbol,$result['symbol']);
            array_push($open,$result['open']);
            array_push($close,$result['close']);
            array_push($high,$result['high']);
            array_push($low,$result['low']);
            array_push($lastprice,$result['lastPrice']);
        }
    }        
    // If API call unsuccessful
    else 
    {   
        echo 'Error retreiving data. Please try again later.';
        die();
    }
?>
<!-- Generating Output in tabular format -->
<table id= test class='table table-responsive'>
    <tr class='head warning'>
        <th>Name</th>
        <th>Symbol</th>
        <th>Open</th>
        <th>Close</th>
        <th>High</th>
        <th>Low</th>
        <th>Last Price</th>
        <th>Price Bought</th>
        <th>Quantity</th>
        <th>Change Per Stock</th>
        <th>Profit/Loss</th>
        <th>Amount Invested</th>
        <th>Current Market Value</th>
        <th>Dividend</th>
        <th>Total Dividend</th>
        <th>Company Description</th>
        <th>Latest News</th>
    </tr>
    <?php
    $profitOrLossSum = 0;
    $dividendRateSum = 0;
    $startEqSum = 0;
    $sumOf = array();
    $pnl = array();

        for($x=0;$x<$y;$x++) 
        {?>
            <tr>
                <td class="input"><?php echo $name[$x]; ?></td>
                <td class="input"><?php echo $symbol[$x]; ?></td>
                <td class="input"><?php echo $open[$x]; ?></td>
                <td class="input"><?php echo $close[$x]; ?></td>
                <td class="input"><?php echo $high[$x]; ?></td>
                <td class="input"><?php echo $low[$x]; ?></td>
                <td class="input"><?php echo $lastprice[$x]; ?></td>
                <td class="input"><?php echo $pri[$x]; ?></td>
                <td class="input"><?php echo $vol[$x]; ?></td>
                <td class="input"><?php 
                    if($pri[$x] > $lastprice[$x]) 
                    {
                        echo $lastprice[$x]-$pri[$x];
                    }
                    else if($pri[$x] < $lastprice[$x]) 
                    {
                        echo $lastprice[$x]-$pri[$x];
                    }
                    else
                        echo '0';
                    ?></td>
                <td class="input"><b><?php 
                    $profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
                    $profitOrLossSum += $profitOrLoss;
                    $pnl[] = $profitOrLoss;
                    echo $profitOrLoss;
                    ?></b></td>
                <td><?php 
                    $starteq = $pri[$x] * $vol[$x];
                    $startEqSum += $starteq;
                    echo $starteq;
                    ?></td>
                <td><b><?php
                    $firstno1  = floatval($vol[$x]);
                    $secondno1 = floatval($lastprice[$x]);
                    $sumOf[] = $firstno1 * $secondno1;
                    $sum1 = $firstno1 * $secondno1;
                    echo ($sum1);
                    ?>
                    </b></td>
                <td><?php 
                    $div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");  
                    $div = json_decode($div,TRUE);  
                    $sum = 0;
                    foreach($div as $divi => $value) {
                    echo $value['stats']['dividendRate']; 
                    $sum += (floatval($vol[$x]) + floatval($value['stats']['dividendRate']));
                     } 
                     ?></td>
                <td><?php 
                    $firstno  = floatval($vol[$x]);
                    $secondno = floatval($value['stats']['dividendRate']);
                    $sum2 = 0;
                    $sum2 += $firstno * $secondno;
                    echo ($sum2);
                    $dividendRateSum += $sum2;
                    ?></td>
                <td class="input"><?php
                        $desc = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=company&filter=description");  
                        $desc = json_decode($desc,TRUE); 
                        foreach($desc as $desc => $des) {
                        echo $des['company']['description'];
                        }
                     ?></td>
                <td><?php
                    $desc1 = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=news&filter=headline,url&range=1m&last=1");  
                    $desc1 = json_decode($desc1,TRUE); 
                    foreach($desc1 as $key111 => $des1) {
                    echo implode(PHP_EOL, array_column($des1['news'],'headline'));
                    ?><br><?php $link = implode(PHP_EOL, array_column($des1['news'],'url'));
                    echo '<a href="'.$link.'">Link</a>';
                    } 
                    ?></td>
            </tr>
            <?php 
        }
    $arr = array('profitOrLossSum' => $profitOrLossSum, 'dividendRateSum' => $dividendRateSum);
    $arr1 = array('startEqSum' => $startEqSum);     
    $array = array_combine($name, $sumOf);
    $array10 = array_combine($name, $pnl);
?>
</table>

<h3> SPY %YTD= <?php echo $spy1 = number_format($spy *100, 2); ?>%</h3>
    <br>
        <h3> Starting Equity= $<?php echo $startEqSum; ?></h3>
        <h3> Current Equity= $<?php echo $profitOrLossSum; ?></h3>
        <h3> Total Profit= $<?php echo $profitOrLossSum - $startEqSum; ?></h3>
        <h3> % Gain/Loss= <?php echo $gain = number_format((($profitOrLossSum - $startEqSum) / $startEqSum) * 100, 2); ?>%</h3>
        <h3> Total Dividend= $<?php echo $dividendRateSum / 4; ?>/Quarter</h3>
        <h3> Portfolio vs SPY= <?php echo $gain-$spy1; ?>%</h3><br>
</body> 


Is This A Good Question/Topic? 0
  • +

Replies To: Localhost PHP Loading Speed Very Slow

#2 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 14357
  • View blog
  • Posts: 57,593
  • Joined: 12-June 08

Re: Localhost PHP Loading Speed Very Slow

Posted 18 February 2018 - 09:47 AM

I would start checking if it is the API/JSON calls or your code itself. Perhaps comment somethings out.

Then again - what are you using to run this locally? Could be a webserver problem as well.
Was This Post Helpful? 1
  • +
  • -

#3 Yhym   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 48
  • Joined: 08-December 13

Re: Localhost PHP Loading Speed Very Slow

Posted 18 February 2018 - 12:59 PM

Thanks for the idea. It does look like the marketdata API is what's causing the slow down. Is there any way to make this faster or not really?
Was This Post Helpful? 0
  • +
  • -

#4 CTphpnwb   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3801
  • View blog
  • Posts: 13,787
  • Joined: 08-August 08

Re: Localhost PHP Loading Speed Very Slow

Posted 19 February 2018 - 06:30 AM

You might try using curl instead of file_get_contents. Also, it may be possible to make fewer queries. You have five and four look similar. Can you combine them into one or two?
Was This Post Helpful? 0
  • +
  • -

#5 Yhym   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 48
  • Joined: 08-December 13

Re: Localhost PHP Loading Speed Very Slow

Posted 19 February 2018 - 09:54 AM

Curl didn't work for me for some reason, I tried it. As for the question, it's the first time I'm using such an API and this was just the way it worked for me so I carried on doing it over and over. Not sure if it's the most efficient way.
Was This Post Helpful? 0
  • +
  • -

#6 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 14357
  • View blog
  • Posts: 57,593
  • Joined: 12-June 08

Re: Localhost PHP Loading Speed Very Slow

Posted 19 February 2018 - 10:00 AM

There are ways to minimize API impact.. things like do not pull on a page load but user instantiated, minimize the parameters so it pulls less, try and for a pull towards the end of a page rendering, etc.
Was This Post Helpful? 0
  • +
  • -

#7 CTphpnwb   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3801
  • View blog
  • Posts: 13,787
  • Joined: 08-August 08

Re: Localhost PHP Loading Speed Very Slow

Posted 19 February 2018 - 01:39 PM

This combines two of your requests. It does it client side, so if you need to do this on your server then you'll need to convert it.
<html>
	<head>
		<title>Test</title>
		<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
		<script>
			var company = { symbols:'AAPL,TSLA,VZ,GM,GOOG,MSFT', types: 'stats,company', filter:'dividendRate,description'};
			$.ajax({
				method: "GET",
				url: "https://api.iextrading.com/1.0/stock/market/batch",
				data: company
			}).done(function( msg ) {
				var output = '';
				for(var itm in msg) {
					output += itm + " has a dividend rate of "+ msg[itm].stats.dividendRate + "<br>" + msg[itm].company.description + "<br><br>";
				}
				document.getElementById('test').innerHTML = output;
			});
		</script>
	</head>
	<body>
		<div id="test"></div>
	</body>
</html>

The response is quick for me, so I'd suspect that file_get_contents is slowing things down.

Edit: I found it useful to generalize it. I might want to use it to scan through a large set of companies, looking for good dividends. ;)

This post has been edited by CTphpnwb: 19 February 2018 - 02:45 PM

Was This Post Helpful? 1
  • +
  • -

#8 Yhym   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 48
  • Joined: 08-December 13

Re: Localhost PHP Loading Speed Very Slow

Posted 20 February 2018 - 01:37 AM

Thanks for taking the time, I see how this works and it's definitely a nice, clean way of doing things. That said, displaying this data on its own doesn't really help me because I've other things that are connected to it, that depend on it. Namely the scripts at the bottom as well as I've arrays of this data connected to Google Charts which are then appropriately displayed. Is there any way for me to replace my approach with yours or not really? I'm not sure if I understand it correctly but I'm just wondering how I could incorporate this into my table vs the approach that I'm currently using.
Thanks for your help!

This post has been edited by andrewsw: 20 February 2018 - 03:03 AM
Reason for edit:: removed previous quote, just use the Reply button

Was This Post Helpful? 0
  • +
  • -

#9 CTphpnwb   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3801
  • View blog
  • Posts: 13,787
  • Joined: 08-August 08

Re: Localhost PHP Loading Speed Very Slow

Posted 20 February 2018 - 04:53 AM

There is a way. First, you need to separate your business logic from your display code. That way you can get your values first (in fewer queries) and then display the results. In pseudo code:

retrieveFromDB(); // For the love of God, use prepared statements!!! See below.
getDataFromExternalSources();
displayResults(); // Use functions. They help to keep code organized and readable.



This is wrong, and needs to be fixed immediately:
    $sql = "SELECT * FROM portfolio WHERE memberID = $memberid";
    $result = mysqli_query($conn, $sql);


See this tutorial.
Was This Post Helpful? 1
  • +
  • -

#10 CTphpnwb   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3801
  • View blog
  • Posts: 13,787
  • Joined: 08-August 08

Re: Localhost PHP Loading Speed Very Slow

Posted 21 February 2018 - 08:23 PM

I decided to test the speed of curl versus file_get_contents on this system, and in my limited testing the two methods appear to be about the same speed, with times ranging from about .25 to about .28 seconds for the query below. You might try testing each of yours. I'd guess that they'll all come out to about the same, so with 5 file_get_contents calls, that's around 1.3 seconds assuming there are no other delays.

<?php
$url = "https://api.iextrading.com/1.0/stock/market/batch?";
$params = ['symbols' => 'AAPL,TSLA,VZ,GM,GOOG,MSFT', 'types' => 'stats,company', 'filter' => 'dividendRate,description'];
foreach ($params as $key => $val) {
    $url .= $key . '=' . $val . "&";
}
$url = substr($url, 0, -1);
echo $url . "<br>";

$options = array(
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_URL => $url,
);

$time_pre = microtime(true);
$ch = curl_init();
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;

echo "time 1: " . $exec_time . "<br>";
print_r($response);

echo "<br>---<br>";

$time_pre = microtime(true);
$data = file_get_contents($url);
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;

echo "time 2: " . $exec_time . "<br>";
print_r($data);


This post has been edited by CTphpnwb: 21 February 2018 - 08:24 PM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1