0

How can optimize my PHP script? It works fine, but it's so slow. It takes almost 1 minute to complete. Is there anything I can do?

Here is my example script

<?php
if ($_GET["email"]) {
    $bar = ['493038', '493014', '493762']; //upto 100 bar ids      
    foreach ($bar as $barid) {
        $email = $_GET['email'];
        $batch = $_GET['batch'];
        date_default_timezone_set('UTC+8');
        $today = date("Y-d-m");
        $url = "https://someapilink/api";
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $headers = array(
            "Content-Type: application/json;charset=UTF-8",
            "Accept: application/json, text/plain, */*"
        );
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $data = <<<DATA
{
  "email": "$email",
  "bar": "$barid",
  "batch": "$batch",
  "date": "$today"
}
DATA;
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($curl);
        $httpcode = curl_getinfo($curl,CURLINFO_HTTP_CODE);
    }
  echo "<br>server returned an HTTP Status code $httpcode";
}
?>
j08691
  • 204,283
  • 31
  • 260
  • 272
hakdog
  • 1
  • 2
    _"upto 100 bar ids"_ - Well, that would mean that your code would do up to 100 http requests in a loop. That's bound to take time. How long does one request take? It could also be that the server has some slow down if it gets hammered with requests from the same IP. We can't possibly know that so we can't really give you an answer here. – M. Eriksson Sep 19 '21 at 21:33
  • 2
    You are performing a GET and a POST in an unknown API service. the only things here left to optimize is perhaps to lower the amount of loops... this pretty much depends on the API you are dealing with , perhaps you can GET multiple $bar data in one GET? and if possible update your data also on one POST - this is depended on the API you are using .... – Shlomtzion Sep 19 '21 at 21:36
  • 4
    _Side note:_ Don't manually build json data. Create an array with the data in the correct format and use `json_encode()` to turn it into json. That will also handle any escaping that might be needed and removes the risk of you sending broken/invalid json. – M. Eriksson Sep 19 '21 at 21:38
  • https://stackoverflow.com/questions/9308779/php-parallel-curl-requests – kmoser Sep 19 '21 at 22:05
  • it takes around 1.4seconds to complete 1 get - post request – hakdog Sep 20 '21 at 10:27
  • Well that's not super-fast but it's not unreasonably slow either. If it's the remote server or the network which is the issue, and you're not in control of either then there probably isn't much you can do. – ADyson Sep 20 '21 at 15:15
  • i guess so thanks alot – hakdog Sep 20 '21 at 16:18

0 Answers0