stream_select error:Strict Standards - php

I create some socket with stream_socket_client(), and put them in a array named $sockets.
When I run the code, an error is coming:
Strict Standards: Only variables should be passed by reference in
D:\www\study\cl\s.php on line 63
Code:
while (count($sockets)) {
$read = $write = $sockets;
stream_select($read, $write, $e = null, $timeout); //line 63
if (count($read)) {
foreach ($read as $r) {
$id = array_search($r, $sockets);
$data = fgets($r, 1024);
echo $data;
if (strlen($data) == 0) {
if ($status[$id] == "in progress") {
$status[$id] = "failed to connect";
}
fclose($r);
unset($sockets[$id]);
} else {
$status[$id] .= $data;
}
}
foreach ($write as $w) {
$id = array_search($w, $sockets);
fwrite($w, "HEAD / HTTP/1.0rnHost: " . $host . "rnrn");
$status[$id] = "waiting for response";
}
} else {
foreach ($sockets as $id => $s) {
$status[$id] = "timed out " . $status[$id];
}
break;
}
}

This line:
stream_select($read, $write, $e = null, $timeout);
should be:
$e=null;
stream_select($read, $write, $e, $timeout);
While the first code will work, PHP will throw the E_STRICT message. I'm not sure why the PHP developers decided so.
However, you should check the return type of stream_select():
$ret = stream_select($read, $write, $e, $timeout);
if($ret === FALSE) {
die('Error: stream_select');
}
Once you are checking the return type, you can also use the silence operator #:
$ret = #stream_select($read, $write, $e = NULL, $timeout);
if($ret === FALSE) {
die('Error: stream_select');
}

Related

Checkmail function

I'm creating a method to validate if an email exists.
I need to do this:
Insert several emails in a spreadsheet, save and in the html page, through a function 'file.onchange = function', select this file to validate through this check:
<?php
define ('DEBUG_OK', false);
class CCheckMail
{
var $timeout = 10;
var $domain_rules = array ("aol.com", "bigfoot.com", "brain.net.pk", "breathemail.net",
"compuserve.com", "dialnet.co.uk", "glocksoft.com", "home.com",
"msn.com", "rocketmail.com", "uu.net", "yahoo.com", "yahoo.de");
function _is_valid_email ($email = "")
{ return preg_match('/^[.\w-]+#([\w-]+\.)+[a-zA-Z]{2,6}$/', $email); }
function _check_domain_rules ($domain = "")
{ return in_array (strtolower ($domain), $this->domain_rules); }
function execute ($email = "")
{
if (!$this->_is_valid_email ($email))
{ return false; }
$host = substr (strstr ($email, '#'), 1);
if ($this->_check_domain_rules ($host))
{ return false; }
$host .= ".";
if (getmxrr ($host, $mxhosts[0], $mxhosts[1]) == true)
{ array_multisort ($mxhosts[1], $mxhosts[0]); }
else
{
$mxhosts[0] = $host;
$mxhosts[1] = 10;
}
if (DEBUG_OK) { print_r ($mxhosts); }
$port = 25;
$localhost = $_SERVER['HTTP_HOST'];
$sender = 'info#' . $localhost;
$result = false;
$id = 0;
while (!$result && $id < count ($mxhosts[0]))
{
if (function_exists ("fsockopen"))
{
if (DEBUG_OK) { print_r ($id . " " . $mxhosts[0][$id]); }
if ($connection = fsockopen ($mxhosts[0][$id], $port, $errno, $error, $this->timeout))
{
fputs ($connection,"HELO $localhost\r\n"); // 250
$data = fgets ($connection,1024);
$response = substr ($data,0,1);
if (DEBUG_OK) { print_r ($data); }
if ($response == '2') // 200, 250 etc.
{
fputs ($connection,"MAIL FROM:<$sender>\r\n");
$data = fgets($connection,1024);
$response = substr ($data,0,1);
if (DEBUG_OK) { print_r ($data); }
if ($response == '2') // 200, 250 etc.
{
fputs ($connection,"RCPT TO:<$email>\r\n");
$data = fgets($connection,1024);
$response = substr ($data,0,1);
if (DEBUG_OK) { print_r ($data); }
if ($response == '2') // 200, 250 etc.
{
fputs ($connection,"data\r\n");
$data = fgets($connection,1024);
$response = substr ($data,0,1);
if (DEBUG_OK) { print_r ($data); }
if ($response == '2') // 200, 250 etc.
{ $result = true; }
}
}
}
fputs ($connection,"QUIT\r\n");
fclose ($connection);
if ($result) { return true; }
}
}
else
{ break; }
$id++;
}
return false;
}
}
?>
However, I am not able to create the structure to validate.
I had created an array with some emails inserted in it, however, it only validates when executing the page, if the emails are valid or not, example:
<?php
include ("CCheckMail.php");
$checkmail = new CCheckMail ();
$emails = array ("pedroiagobucci#gmail.com", "invalid#email.com", "setec#freemail.it", "thisdoesentexist#google.com");
foreach ($emails as $email)
{
if ($checkmail->execute ($email))
{ print ("Address $email exists!<br>"); }
else
{ print ("Address $email <strong>not</strong> exists!<br>"); }
}
?>
can you help me?

