I'm trying to send some data (text) to the current socket.
Previously making hand shake - OK.
Then send data from client (Chrome, latest version) - socket_recv receives it - OK.
Then I'm trying to write to the same socket what I just read by socket_recv using socket_write - NOTHING.
Any errors (checked using socket_last_error and the function returns TRUE). It seems like all OK.
But onmessage event on the client-side not firing. Silence...
Who used websockets in PHP, please help.
Client:
var host = "ws://192.168.0.100:5000/wbs_r1.php";
try {
var socket = new WebSocket(host);
message('<p class="event">Socket Status: ' + socket.readyState);
socket.onopen = function (msg) {
message('<p class="event">Socket Status: ' + socket.readyState + ' (open)');
console.log(socket);
console.log(msg);
}
socket.onmessage = function (msg) {
message('<p class="message">Received: ' + msg.data);
console.log(socket);
console.log(msg);
}
socket.onclose = function (msg) {
message('<p class="event">Socket Status: ' + socket.readyState + ' (Closed)');
console.log(socket);
console.log(msg);
}
socket.onerror = function (msg) {
message('Error: ');
console.log(socket);
console.log(msg);
}
} catch (exception) {
message('<p>Error' + exception);
console.log(exception);
}
Server:
header('Content-Type: text/plain; charset=utf-8');
set_time_limit(0);
error_reporting(E_ALL);
ob_implicit_flush(true);
$sockets = array();
$handshakes = array();
$sockets["wbs1"] = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($sockets["wbs1"], SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($sockets["wbs1"], "0.0.0.0", 5000);
socket_listen($sockets["wbs1"], 20);
socket_set_nonblock($sockets["wbs1"]);
echo $sockets["wbs1"] . "\n";
while(true) {
$changed_sockets = $sockets;
$num_sockets = socket_select($changed_sockets, $write = null, $exceptions = null, null);
//print_r($changed_sockets);
foreach($changed_sockets as $socket) {
echo "\n\n\n" . "Current socket: " . $socket . "\n";
if($socket == $sockets["wbs1"]) {
if(($client = socket_accept($sockets["wbs1"])) >= 0) $sockets[] = $client;
echo "Accepting socket ".$socket."\n";
echo "Client: " . $client . "\n";
} else {
$index = array_search($socket, $sockets);
$len = #socket_recv($socket, $buffer, 2048, 0);
echo "Received " . $len . " bytes from socket ".$socket.": " . $buffer . "\n";
if($len == 0) {
unset($sockets[$index]);
unset($handshakes[$index]);
socket_close($socket);
echo "Closing socket " . $socket . "\n";
} else if(!isset($handshakes[$index])) {
$buffer = substr($buffer, strpos($buffer, "Sec-WebSocket-Key: ") + 19);
$accept = base64_encode(sha1(substr($buffer, 0, strpos($buffer, "\r\n")) . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true));
$upgrade = "HTTP/1.1 101 Switching Protocols\r\n" .
"Upgrade: websocket\r\n" .
"Connection: Upgrade\r\n" .
"Sec-WebSocket-Accept: {$accept}\r\n\r\n" .
"Sec-Websocket-Extensions=x-webkit-deflate-frame". chr(0);
socket_write($socket, $upgrade, strlen($upgrade));
$handshakes[$index] = true;
echo "Handshaking: " . $socket . "\n";
} else {
$msg = "Hello!!!\n\0";
$wr = socket_write($socket,$msg);
if(!$wr) echo socket_strerror(socket_last_error()) . "\n";
else echo "Writing to socket " . $socket . "\n";
}
}
}
}
Related
I'm currently trying to figure out how to check for all available ports in the range 53000-53050. However, I cannot figure this out. I've tried out multiple responses, and in my case, I either got an error stating "(No connection could be made because the target machine actively refused it.)" using localhost as the host, or didn't load the page at all. Any ideas?
Thanks.
Short solution:
$host = 'stackoverflow.com';
$start = 53000;
$end = 53050;
for($port = $start; $port <= $end; $port++)
{
$connection = #fsockopen($host, $port);
if (is_resource($connection)) {
echo $host . ':' . $port . ' ' . '(' . getservbyport($port, 'tcp') . ') is open.' . PHP_EOL;
fclose($connection);
} else {
echo $host . ':' . $port . ' is not responding.' . PHP_EOL;
}
}
For PHP, please use fsockopen and getservbyport
<form method="post" >
Domain/IP:
<input type="text" name="domain" />
<input type="submit" value="Scan" />
</form>
<br />
<?php
if(!empty($_POST['domain'])) {
//list of port numbers to scan
// $ports = array(21, 22, 23, 25, 53, 80, 110, 1433, 3306);
/////////// Use this block to set start port and end port
$ports=array();
$i=53000;
while ($i <=53050){
array_push($ports, $i);
$i++;
}
/////////// end block
$results = array();
foreach($ports as $port) {
if($pf = #fsockopen($_POST['domain'], $port, $err, $err_string, 1)) {
$results[$port] = true;
fclose($pf);
} else {
$results[$port] = false;
}
}
foreach($results as $port=>$val) {
$prot = getservbyport($port,"tcp");
echo "Port $port ($prot): ";
if($val) {
echo "<span style=\"color:green\">OK</span><br/>";
}
else {
echo "<span style=\"color:red\">Inaccessible</span><br/>";
}
}
}
?>
I am trying to update an old script that uses PayPal to checkout. The $auth_token variable is equal to my business account's identity token.
if ($_REQUEST['do'] == 'receipt')
{
$request = 'cmd=_notify-synch';
$tx_token = $_REQUEST['tx'];
$auth_token = $configtoken;
$request .= "&tx=$tx_token&at=$auth_token";
$headerx .= "POST /cgi-bin/webscr HTTP/1.1\r\n";
$headerx .= "Content-Type: application/x-www-form-urlencoded\r\n";
$headerx .= "Host: www.paypal.com\r\n";
$headerx .= "Content-Length: " . strlen ($request) . "\r\n\r\n";
$sock = fsockopen('www.paypal.com', 80, $errno, $errstr, 30);
if (!$sock)
{
$file = fopen($config['log'] . $_REQUEST['tx'] . '.datatrans', "w", 0);
fputs($file, "HTTP ERROR\n");
fclose($file);
eval('$cartinfo .= "' . fetch_template('covercart_orderfailure') . '";');
} else
{
fputs($sock, $headerx . $request);
// read the body data
$result = '';
$headerdone = false;
while (!feof($sock))
{
$line = fgets($sock, 1024);
if (strcmp($line, "\r\n") == 0)
{
// read the header
$headerdone = true;
} else
if ($headerdone)
{
// header has been read. now read the contents
$result .= $line;
}
}
// parse the data
$lines = explode("\n", $result);
$keyarray = array();
if (!strcmp($lines[0], "SUCCESS") == 0)
{
$file = fopen($config['log'] . $_REQUEST['tx'] . '.datatrans', "w", 0);
fputs($file, "COULD NOT VALIDATE\n");
fclose($file);
eval('$cartinfo .= "' . fetch_template('covercart_orderfailure') . '";');
} else
{
for ($i = 1; $i < count($lines); $i++)
{
list($key, $val) = explode("=", $lines[$i]);
$keyarray[urldecode($key)] = urldecode($val);
}
$txn_id = $keyarray['txn_id'];
$item_name = $keyarray['item_name'];
$item_number = $keyarray['item_number'];
$payment_status = $keyarray['payment_status'];
$payer_email = $keyarray['payer_email'];
$product = explode("|", $item_number);
$item_array = explode("-", $product[1]);
$transamount = $_REQUEST['amt'];
$cm = urldecode($_REQUEST['cm']);
$transid = explode(":", $cm);
$transactionid = $transid[2];
$buyerid = $transid[0];
$transcookie = $transid[3];
$who = fetch_userinfo($buyerid);
$buyername = $who['username'];
$buyeremail = $who['email'];
$transamount = sprintf('%.2f', $transamount);
$mcgross = number_format(doubleval($_POST['mc_gross']), 2);
if ($item_name != 'renewal' and $transamount)
{
$verify = $db->query_first("SELECT amount FROM " . TABLE_PREFIX .
"covercartfraud WHERE transactionid='" . $transid[2] . "' AND userid='" . $buyerid .
"'");
if ($verify['amount'] <> $transamount)
{
$file = fopen($config['log'] . $_REQUEST['tx'] . '.datatrans', "w", 0);
fputs($file, "POSSIBLE FRAUD IP: " . $_SERVER['REMOTE_ADDR'] . " FROM PAYPAL: " .
$transamount . " VBCART TRANSACTION ID: " . $transid[2] . " USERID: " . $buyerid .
" FROM DB: " . $verify['amount'] . "\n");
fclose($file);
eval(standard_error(fetch_error('covercart_invalidamount')));
}
}
It goes on a little further, but I feel the part I need to focus on is right at the top. since that's where it communicates with PayPal.
When I submit to PayPal it sends me to https://www.paypal.com/webapps/shoppingcart/error?flowlogging_id=3986eaa08f5be&code=AMOUNT_ERROR and states Things don't appear to be working at the moment. Please try again later.
I have made the following changes, updating the headers and adding trim in 2 places (I thought were correct) yet I am still receiving this error when I attempt to checkout.
$headerx .= "POST /cgi-bin/webscr HTTP/1.1\r\n";
$headerx .= "Content-Length: " . strlen($request) . "\r\n";
$headerx .= "Content-Type: application/x-www-form-urlencoded\r\n";
$headerx .= "Host: www.paypal.com\r\n";
$headerx .= "Connection: close\r\n\r\n";
//$sock = fsockopen('www.paypal.com', 80, $errno, $errstr, 30);
$sock = fsockopen( 'tls://ipnpb.paypal.com', 443, $errno, $errstr, 30);
if (!$sock)
{
$file = fopen($config['log'] . $_REQUEST['tx'] . '.datatrans', "w", 0);
fputs($file, "HTTP ERROR\n");
fclose($file);
eval('$cartinfo .= "' . fetch_template('covercart_orderfailure') . '";');
} else
{
fputs($sock, $headerx . $request);
// read the body data
$result = '';
$headerdone = false;
while (!feof($sock))
{
$line = fgets($sock, 1024);
if (strcmp(trim($line), "\r\n") == 0)
{
// read the header
$headerdone = true;
} else
if ($headerdone)
{
// header has been read. now read the contents
$result .= $line;
}
}
// parse the data
$lines = explode("\n", $result);
$keyarray = array();
if (!strcmp(trim($lines[0]), "SUCCESS") == 0)
Where am I going wrong for the communication between my site and PayPal?
UPDATE:
I dug into the AMOUNT_ERROR I noticed in the url (which seemed suspicious) and discovered my input was submitting $1.00 when it needed to be sending 1.00 removing the $ allowed the process to go through.
It's very broad question, so my answer will be broad to.
From $request = 'cmd=_notify-synch'; until $lines = explode("\n", $result); it's an API call to PayPal. So maybe you can start by looking up that call in the PayPal documentation. And replace that peace of code by the PayPal PHP SDK. That library will contain information about authentication and I assume that will tell you where to put the client ID and secret.
I was coded a php bot. Now I want send a 8 million request. Yeah for example:
I use multi_curl* but problems.
I use linux parallels library problems.
Maybe you have any suggestions ?
Php 7.1.1 , Linux Ubuntu 16.0.1
myfnc(){
i=1264609
echo "$(($1+i))";
response=$(curl --write-out %{http_code} --silent --output /dev/null http://localhost/botum/index.php?i=$(($1+i)))
echo $response
}
export -f myfnc
seq 100 | parallel -j0 myfnc
Multi curl problems :
set_time_limit(0);
ini_set("max_execution_time",-1);
$nodes = array();
for($i =1366295;$i<1396296;$i++){
array_push($nodes,"http://165.227.152.138/botum2/index.php?i=$i");
}
$node_count = count($nodes);
$curl_arr = array();
$master = curl_multi_init();
for($i = 0; $i < $node_count; $i++)
{
$url =$nodes[$i];
//problems code start
$curl_arr[$i] = curl_init($url);
curl_setopt($curl_arr[$i], CURLOPT_RETURNTRANSFER, true);
//problems code end
curl_multi_add_handle($master, $curl_arr[$i]);
}
do {
curl_multi_exec($master,$running);
} while($running > 0);
for($i = 0; $i < $node_count; $i++)
{
$results[] = curl_multi_getcontent ( $curl_arr[$i] );
}
print_r($results);
your curl code is trying to start 1.3 million curl handles SIMULTANEOUSLY, and will obviously run out of resources (but you don't catch that because you don't check the return value of curl_init(), if you had done something like if(!($curl_arr[$i] = curl_init($url))){throw new \RuntimeException("curl_init failed!");} then you would have noticed it)
furthermore you're using a busy loop here
do {
curl_multi_exec($master,$running);
} while($running > 0);
meaning you'll be using 100% cpu while the handles are executing, for no goddamn reason, while you should have been waiting with curl_multi_select.
this is a job for curl_multi, but you're just using it wrong. my suggestion is to just slightly modify the code from Which performs faster, headless browser or Curl? ,
this will do 8 million requests, print the responses as they are getting completed, and never use more than 500 connections simultaneously, and use an async select() approach to not use any cpu while waiting for network IO,
curl_multi_fetch_and_print("http://165.227.152.138/botum2/index.php?i=",8000000,500,10000,true,true);
function curl_multi_fetch_and_print(string $base_url, int $count, int $max_connections, int $timeout_ms = 10000, bool $consider_http_300_redirect_as_error = true, bool $print_fault_reason): void
{
if ($max_connections < 1) {
throw new InvalidArgumentException("max_connections MUST be >=1");
}
if ($count < 1) {
throw new InvalidArgumentException("count MUST be >=1");
}
$mh = curl_multi_init();
$workers = array();
$work = function () use (&$workers, &$mh, &$print_fault_reason) {
// > If an added handle fails very quickly, it may never be counted as a running_handle
while (1) {
curl_multi_exec($mh, $still_running);
if ($still_running < count($workers)) {
break;
}
$cms = curl_multi_select($mh, 10);
//var_dump('sr: ' . $still_running . " c: " . count($workers)." cms: ".$cms);
}
while (false !== ($info = curl_multi_info_read($mh))) {
//echo "NOT FALSE!";
//var_dump($info);
{
if ($info['msg'] !== CURLMSG_DONE) {
continue;
}
if ($info['result'] !== CURLM_OK) {
if ($print_fault_reason) {
echo "request #" . ($workers[(int)$info['handle']]) . " error: " . print_r(array(false, $info['result'], "curl_exec error " . $info['result'] . ": " . curl_strerror($info['result'])), true) . PHP_EOL;
}
} elseif (CURLE_OK !== ($err = curl_errno($info['handle']))) {
if ($print_fault_reason) {
echo "request #" . ($workers[(int)$info['handle']]) . " error: " . print_r(array(false, $err, "curl error " . $err . ": " . curl_strerror($err)), true) . PHP_EOL;
}
} else {
$code = (string)curl_getinfo($info['handle'], CURLINFO_HTTP_CODE);
if ($code[0] === "3") {
if ($consider_http_300_redirect_as_error) {
if ($print_fault_reason) {
echo "request #" . ($workers[(int)$info['handle']]) . " error: " . print_r(array(false, -1, "got a http " . $code . " redirect, which is considered an error"), true) . PHP_EOL;
}
} else {
//if ($print_fault_reason) {
// echo "request #" . ($workers[(int)$info['handle']]) . " success: " . print_r(array(true, 0, "got a http " . $code . " redirect, which is considered a success"), true).PHP_EOL;
//} else {
// ... got a http redirect, which is not considered an errror,
echo "request #" . ($workers[(int)$info['handle']]) . " success: (http {$code} redirect)\n";
//}
}
} elseif ($code[0] === "2") {
if ($print_fault_reason) {
echo "request #" . ($workers[(int)$info['handle']]) . " success: http {$code}: " . curl_multi_getcontent($info['handle']) . PHP_EOL;
} else {
echo "request #" . ($workers[(int)$info['handle']]) . ": " . curl_multi_getcontent($info['handle']) . PHP_EOL;
}
} else {
// all non-2xx and non-3xx are always considered errors (500 internal server error, 400 client error, 404 not found, etcetc)
if ($print_fault_reason) {
echo "request #" . ($workers[(int)$info['handle']]) . " error: " . print_r(array(false, -1, "got a http " . $code . " code, which is considered an error"), true) . PHP_EOL;
}
}
}
curl_multi_remove_handle($mh, $info['handle']);
assert(isset($workers[(int)$info['handle']]));
unset($workers[(int)$info['handle']]);
curl_close($info['handle']);
}
}
//echo "NO MORE INFO!";
};
for ($i = 0; $i < $count; ++$i) {
$url = $base_url . $i;
while (count($workers) >= $max_connections) {
//echo "TOO MANY WORKERS!\n";
$work();
}
$neww = curl_init($url);
if (!$neww) {
trigger_error("curl_init() failed! probably means that max_connections is too high and you ran out of resources", E_USER_WARNING);
if ($print_fault_reason) {
echo "request #{$i} error: curl_init() failed!" . PHP_EOL;
}
continue;
}
$workers[(int)$neww] = $url;
curl_setopt_array($neww, array(
//CURLOPT_NOBODY => 1,
CURLOPT_RETURNTRANSFER=>1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_TIMEOUT_MS => $timeout_ms
));
curl_multi_add_handle($mh, $neww);
//curl_multi_exec($mh, $unused_here); LIKELY TO BE MUCH SLOWER IF DONE IN THIS LOOP: TOO MANY SYSCALLS
}
while (count($workers) > 0) {
//echo "WAITING FOR WORKERS TO BECOME 0!";
//var_dump(count($workers));
$work();
}
curl_multi_close($mh);
return;
}
this is the issue, i write a php socket, it work as a daemon, every time, and i have a client side, the client connect but every 30 seconds client automaticaly disconnect, it is happening because socket do not send himself a line (ka();) every 30 seconds, the (ka();) line is readed by the client and keep a constant conection, i have tried making a function inside the socket, so every 30 seconds write (ka();), but it does not work, it work wrong, it show the (ka();) if the client send something to the socket, if client side do not send anything the socket do not sent the anything.
the socket work has a daemon CLI windows and the client side is just javascript, when the socket is running, can be accesed directly by navigator and read what client send, if the client do not send anything, the socket need write the (ka();) line, so it is readed by client side and keep conection and so indefinitely.
this is the socket script
error_reporting(1);
ini_set('display_errors', '1');
define('CON_IP', '127.0.0.1');
define('CON_PORT', 1000);
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$max_clients = MAX_CLIENTS;
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socket, CON_IP, CON_PORT);
socket_listen($socket, $max_clients);
$clients = array(
'0' => array(
'socket' => $socket
)
);
echo "Server running....\n\n";
echo "Server Started on : " . date('Y-m-d H:i:s') . "\n";
echo "Listening on : " . CON_IP . " port " . CON_PORT . "\n";
echo ".... awaiting connections ...\n\n";
$session = (TRUE);
while ($session === TRUE) {
$read[0] = $socket;
for ($i = 1; $i < count($clients) + 1; ++$i) {
if ($clients[$i] != NULL) {
$read[$i + 1] = $clients[$i]['socket'];
}
}
$ready = socket_select($read, $write = NULL, $except = NULL, $tv_sec = NULL);
if (in_array($socket, $read)) {
for ($i = 1; $i < $max_clients + 1; ++$i) {
if (!isset($clients[$i])) {
$clients[$i]['socket'] = socket_accept($socket);
socket_getpeername($clients[$i]['socket'], $RemoteAddr, $RemotePort);
$clients[$i]['ipadd'] = $RemoteAddr . ':' . $RemotePort;
echo 'Incoming connection from ' . $clients[$i]['ipadd'] . "]\r\n";
break;
} elseif ($i == $max_clients - 1) {
echo 'Clients Overload!' . "\r\n";
}
if ($ready < 1) {
continue;
}
}
}
for ($i = 1; $i < $max_clients + 1; ++$i) {
if (in_array($clients[$i]['socket'], $read)) {
if (!$client[$i]['iframe']) {
$data = #socket_read($clients[$i]['socket'], 1024, PHP_BINARY_READ);
}
if (substr($data, 0, 3) == 'GET' || substr($data, 0, 4) == 'POST' || substr($data, 0, 4) == 'OPTI') {
$clients[$i]['iframe'] = true;
echo 'Incoming connection from browser [' . $clients[$i]['ipadd'] . "]\r\n";
socket_write($clients[$i]['socket'], "HTTP/1.1 200 OK\r\n");
socket_write($clients[$i]['socket'], "Content-Type: text/html; charset=utf-8;\r\n");
socket_write($clients[$i]['socket'], "Cache-Control: private\r\n\r\n");
for ($z = 0; $z < 4096; $z++)
$Brk = ("\n");
$html = ('<!DOCTYPE html>' . $Brk);
$html .= ('<html>' . $Brk);
$html .= ('<head>' . $Brk);
$html .= ('</head>' . $Brk);
$html .= ('<body>' . $Brk);
$html .= ('<script>' . $Brk);
$html .= ('function recv(packets){}' . $Brk);
$html .= ('</script>' . $Brk);
$html .= ('</body>' . $Brk);
socket_write($clients[$i]['socket'], $html);
} else {
if (trim($data) != '' && strlen(str_replace(' ', '', trim($data))) > 1) {
$msgs = ($data);
}
}
if ($data === FALSE) {
echo 'Incoming disconnection of ' . $clients[$i]['ipadd'] . "]\r\n";
unset($clients[$i]);
continue;
}
$data = trim($data);
if (!empty($data)) {
//LOGS
if ($msgs) {
$ClientDumpLog = fopen('log/InputToSocket.txt', "a");
fwrite($ClientDumpLog, "$msgs\n");
fclose($ClientDumpLog);
}
//
for ($j = 1; $j < $max_clients + 1; ++$j) {
if (isset($clients[$j]['socket']) and ($msgs !== NULL)) {
echo ('[' . $clients[$i]['ipadd'] . '] OK!' . "\r\n");
socket_write($clients[$j]['socket'], '<script>' . $msgs . "</script>\r\n");
}
}
break;
}
}
}
}
EDIT:
this solution, i think it was, but no, this code block, to test, writed after this line:
for ($j = 1; $j < $max_clients + 1; ++$j) {
$last_time = time();
while(true) {
if(time()-$last_time > 10) {
echo ('[' . $clients[$i]['ipadd'] . '] KA!' . "\r\n");
socket_write($clients[$j]['socket'], "ka();\r\n");
$last_time = time();
}
}
when i put this code, when the socket start, it show every (chosed time) in cli (KA!), when i access by navigator it show the (ka();) line too, but when the client side send something it never show, is like the (ka) line or what the client send, but no both at the same time.
somebody know some function or solution to make it work?
You have to override the maximum execution time setting of php.ini. You should not change it within php.ini - you rather should change it on top of your code:
<?php
set_time_limit(0);
//... your fancy code here...
First of all I am not sure if this the correct place to post about this particular problem because I don't know what the root cause is. If it isn't the right place, please say so and close the topic.
In a Windows Server 2012 64bit environment with 32GB RAM and an intel i7-4770, recently (last 4 months - before that it never happened) errors have started to appear in php_error.log with a totally random pattern as to when.
The errors say that functions or variables defined in other files included with require_once() do not exist. Once these errors start happening a reboot of the server machine "fixes" the issue. It takes a random amount of time for the problem to appear again, from 3 days to 10 days or 4 weeks. I have made disk checks for errors but nothing has come up
example1:
[21-Apr-2018 07:36:26 Asia/Kuwait] PHP Notice: Undefined variable: APPLICATIONDIRECTORY in C:\inetpub\wwwroot\ell\makeIdent.php on line 18
[21-Apr-2018 07:36:26 Asia/Kuwait] PHP Notice: Undefined variable: DLLDIR in C:\inetpub\wwwroot\ell\makeIdent.php on line 18
makeIdent.php:
require_once('dirpath.php');
if ( isset($_GET['GreekWord']) ) {
$curword = trim($_GET['GreekWord']);
$strRes = "";
if (strlen($curword) > 1) {
try {
$obj = new COM("Ellinognosia.ExtFunctions") or die("Unable to instantiate Ellinognosia");
$sid = 0;
$mdr = 0;
$output = $obj->fnInitialize("arxaia", $APPLICATIONDIRECTORY . "\\elllex", $DLLDIR, "utf8");
$output = $obj->fnIdentify($curword);
echo $output;
}
catch (Exception $e) {
$errmsg = $e->getMessage();
echo "Fatal error: " . $errmsg . " :internal error";
$logfile = fopen("error.log", "a");
if (flock($logfile, LOCK_EX)) {
fputs($logfile, date('d-m-Y') . " # " . date('H:i:s') . " # " . $_SERVER['REMOTE_ADDR'] . " # " . $_SERVER['HTTP_USER_AGENT'] . " # " . ($ref = (isset($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : "NO_REFERER") . " # " . $_SERVER['REQUEST_URI'] . " # " . $errmsg . " # " . "Variables:\r\n" . print_r($_POST, true) . " # " . print_r($_GET, true) . "\r\n\r\n");
flock($logfile, LOCK_UN);
fclose($logfile);
}
}
} else {
echo "Fatal error: Parameters Length Incorrect :internal error";
}
} else {
echo "Fatal error: Missing Parameters :internal error";
}
?>
dirpath.php:
<?php
date_default_timezone_set("Europe/Athens");
$APPLICATIONDIRECTORY = "C:\\inetpub\\wwwroot\\ell";
if (strpos(php_uname("v"), " R2 ") > 0 || strpos(php_uname("v"), "ild 92") > 0) {
$DLLDIR = "C:\\Windows\\SysWOW64";
} else {
$DLLDIR = $APPLICATIONDIRECTORY . "\\elldll";
}
?>
example2:
[21-Apr-2018 07:36:27 Asia/Kuwait] PHP Fatal error: Call to undefined function toMonotonic() in C:\inetpub\wwwroot\ell\ajaxGetWordsFromLet.php on line 15
ajaxGetWordsFromLet.php:
<?php
require_once('phpcommonscripts/functions/fn_application.php');
try {
if ( isset($_GET['Letters']) && isset($_GET['CurLex']) ) {
$letters = trim($_GET['Letters']);
$curlex = trim($_GET['CurLex']);
if (mb_strlen($letters, "UTF-8") > 2 && mb_strlen($curlex, "UTF-8") > 0) {
$strReturn = "";
if ($curlex == "newg" || $curlex == "arch" || $curlex == "phrases") {
$letters = mb_substr($letters, 0, 32, "UTF-8");
$letters = toMonotonic($letters);
$letters = RemoveSimeiaStiksisArx($letters);
// more irrelevant php code here, the error is 2 lines above
}
echo $strReturn;
} else {
echo "Fatal error: Parameters Length Incorrect :internal error";
}
} else {
echo "Fatal error: Missing Parameters :internal error";
}
}
catch(Exception $e) {
$errmsg = $e->getMessage();
echo "Fatal error: " . $errmsg . " :internal error";
$logfile = fopen("error.log", "a");
if (flock($logfile, LOCK_EX)) {
fputs($logfile, date('d-m-Y') . " # " . date('H:i:s') . " # " . $_SERVER['REMOTE_ADDR'] . " # " . $_SERVER['HTTP_USER_AGENT'] . " # " . ($ref = (isset($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : "NO_REFERER") . " # " . $_SERVER['REQUEST_URI'] . " # " . $errmsg . " # " . "Variables:\r\n" . print_r($_POST, true) . " # " . print_r($_GET, true) . "\r\n\r\n");
flock($logfile, LOCK_UN);
fclose($logfile);
}
}
?>
fn_application.php:
<?php
function toMonotonic($s) {
$s = str_replace(":α", "ά", $s);
$s = str_replace(":ε", "έ", $s);
$s = str_replace(":η", "ή", $s);
$s = str_replace(":ι", "ί", $s);
$s = str_replace(":ο", "ό", $s);
$s = str_replace(":υ", "ύ", $s);
$s = str_replace(":ω", "ώ", $s);
$s = str_replace(":ϊ", "ΐ", $s);
$s = str_replace(":ϋ", "ΰ", $s);
$s = str_replace(":Α", "Ά", $s);
$s = str_replace(":Ε", "Έ", $s);
$s = str_replace(":Η", "Ή", $s);
$s = str_replace(":Ι", "Ί", $s);
$s = str_replace(":Ο", "Ό", $s);
$s = str_replace(":Υ", "Ύ", $s);
$s = str_replace(":Ω", "Ώ", $s);
$s = str_replace(":Ϊ", "Ϊ", $s);
$s = str_replace(":Ϋ", "Ϋ", $s);
return $s;
}
// more functions here
?>
example3:
[21-Apr-2018 07:36:27 Asia/Kuwait] PHP Notice: Undefined variable: LGCACHEPDO in C:\inetpub\wwwroot\ell\displayOmor.php on line 38
[21-Apr-2018 07:36:27 Asia/Kuwait] PHP Fatal error: Call to undefined function getCache() in C:\inetpub\wwwroot\ell\displayOmor.php on line 39
displayOmor.php:
<?php
require_once('dirpath.php');
require_once("phpcommonscripts/connections/con_cache.php");
require_once("phpcommonscripts/functions/cache.php");
function get_data($url) {
$ch = curl_init();
$timeout = 100;
$userAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)";
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function mb_ucfirst($str, $enc = 'utf-8') {
return mb_strtoupper(mb_substr($str, 0, 1, $enc), $enc).mb_substr($str, 1, mb_strlen($str, $enc), $enc);
}
if ( isset($_GET['GreekWord']) && isset($_GET['selectedRes']) ) {
$curword = trim($_GET['GreekWord']);
$selres = trim($_GET['selectedRes']);
$strRes = "";
if (strlen($curword) > 1 && strlen($selres) > 0) {
try {
$cacheoutput = "";
$useCache = true;
if ($LGCACHEPDO === null) $useCache = false;
$cacheoutput = getCache($useCache, $_SERVER['QUERY_STRING'], $_POST, pathinfo(__FILE__, PATHINFO_FILENAME));
if ($cacheoutput != "") {
$output = $cacheoutput;
} else {
//more code
}
$strRes = $output;
echo $strRes;
}
catch (Exception $e) {
$errmsg = $e->getMessage();
echo "Fatal error: " . $errmsg . " :internal error";
$logfile = fopen("error.log", "a");
if (flock($logfile, LOCK_EX)) {
fputs($logfile, date('d-m-Y') . " # " . date('H:i:s') . " # " . $_SERVER['REMOTE_ADDR'] . " # " . $_SERVER['HTTP_USER_AGENT'] . " # " . ($ref = (isset($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : "NO_REFERER") . " # " . $_SERVER['REQUEST_URI'] . " # " . $errmsg . " # " . "Variables:\r\n" . print_r($_POST, true) . " # " . print_r($_GET, true) . "\r\n\r\n");
flock($logfile, LOCK_UN);
fclose($logfile);
}
}
} else {
echo "Fatal error: Parameters Length Incorrect :internal error";
}
} else {
echo "Fatal error: Missing Parameters :internal error";
}
?>
con_cache.php:
<?php
//Cache
$hostname_LGCACHE = "127.0.0.1";
$database_LGCACHE = "xxx";
$username_LGCACHE = "xxx";
$password_LGCACHE = "xxx";
$errorreporting = error_reporting();
try {
error_reporting(E_ALL ^ E_WARNING);
$LGCACHEPDO = new PDO("mysql:host=".$hostname_LGCACHE.";dbname=".$database_LGCACHE, $username_LGCACHE, $password_LGCACHE, array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING, PDO::ATTR_TIMEOUT => 2));
} catch (PDOException $ex) {
$LGCACHEPDO = null;
}
error_reporting($errorreporting);
?>
cache.php:
<?php
$gl_TBLNAME = "";
$gl_QUERYSTRING = "";
function getCache($useCache, $serverQUERYSTRING, $serverPOST, $serverFILENAME) {
$ret = "";
if ($useCache === true) {
global $LGCACHEPDO;
global $gl_TBLNAME;
global $gl_QUERYSTRING;
$gl_QUERYSTRING = $serverQUERYSTRING;
if ($gl_QUERYSTRING == "") {
foreach ($serverPOST as $key => $value) $gl_QUERYSTRING = $gl_QUERYSTRING . $key . "=". urlencode($value) . "&";
$gl_QUERYSTRING = rtrim($gl_QUERYSTRING, "&");
}
$gl_TBLNAME = $serverFILENAME;
$getcache_PRST = $LGCACHEPDO->prepare("SELECT output FROM " . $gl_TBLNAME . " WHERE querystring = :querystring");
$getcache_PRST->bindValue(":querystring", $gl_QUERYSTRING);
$getcache_PRST->execute() or die($LGCACHEPDO->errorInfo());
if ($getcache_PRST->rowCount() == 1) {
$getcache_RSLT = $getcache_PRST->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT);
$ret = $getcache_RSLT["output"];
}
}
return $ret;
}
// more functions here
?>
What I understand is that for some reason PHP or Windows fails some times to load those files.
We have had this server box for ~4 years and only recently started to show these problems. This server handles 70% of the website load and runs a MYSQL server (the website load is ~80% of what it was a year ago, so no it hasn't gone up). There is a same hardware second machine which has Windows Server 2012 R2 64bit which handles 30% of the load and doesn't run any MYSQL server and never shows these kind of problems. Both servers have PHP 5.3.28
Any ideas and help on what to do to pinpoint the issue would be welcome. Thank you in advance.