I'm building a small project regarding WhatsApp, and I'm using the https://github.com/mgp25/Chat-API, even though there's no longer support on the repo.
My issue is with sockets, and I'm using them to log in. The section of my code which is failing is :
<?php
$socket = fsockopen("e" . rand(1, 16) . ".whatsapp.net:" . Constants::PORT);
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array(
'sec' => Constants::TIMEOUT_SEC,
'usec' => Constants::TIMEOUT_USEC
));
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array(
'sec' => Constants::TIMEOUT_SEC,
'usec' => Constants::TIMEOUT_USEC
));
?>
I'm getting the following error:
C:\MAMP\htdocs\WhatsappTestApp\whatsapp\src\whatsprot.class.php on line 305
[10-May-2017 15:11:13 Africa/Johannesburg] PHP Warning: socket_set_option(): supplied resource is not a valid Socket resource in C:\MAMP\htdocs\WhatsappTestApp\whatsapp\src\whatsprot.class.php on line 291
[10-May-2017 15:11:13 Africa/Johannesburg] PHP Warning: socket_set_option(): supplied resource is not a valid Socket resource in C:\MAMP\htdocs\WhatsappTestApp\whatsapp\src\whatsprot.class.php on line 296
[10-May-2017 15:11:13 Africa/Johannesburg] PHP Warning: socket_read(): supplied resource is not a valid Socket resource in C:\MAMP\htdocs\WhatsappTestApp\whatsapp\src\whatsprot.class.php on line 299
[10-May-2017 15:11:13 Africa/Johannesburg] PHP Fatal error: Uncaught FailedProxy: [0]: Failed proxy. Error 3
thrown in C:\MAMP\htdocs\WhatsappTestApp\whatsapp\src\whatsprot.class.php on line 301
In your code you're mixing files with sockets , so PHP throws an error . To fix this, you can either create a socket with socket_create
, or use stream_set_timeout
to set the timeout and use filesystem functions to read / write to the socket :
<?php
$protocol = "tcp"; /* or "ssl" for HTTPS */
$host = "e" . rand(1, 16) . ".whatsapp.net";
$fp = fsockopen("$protocol://$host", Constants::PORT, $errn, $errm);
stream_set_timeout($fp, Constants::TIMEOUT_SEC);
/* You can treat $fp the same way you would treat a file */
//$data = fread($fp, 8192);
//fwrite($fp, "my data");
//fclose($fp);
?>
If you want to use sockets then $socket
should be a socket resource :
<?php
$host = "e" . rand(1, 16) . ".whatsapp.net";
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, $host, Constants::PORT);
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array(
'sec' => Constants::TIMEOUT_SEC,
'usec' => Constants::TIMEOUT_USEC
));
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array(
'sec' => Constants::TIMEOUT_SEC,
'usec' => Constants::TIMEOUT_USEC
));
?>