I'm trying to send SMS using an API. It is sending almost one SMS per second but i want to send multiple SMS in one second using multithreading/pthreads in PHP. How is it possible or how can i send multiple SMS request asynchronously to API server from my end at least time.
//Threads Class
class MThread extends Thread {
public $data;
public $result;
public function __construct($data){
$this->data = $data;
}
public function run() {
foreach($this->data as $dt_res){
// Send the POST request with cURL
$ch = curl_init("http://www.example.com");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dt_res['to']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$this->result = $http_code;
/**/
}
}
}
// $_POST['data'] has multi arrays
$request = new MThread($_POST['data']);
if ($request->start()) {
$request->join();
print_r($request->result);
}
Any idea will be appreciated.
It's better to use something like Beanstalk with multiple workers.
Why do you make a foreach into the run() ? When you do that, that exactly like a simple function, no multithreading.
Here is the solution at your problem:
$thread = array();
foreach ($_POST['data'] as $index => $data) {
$thread[$index] = new MThread($data);
$thread[$index]->start();
}
You should be able to understand your error with this code.
Just delete your foreach into your run() function and use my code and it's will work.
You don't necessarily need to use threads to send multiple HTTP requests asynchronously. You can use non-blocking I/O, multicurl is suitable in this case. There are some HTTP clients with multicurl support. Example (using Guzzle 6):
$client = new \GuzzleHttp\Client();
$requestGenerator = function() use ($client) {
$uriList = ['https://www.google.com', 'http://amazon.com', 'http://github.com', 'http://stackoverflow.com'];
foreach ($uriList as $uri) {
$request = new \GuzzleHttp\Psr7\Request('GET', $uri);
$promise = $client->sendAsync($request);
yield $promise;
}
};
$concurrency = 4;
\GuzzleHttp\Promise\each_limit($requestGenerator(), $concurrency, function(\GuzzleHttp\Psr7\Response $response) {
var_dump($response->getBody()->getContents());
}, function(\Exception $e) {
var_dump($e->getMessage());
})->wait();