could any one help me to understand the following example about handling multiple connection in PHP socket programming.
I need just to explain for me these steps
if(socket_select($read , $write , $except , null) === false)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
//if ready contains the master socket, then a new connection has come in
if (in_array($sock, $read))
{
}
really I cant understand what happen in those steps.
this is the full example :
error_reporting(~E_NOTICE);
set_time_limit (0);
$address = "0.0.0.0";
$port = 6000;
$max_clients = 10;
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
// Bind the source address
if( !socket_bind($sock, $address , 5000) )
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not bind socket : [$errorcode] $errormsg \n");
}
echo "Socket bind OK \n";
if(!socket_listen ($sock , 10))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
echo "Socket listen OK \n";
echo "Waiting for incoming connections... \n";
//array of client sockets
$client_socks = array();
//array of sockets to read
$read = array();
//start loop to listen for incoming connections and process existing connections
while (true)
{
//prepare array of readable client sockets
$read = array();
//first socket is the master socket
$read[0] = $sock;
//now add the existing client sockets
for ($i = 0; $i < $max_clients; $i++)
{
if($client_socks[$i] != null)
{
$read[$i+1] = $client_socks[$i];
}
}
//now call select - blocking call
if(socket_select($read , $write , $except , null) === false)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
//if ready contains the master socket, then a new connection has come in
if (in_array($sock, $read))
{
for ($i = 0; $i < $max_clients; $i++)
{
if ($client_socks[$i] == null)
{
$client_socks[$i] = socket_accept($sock);
//display information about the client who is connected
if(socket_getpeername($client_socks[$i], $address, $port))
{
echo "Client $address : $port is now connected to us. \n";
}
//Send Welcome message to client
$message = "Welcome to php socket server version 1.0 \n";
$message .= "Enter a message and press enter, and i shall reply back \n";
socket_write($client_socks[$i] , $message);
break;
}
}
}
//check each client if they send any data
for ($i = 0; $i < $max_clients; $i++)
{
if (in_array($client_socks[$i] , $read))
{
$input = socket_read($client_socks[$i] , 1024);
if ($input == null)
{
//zero length string meaning disconnected, remove and close the socket
unset($client_socks[$i]);
socket_close($client_socks[$i]);
}
$n = trim($input);
$output = "OK ... $input";
echo "Sending output to client \n";
//send response to client
socket_write($client_socks[$i] , $output." welcome any time");
}
}
}
Related
I am using php mail() (Via piped to program) and my goal is to simply get the email and scan the "from" header to filter it and then if it passes my "rules" or "checks" pass it along to the intended receiver. I have been able to use a sample code to get the mail and I can actually get my "test check" done. The problem I am having is that I cannot get the php mail() function to resend the mail as it was (plain or html). Every time i get my test mail, it comes with all the headers exposed and code. Not a nice and neat email. I also found out that I could encounter problems with this if there are attachments to the mail. I have seen alot of suggestions about going thru PHPMailer and I am willing to entertain that option. I just don't need this to get to complicated. here is the code I am using -
#!/usr/bin/php -q
<?php
$notify= 'myemail#mydomain.com'; // an email address required in case of errors
function mailRead($iKlimit = "")
{
if ($iKlimit == "") {
$iKlimit = 1024;
}
$sErrorSTDINFail = "Error - failed to read mail from STDIN!";
$fp = fopen("php://stdin", "r");
if (!$fp) {
echo $sErrorSTDINFail;
exit();
}
$sEmail = "";
if ($iKlimit == -1) {
while (!feof($fp)) {
$sEmail .= fread($fp, 1024);
}
} else {
while (!feof($fp) && $i_limit < $iKlimit) {
$sEmail .= fread($fp, 1024);
$i_limit++;
}
}
fclose($fp);
return $sEmail;
}
$email = mailRead();
$lines = explode("\n", $email);
$to = "";
$from = "";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;
for ($i=0; $i < count($lines); $i++) {
if ($splittingheaders) {
$headers .= $lines[$i]."\n";
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
$tst = substr($subject, -3);
if ($tst == "win" | $tst == "biz" | $tst == "net"){
$subject = $subject . "BAD ADDRESS";
}
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
if (preg_match("/^To: (.*)/", $lines[$i], $matches)) {
$to = $matches[1];
}
} else {
// not a header, but message
$message .= $lines[$i]."\n";
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$splittingheaders = false;
}
}
mail('noreply#mydomain.com', $subject, $message);
?>
I am interested in learning, I am code savvy. Somewhat new to email formatting, but very understanding of PHP. Any help is appreciated. Thanx.
The following code is example php code for socket tutorial, and I run successfully to collect remote site or localhost webpage.Either the protocol number I used for socket_create is 0 or 6, both
number is also working on that code, Why ? I thought network programming will needs to include TCP and IP for today's window computer together to make the communication possible. Why just need TCP or IP protocol num could make the program code working that doesn't include both protocol num ?
TCP is protocol for transport layer and IP is protocol for network layer for both OSI or classical TCP/IP model
<?php
$protocol = 'tcp';
$get_prot = getprotobyname($protocol);
echo $get_prot."----protocol\n";
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 6)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
if(!socket_connect($sock , '127.0.0.1' , 80))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not connect: [$errorcode] $errormsg \n");
}
echo "Connection established \n";
$message = "GET / HTTP/1.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 \r\n\r\n";
$message = "GET / HTTP/1.1\r\n";
$message .= "Host: \r\n";
$message .= "Connection: Close\r\n\r\n";
//Send the message to the server
if( ! socket_send ( $sock , $message , strlen($message) , 0))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not send data: [$errorcode] $errormsg \n");
}
echo "Message send successfully \n";
//Now receive reply from server
if(socket_recv ( $sock , $buf , 6144 , MSG_WAITALL ) === FALSE)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not receive data: [$errorcode] $errormsg \n");
}
//print the received message
echo $buf;
?>
Passing 0 as the protocol will give you a default protocol. AF_INET says you want
IP protocol suite (IPv4 specifically). For a combination of AF_INET and SOCK_STREAM, tcp is the default. A combination of AF_INET6 and SOCK_DGRAM would give you IPv6 and UDP as default.
TCP has the protocol number 6, which you can pass as well if you want to be explicit.
i have a problem with socket connections
i need multiple socket read with several clients but i can connect several clients but only can one socket_read for client, if i add second socket_read, the program doesnt work
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
$socket_bind($sock, $address , $port);
$socket_listen ($sock , 10)
while (true){
$read = array();
//first socket is the master socket
$read[0] = $sock;
//now add the existing client sockets
for ($i = 0; $i < $max_clients; $i++)
{
if($client_socks[$i] != null)
{
$read[$i+1] = $client_socks[$i];
}
}
//now call select - blocking call
if(socket_select($read , $write , $except , null) === false)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
//if ready contains the master socket, then a new connection has come in
if (in_array($sock, $read))
{
for ($i = 0; $i < $max_clients; $i++)
{
if ($client_socks[$i] == null)
{
$client_socks[$i] = socket_accept($sock);
//display information about the client who is connected
if(socket_getsockname($client_socks[$i], $address, $port))
{
echo "Client $i : $port . \n";
}
//Send Welcome message to client
$msg = "Bienvenido cliente {$key[0]} \n\r";
$msg .= "1.-Crear Paleta\n\r";
$msg .= "2.-Ubicar Paleta\n\r";
$msg .= "exz.-Salir\n\r";
socket_write($client_socks[$i] , $msg);
break;
}
}
}
//check each client if they send any data
for ($i = 0; $i < $max_clients; $i++)
{
if (in_array($client_socks[$i] , $read))
{
if (false === ($input = socket_read($client_socks[$i],PHP_NORMA))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
break 2;
}
echo "client $i : ";
echo "$input";
//send response to client
socket_write ($client_socks[$i], "client $i : ");
socket_write ($client_socks[$i], $input);
socket_write ($client_socks[$i], "\r");
$y++;
}
}
}
I am sending push notification in php I got "87" in result variable. what does it means.
<?php
$deviceToken = "a448b8946a5de3801dc6a11862a5a0bf11f1adc16xxxxxxxxxxxx"; // masked for security reason
// Passphrase for the private key
$pass = 'molik';
// Get the parameters from http get or from command line
$message = $_GET['message'] or $message = $argv[1] or $message = 'Test Message';
//$badge = (int)$_GET['badge'] or $badge = (int)$argv[2] or $badge = 1;
$sound = $_GET['sound'] or $sound = $argv[3] or $sound = 'default';
// Construct the notification payload
$body = array();
$body['aps'] = array('alert' => $message);
if ($badge)
$body['aps']['badge'] = $badge;
if ($sound)
$body['aps']['sound'] = $sound;
/* End of Configurable Items */
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
// assume the private key passphase was removed.
stream_context_set_option($ctx, 'ssl', 'passphrase', $pass);
// for production change the server to ssl://gateway.push.apple.com:219
$fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
if (!$fp) {
print "Failed to connect $err $errstr\n";
return;
}
else {
print "Connection OK\n";
}
$payload = json_encode($body);
$msg = chr(0) . pack("n",32) . pack('H*', $deviceToken) . pack("n",strlen($payload)) . $payload;
print "sending message :" . $payload . "\n";
$result=fwrite($fp, $msg);
echo ">>" .$result ."<<" . PHP_EOL;
fclose($fp);
OutPut
Connection OK
sending message :{"aps":{"alert":"Test Message","sound":"default"}}
>>87<<
In PHP fwrite returns the number of characters written, in this case the number of bytes written to your socket.
I wrote the below script to read the feedback data. But, for some reasons, I am not receiving any data from the server. Can you kindly let me know whats wrong with the script. Also, if you have any working php script for feedback service, can you kindly share it...
regards,
DD.
<?php
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
// Set time limit to indefinite execution
set_time_limit (0);
// Set the ip and port we will listen on
$address = 'ssl://feedback.sandbox.push.apple.com';
$port = 2196;
// Create a TCP Stream socket
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
echo "PHP Socket Server started at " . $address . " " . $port . "\n";
// Bind the socket to an address/port
socket_bind($sock, $address, $port) or die('Could not bind to address');
// Start listening for connections
socket_listen($sock);
//loop and listen
while (true) {
/* Accept incoming requests and handle them as child processes */
$client = socket_accept($sock);
// Read the input from the client – 1024 bytes
$input = socket_read($client, 1024);
}
// Close the client (child) socket
socket_close($client);
// Close the master sockets
socket_close($sock);
?>
You must act as a client, just like you're sending notification. That must be something like:
<?php
$certFile = 'apns-dev.pem';
while (true) {
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', $certFile);
//stream_context_set_option($ctx, 'ssl', 'passphrase', $this->certPass);
echo "try to open stream\n";
$fp = stream_socket_client('ssl://feedback.sandbox.push.apple.com:2196', $err, $errstr, 5, STREAM_CLIENT_CONNECT, $ctx);
if (!$fp) {
print "Failed to connect". $err . $errstr. "\n";
exit();
} else {
echo 'Connected to feedback sandbox...';
while (($in = fread($fp, 1024)) != EOF) {
echo 'read '. $in . "\n";
}
socket_close($fp);
fclose($fp);
}
sleep(2000);
}
?>