php to few arguments to my function when I call her 7.0

I have an error in my code when I compile :
Fatal error: Uncaught ArgumentCountError: Too few arguments to
function getData::QueryWhoisServer(), 0 passed in
C:\xampp\htdocs\testVisitor\index.php on line 19 and exactly 2
expected in C:\xampp\htdocs\testVisitor\Model\getData.php:72 Stack
trace: #0 C:\xampp\htdocs\testVisitor\index.php(19):
getData->QueryWhoisServer() #1 {main} thrown in
C:\xampp\htdocs\testVisitor\Model\getData.php on line 72
I know that since php 7.0 I need to pass argument but the argument are not recognize...
here is my code:
index.php :
require_Once('Model/getData.php');
require_Once('Controller/writeData.php');
$getData = new getData();
$writeData =new writeData();
$getData->get_ip();
$getData->LookupIP($domain);
$getData->ValidateIP($domain);
$getData->QueryWhoisServer();
if($domain && $pageEnCours != preg_match("#localhost/testVisitor/$#",$pageEnCours)) {
$domain = trim($domain);
if($getData->ValidateIP($domain)) {
$result = $getData->LookupIP($domain);
$writeData->write_domain($result);
}
else{
write_error();
};
}
echo $domain;
echo "cc";
and getData.php :
$urlPart1 = $_SERVER['HTTP_HOST'] ;
$urlPart2 = $_SERVER['REQUEST_URI'];
$pageEnCours = $urlPart1 .= $urlPart2;
$domain ='0.0.0.0';
class getData
{
// For the full list of TLDs/Whois servers see http://www.iana.org/domains/root/db/ and http://www.whois365.com/en/listtld/
/**
* Récupérer la véritable adresse IP d'un visiteur
*/
function get_ip() {
// IP si internet partagé
global $domain;
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
return $domain =$_SERVER['HTTP_CLIENT_IP'];
}
// IP derrière un proxy
elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
return $domain=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
// Sinon : IP normale
else {
return $domain=(isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '');
}
}
function LookupIP($ip) {
$whoisservers = array(
//"whois.afrinic.net", // Africa - returns timeout error :-(
//"whois.lacnic.net", // Latin America and Caribbean - returns data for ALL locations worldwide :-)
//"whois.apnic.net", // Asia/Pacific only
//"whois.arin.net", // North America only
//"whois.ripe.net" // Europe, Middle East and Central Asia only
);
$results = array();
foreach($whoisservers as $whoisserver) {
$result = QueryWhoisServer($whoisserver, $ip);
if ($result && !in_array($result, $results)) {
$results[$whoisserver] = $result;
}
}
$res = "RESULTS FOUND: " . count($results);
foreach($results as $whoisserver=>$result) {
$res .= "\n\n-------------\nLookup results for " . $ip . " from " . $whoisserver . " server:\n\n" . $result;
}
return $res;
}
function ValidateIP($ip) {
$ipnums = explode(".", $ip);
if(count($ipnums) != 4) {
return false;
}
foreach($ipnums as $ipnum) {
if(!is_numeric($ipnum) || ($ipnum > 255)) {
return false;
}
}
return $ip;
}
function QueryWhoisServer($whoisserver , $domain ) {
$port = 43;
$timeout = 10;
$fp = #fsockopen($whoisserver, $port, $errno, $errstr, $timeout) or die("Socket Error " . $errno . " - " . $errstr);
//if($whoisserver == "whois.verisign-grs.com") $domain = "=".$domain; // whois.verisign-grs.com requires the equals sign ("=") or it returns any result containing the searched string.
fputs($fp, $domain . "\r\n");
$out = "";
while(!feof($fp)){
$out .= fgets($fp);
}
fclose($fp);
$res = "";
if((strpos(strtolower($out), "error") === FALSE) && (strpos(strtolower($out), "not allocated") === FALSE)) {
$rows = explode("\n", $out);
foreach($rows as $row) {
$row = trim($row);
if(($row != '') && ($row{0} != '#') && ($row{0} != '%') && ($row != preg_match("#^netname|^descr|^country|^person|^address|^phone#",$row ))) {
$res .= $row."\n";
}
}
}
return $res;
}
}
Too few arguments to function getData::QueryWhoisServer(), 0 passed in C:\xampp\htdocs\testVisitor\index.php
$getData->QueryWhoisServer(); is not providing any arguments.
In your function :
function QueryWhoisServer($whoisserver , $domain ) {
$port = 43;
$timeout = 10;
$fp = #fsockopen($whoisserver, $port, $errno, $errstr, $timeout)
fputs($fp, $domain . "\r\n");
$fp need $whoisserver,$portand$timeout
The $port and $timeout are defined in the function
But you need to specify $whoisserver and the $domain (domain is used in fputs) when you call this function,
That will be something like :
$getData->QueryWhoisServer($whoisserver, $domain);
Also in your function
LookupIP($domain);
The result use the fucntion QueryWhoisServer, so try to get the $result

socket_select() not a valid socket

I got this error:
Warning: socket_select(): supplied argument is not a valid Socket resource in /volume1/web/is/xxxx/listen-new.php on line 12
PHP Warning: socket_select(): supplied argument is not a valid Socket resource in /volume1/web/is/xxxx/listen-new.php on line 12
this my snippet code
My code is:
$port = $this->port;
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($sock, 0, $port);
socket_listen($sock);
$this->clients[] = $sock;
$data = array();
while (true) {
$read = $this->clients;
$write = array(); //NULL
$except = array();//NULL
$sckt = socket_select($read, $write, $except, 0);
if($sckt === false){
echo "socket_select() failed, reason: " .
socket_strerror(socket_last_error()) . "\n";
}
elseif($sckt > 0) {
if (in_array($sock, $read)) {
$this->clients[] = $newsock = socket_accept($sock);
//var_dump($this->gps);
socket_write($newsock, "Connected\n");
//var_dump($this->gps);
/**try{
socket_getpeername($newsock, $ip); //error
echo "New client connected: {$ip}\n";
}
catch(Exception $e){
echo "error : $e->getMessage()\n";
}**/
$key = array_search($sock, $read);
unset($read[$key]);
}
foreach ($read as $read_sock) {
$data = #socket_read($read_sock, 2048);
if ($data === false) {
$gpsdisc = array_search($read_sock, array_column($this->gps, 'pid'));
$key = array_search($read_sock, $this->clients);
unset($this->clients[$key]);
unset($this->gps[$gpsdisc]);
echo "client disconnected.\n";
continue;
}
else{
$data = trim($data);
if (!empty($data)) {
var_dump($data);
$buf = bin2hex($data);
$start = substr($buf, 0,4);
if($start=="7878"){
$protocol = substr($buf, 6,2);
if($protocol=="01"){
$imei = substr($buf, 8,16);
$cariGPS = $this->cariGPS($imei);
if($cariGPS!=NULL){
$this->setGPS($imei,$read_sock,$cariGPS);
$reply = $this->authLogin($data);
$rep = hex2bin("$reply");
socket_write($read_sock, $rep, strlen($rep));
}
else
echo "$imei salah";
}
elseif($protocol=="15"){
//echo "$buf\n";
$this->reply($data);
}
elseif($protocol=="12"){
$hex12 = bin2hex($data);
//echo "$hex12\n";
}
else{
$hex12 = bin2hex($data);
echo "$hex12\n";
}
echo "$protocol\n";
}
else{
if($data=="where"){
//echo $data."\n";
$this->where($this->gps);
}
elseif($data=="quit"){
$gpsdisc = array_search($read_sock, array_column($this->gps, 'pid'));
unset($this->gps[$gpsdisc]);
socket_close($read_sock);
$key = array_search($read_sock, $this->clients);
unset($this->clients[$key]);
}
else{
echo "command not found\n";
}
}
}
}
}
}
}
socket_close($sock);
PS I also had to change $write = null and $except = null
Are there any solution for this?
It looks like you supplied only the server code but omitted the client code. Can you post the client code please? I guess the problem is there. With my test client (fyi I used socket_create) I cannot reproduce the problem you are reporting.
Also mine is php7 (if you are curious).
This may have some hints for you: Socket_read() says "not a valid resource"

Send php variable to above for preventing a loop

i have a script where i use die to prevent a function's continuous loop. But if i place this above the html, the html script will stop as well so i place it below the html but all the variables get echoed below the actual website. How can i make sure this get's echoed to the place where i want it to be and not below the website? Or is there a different way than using die? This is the code of the function:
function QueryWhoisServer($whoisserver, $domain) {
$port = 43;
$timeout = 5;
$errm = "<p1>No connection could be made</p1>";
$fp = #fsockopen($whoisserver, $port, $errno, $errstr, $timeout) or die($errm);
fputs($fp, $domain . "\r\n");
$out = "";
while (!feof($fp)) {
$out .= fgets($fp);
}
fclose($fp);
$res = "";
if((strpos(strtolower($out), "error") === FALSE) && (strpos(strtolower($out), "not allocated") === FALSE)) {
$rows = explode("\n", $out);
foreach($rows as $row) {
$row = trim($row);
if(($row != ':') && ($row != '#') && ($row != '%')) {
$res .= $row."<br>";
}
}
}
return $res;
}
The keyword break breaks out of any loop, just use it instead of die.
Beware if you have nested loops, as break will only exit the innermost loop. Oddly enough, in php you can use break(2) to break from two loops. I would refrain from doing that though.
die(); stops all PHP execution. It's rare that you'd actually want to do that.
Instead you should look at the try - catch construct and throwing and catching exceptions.
function QueryWhoisServer($whoisserver, $domain) {
try {
$port = 43;
$timeout = 5;
$errm = "<p1>No connection could be made</p1>";
$fp = #fsockopen($whoisserver, $port, $errno, $errstr, $timeout);
if (!fp) {
throw new Exception ("Couldn't open socket.");
}
//after the exception is thrown, the rest of this block will not execute.
fputs($fp, $domain . "\r\n");
$out = "";
while (!feof($fp)) {
$out .= fgets($fp);
}
fclose($fp);
$res = "";
if((strpos(strtolower($out), "error") === FALSE) && (strpos(strtolower($out), "not allocated") === FALSE)) {
$rows = explode("\n", $out);
foreach($rows as $row) {
$row = trim($row);
if(($row != ':') && ($row != '#') && ($row != '%')) {
$res .= $row."<br>";
}
}
}
return $res;
} catch (Exception $e) {
//this block will be executed if any Exception is caught, including the one we threw above.
//you can handle the error here or rethrow it to pass it up the execution stack.
return "";
}
}
PHP's Exceptions manual page
You can use a control variable to avoid infinite looping.
$end_condition = false;
while (!$end_condition)
{
//do the job
if (conditions/are/met)
{
$end_condition = true;
}
}

fopen on URL blocks script execution in PHP

I'm trying to open a non-blocking stream in PHP (5.3.2 & 5.4.4). I do the following:
$fp = fopen($url, 'r');
if ($fp === false)
return false;
print('stream opened'.PHP_EOL);
stream_set_blocking($fp, 0);
The url points to a php file:
<?php sleep(10); ?>
<html><body>Hello</body></html>
The problem is that fopen() seems to block before I am even able to setup the stream as non blocking. Indeed, the stream opened message is printed after 10 seconds and not directly.
When doing a fopen on a url, the HTTP headers are sent at that moment. Since no context has been defiened (and it is not possible to configure contexts with the non-blocking option), fopen waits for the http headers to be sent and blocks.
A workaround is to use fsockopen which only opens the tcp connecion and does nothing more. The drawback of this approach is that the HTTP request has to be created manually.
Here is an (optimizable) implementation that reads data from an url in a non blocking way.
function parse_http_url($url)
{
$parts = parse_url($url);
if ($parts === false) return false;
if (!isset($parts['scheme']))
$parts['scheme'] = 'http';
if ($parts['scheme'] !== 'http' && $parts['scheme'] !== 'https')
return false;
if (!isset($parts['port']))
$parts['port'] = ($parts['scheme'] === 'http') ? 80 : 443;
if(!isset($parts['path']))
$parts['path'] = '/';
$parts['uri'] = $parts['path'];
if (!empty($parts['query']))
$parts['uri'] .= '?'.$parts['query'];
return $parts;
}
function url_get_contents($url, $options = null) {
if(!($url_parts = parse_http_url($url))) return false;
$timeout = intval(#$options['http']['timeout']);
if (!($fp = fsockopen($url_parts['host'], $url_parts['port'], $errno, $errstr, $timeout))) return false;
stream_set_blocking($fp, 0);
if($timeout > 0) {
stream_set_timeout($fp, $timeout);
$sleep_time = (($timeout * 1000000) / 100); # 1% of timeout in ms
$stop_time = microtime(true) + $timeout;
} else {
$sleep_time = 10000; # 10 ms
}
if (!isset($options['http']['method'])) $options['http']['method'] = 'GET';
if (!isset($options['http']['header'])) $options['http']['header'] = '';
$request = "{$options['http']['method']} {$url_parts['uri']} HTTP/1.1\r\n{$options['http']['header']}\r\n";
if (fwrite($fp, $request) === false) {
fclose($fp);
return false;
}
$content = '';
$buff_size = 4096;
do {
$rd = fread($fp, $buff_size);
if ($rd === false) {
fclose($fp);
return false;
}
$content .= $rd;
$meta = stream_get_meta_data($fp);
if ($meta['eof']) {
fclose($fp);
if(empty($content)) return false;
// HTTP headers should be separated with \r\n only but lets be safe
$content = preg_split('/\r\n|\r|\n/', $content);
$resp = explode(' ', array_shift($content));
$code = isset($resp[1]) ? intval($resp[1]) : 0;
if ($code < 200 || $code >= 300) {
$message = isset($resp[2]) ? $resp[2] : 'Unknown error';
trigger_error("Error {$code} {$message}", E_USER_WARNING);
return false;
}
// Skip headers
while (!empty($content) && array_shift($content) !== '');
return implode("\n", $content);
}
if ($meta['timed_out']) {
fclose($fp);
return false;
}
if (isset($stop_time) && microtime(true) >= $stop_time) {
fclose($fp);
return false;
}
if ($meta['unread_bytes'] === 0) {
usleep($sleep_time);
}
} while(true);
}

Categories