Suggestion : 8 million send request - php

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

Related

Running into ERR_CONNECTION_RESET when checking multiple links

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

how to make timer inside socket php

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...

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.

Loop "Addfriend" counting issue

I am having this below code, It is work perfectly. But am having a small issue messuring the "$username_index" count.
the main idea of my code is following:
having accounts.txt [92 lines] usernames:pass format.
having usernames.txt [99999 lines] usernames format.
It will login to account1, then it will add 95 usernames, then next account2 , then add next 95 usernames.
But some accounts are giving response "Too many add friends". In this case response, I will skip the account and go to next.
But below code will contiue to the next 95!, so its skip 95 from usernames!
I want it contiue adding where the left username from skipped account.
I want it as soon it will login to the next account AND CONTIUING ADD THE NEXT LINE OF USERNAMES! no need to jump to next 95 username to add!
Example how i want it:
login account1
add username1
add username2
ERROR APPEARS!
login account2
add username3
add username4
add username5
add username6
error appears!
login account3
add username7
add username8
etc..
Current Code:
$username_index = 0;
while(true) { // This is our while.. yes but this not for login()!
try {
$names = readFromFile("usernames.txt", 95, $username_index);
if(count($names) <= 0)
break;
sleep(1);
$fuckc = 0;
foreach($names as $name){
$ans = $API->addFriend($name);
$var_response = $ans->getMessage();
if (strpos($var_response, 'too many friends!') !== false) {
printf("[!] Too many friends!, Skipping account now.\n");
break;
}
if (strpos($var_response, 'Sorry') === false) {
$fuckc++;
printf("[+]" . "[" . date("h:i:s") . "]" . "[" . $fuckc . "] " . "response: " . $var_response . "\n");
//printf("[" . $fuckc . "] " . "response: " . $var_response . "\n");
}
//sleep(SLEEP_TIME);
}
$username_index += 95;
$API->logout();
//rotate_proxy();
$API = null;
//sleep(waiting);
//$results = $findFriends->getResults();
if (!isset($results) || count($results) == 0) {
if(!login()) die("Could not find a valid account.\n");
}
} catch(Exception $e){
echo $e->getMessage() . "\n";
if(!login()) die("Could not find a valid account.\n");
}
}
Edited again : the counter $username_index only increasse when $var_response is not "too many friends!" :
$username_index = 0;
while(true) { // This is our while.. yes but this not for login()!
try {
$names = readFromFile("usernames.txt", 95, $username_index);
if(count($names) <= 0)
break;
sleep(1);
$fuckc = 0;
foreach($names as $name){
$ans = $API->addFriend($name);
$var_response = $ans->getMessage();
if (strpos($var_response, 'too many friends!') !== false) {
printf("[!] Too many friends!, Skipping account now.\n");
break;
}
else $username_index++; //◄■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
if (strpos($var_response, 'Sorry') === false) {
$fuckc++;
printf("[+]" . "[" . date("h:i:s") . "]" . "[" . $fuckc . "] " .
"response: " . $var_response . "\n");
//printf("[" . $fuckc . "] " . "response: " . $var_response . "\n");
}
//sleep(SLEEP_TIME);
}
// $username_index += 95; //◄■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
$API->logout();
//rotate_proxy();
$API = null;
//sleep(waiting);
//$results = $findFriends->getResults();
if (!isset($results) || count($results) == 0) {
if(!login()) die("Could not find a valid account.\n");
}
} catch(Exception $e){
echo $e->getMessage() . "\n";
if(!login()) die("Could not find a valid account.\n");
}
}

Faster Rackspace cloud upload

