-3

I have an integration with Twilio's PHP library to bulk send SMS messages. This is all working fine with 5-10 numbers, however, I keep getting a 504 timeout error after 60 seconds when sending to hundreds of numbers. I have created a simple form that you can type a message into which submits to Twilio's API. My integration opens a CSV which contains all the numbers and sends the message to each number. The issue I have is that after 60 seconds I hit a 504 timeout error and therefore only 200-300 numbers receive my SMS. How can I avoid this? Is there a way to break down the nubmers into batches?

<?php
require __DIR__ . '/src/Twilio/autoload.php';

use Twilio\Rest\Client;

// Your Account SID and Auth Token from twilio.com/console
$sid = 'xxxxxxxxxxxxxxx';
$token = 'xxxxxxxxxxxxx';
$notify_sid = 'xxxxxxxxxxxx';
$client = new Client($sid, $token);

    $row = 1;
        if (($handle = fopen("test.csv", "r")) !== FALSE) {
            while (($data = fgetcsv($handle, 100, ",")) !== FALSE) {
                $num = count($data);
                $row++;
                    for ($c=0; $c < $num; $c++) {
                        $numbersFinal = "'".$data[$c] . "',";
                        
                    if ($_SERVER["REQUEST_METHOD"] == "POST") {

                        // Use the client to do fun stuff like send text messages!
                        $message = $_POST['message'];

                        $phoneNumbers = array($numbersFinal);

                        $to = array();
                        foreach ($phoneNumbers as $phoneNumber) { 
                            $to[] = '{"binding_type":"sms", "address":"'.$phoneNumber.'"}';
                        }

                        $request_data = [
                            "toBinding" => $to,
                            'body' => $message
                        ];


                        // Create a notification
                        $notification = $client
                        ->notify->services($notify_sid)
                        ->notifications->create($request_data);

                        }

                    }
                }
    
            fclose($handle);
        }

    ?>
sc2015
  • 123
  • 13

1 Answers1

1

504 is a timeout error. This error occurs because of your php.ini settings. Please check the phpinfo() output. Look for max_execution_time variable. It's probably 60 seconds. While you run the file, server terminates the process after this time exceeded.

To handle this problem, you can follow several ways:

  1. Ask your service provider to raise this limit. Usually, they reject those requests.
  2. You can run this file as a cron task. When you click send button, you can save it as a cronjob. You can figure it out.
  3. When you click send, you can send sms by 100, 100, ... send_sms.php?sent=100 could send 100 sms then redirect to send_sms.php?sent=200... until they end.

Tell me if any of these solutions work for you.

oralunal
  • 393
  • 3
  • 16