I have used to the Rackspace API to upload files to the RackSpace cloud. But this method seems to be a little on the slow side. Is there a better or faster way to upload a file to the cloud(curl, http adapters, etc)?
I am currently uploading with PHP and using the provided API.
Here is my solution how to make it fast:
I'm uploading only missing files using simple PHP script below. Thanks to it I do it in just one click and in just a few seconds.
PHP source code:
function UploadMissingFilesToRackFileCDN($file_paths_to_upload, $b_force_upload = false)
{
include_once("cloudfiles.php");
// Connect to Rackspace
$username = cloudfile_username; // username
echo "Connecting to CDN..." . date("H:i:s") . "<br>"; ob_flush();
$key = cloudfile_api_key; // api key
$auth = new CF_Authentication($username, $key);
$auth->authenticate();
$conn = new CF_Connection($auth);
echo " Connected!" . date("H:i:s") . "<br>"; ob_flush();
// Get the container we want to use
$container_name = 'vladonai';//'test_container';
echo "Obtaining container $container_name..." . date("H:i:s") . "<br>"; ob_flush();
$container = $conn->get_container($container_name);
echo " The container is obtained." . date("H:i:s") . "<br>"; ob_flush();
if (!$b_force_upload)
{
echo "Receiving container objects list..." . date("H:i:s") . "<br>"; ob_flush();
$existing_object_names = $container->list_objects();
$existing_files_count = count($existing_object_names);
echo " Objects list obtained: $existing_files_count." . date("H:i:s") . "<br>"; ob_flush();
$existing_object_names_text .= "\r\n";
foreach ($existing_object_names as $obj_name)
{
$existing_object_names_text .= $obj_name . "\r\n";
}
}
// upload files to Rackspace
$uploaded_file_n = 0;
$skipped_file_n = 0;
$errors_count = 0;
foreach ($file_paths_to_upload as $localfile_path => $file_info)
{
$filename = basename($localfile_path);
if (!file_exists($localfile_path))
{
echo "<font color=red>Error! File $localfile_path doesn't exists!</font>" . date("H:i:s") . "<br>"; ob_flush();
$errors_count ++;
} else
if (is_dir($localfile_path))
{
//simply skip it
} else
if (strpos($existing_object_names_text, "\r\n" . $filename . "\r\n") !== false)
{
//file is already uploaded to CDN (at least file name is present there). Would be good to have date/size checked, but CDN api has no such feature
//echo "<font color=gray>Skipped file $localfile_path - it already exists!</font><br>"; ob_flush();
$skipped_file_n ++;
} else
{
echo "<font color=green>Uploading file $localfile_path (file #$uploaded_file_n)..." . date("H:i:s") . "</font><br>"; ob_flush();
try
{
$object = $container->create_object($filename);
$object->load_from_filename($localfile_path);
$uploaded_file_n ++;
}
catch (Exception $e)
{
echo "<font color=red>Error! Caught exception: ", $e->getMessage(), " on uploading file <strong>$localfile_path</strong>!</font>" . date("H:i:s") . "<br>"; ob_flush();
$errors_count ++;
}
}
// if ($uploaded_file_n >= 10)
// break;
}
echo "Done! $uploaded_file_n files uploaded. Disconnecting :)" . date("H:i:s") . "<br>"; ob_flush();
echo "Skipped files: $skipped_file_n<br>"; ob_flush();
if ($errors_count > 0)
echo "<font color=red>Erorrs: $errors_count</font><br>"; ob_flush();
}
function UploadChangedImagesToRackFileCDN($b_force_upload = false)
{
$exclude = array
(
'.',
'..',
'*.html',
'*.htm',
'*.php',
'*.csv',
'*.log',
'*.txt',
'*.cfg',
//'*sub/forum/files/*',
);
$files_array_images = get_dirlist("/var/www/html/vladonai.com/images/", '*', $exclude, false);
$files_array = array_merge(get_dirlist("/var/www/html/vladonai.com/js/", '*', $exclude, false), $files_array_images);
UploadMissingFilesToRackFileCDN($files_array, $b_force_upload);
}
function get_dirlist($path, $match = '*', $exclude = array( '.', '..' ), $b_short_path = true)
{
$result = array();
if (($handle = opendir($path)))
{
while (false !== ($fname = readdir($handle)))
{
$skip = false;
if (!empty($exclude))
{
if (!is_array($exclude))
{
$skip = fnmatch($exclude, $fname) || fnmatch($exclude, $path . $fname);
} else
{
foreach ($exclude as $ex)
{
if (fnmatch($ex, $fname) || fnmatch($ex, $path . $fname))
$skip = true;
}
}
}
if (!$skip && (empty($match) || fnmatch($match, $fname)))
{
$file_full_path_and_name = $path . $fname;
//echo "$file_full_path_and_name<br>";
$b_dir = is_dir($file_full_path_and_name);
$b_link = is_link($file_full_path_and_name);
$file_size = ($b_dir || $b_link) ? 0 : filesize($file_full_path_and_name);
$file_mod_time = ($b_dir || $b_link) ? 0 : filemtime($file_full_path_and_name);
$new_result_element = array();
if ($b_short_path)
$file_name = str_replace("/var/www/html/vladonai.com/", "", $file_full_path_and_name);//'[' . str_replace("/var/www/html/vladonai.com/", "", $file_full_path_and_name) . ']';
else
$file_name = $file_full_path_and_name;
$result[$file_name] = array();
$result[$file_name]['size'] = $file_size;
$result[$file_name]['modtime'] = $file_mod_time;
if ($b_dir && !$b_link)
{
//recursively enumerate files in sub-directories
$result = array_merge(get_dirlist($file_full_path_and_name . "/", $match, $exclude, $b_short_path), $result);
}
}
}
closedir($handle);
}
return $result;
}

Categories