IP Blacklist lookup with PHP - php

I am trying to count the number of hits an IP occur in the array function "dnsblookup". If the IP occurs three times, it should echo "3|10", where 10 is the total number of blacklist database in the array. My code returns "1|10" for every IP even if it occurs more than once in the blacklist database in the array. I do not know where I made the mistake. I need help to complete this project. Thank you. I put multiple asterisks (*) before the exact code I am having issues with.
<?php
function dnsbllookup($ip)
{
$dnsbl_lookup = array (
"dnsbl-1.uceprotect.net","all.s5h.net","wormrbl.imp.ch",
"dnsbl-2.uceprotect.net","blacklist.woody.ch",
"dnsbl-3.uceprotect.net","combined.abuse.ch","dnsbl.spfbl.net",
"dnsbl.dronebl.org","http.dnsbl.sorbs.net");
$list = "";
if ($ip) {
$reverse_ip = implode(".", array_reverse(explode(".", $ip)));
foreach ($dnsbl_lookup as $host) {
if (checkdnsrr($reverse_ip . "." . $host . ".", "A")) {
$list .= implode(".", array_reverse(explode(".",$reverse_ip))) . ' <font color="red">
<strong>is Listed in </strong></font>'. $host . '<br />';
}
}
}
if (empty($list)) {
echo 'No record was not found in the IP blacklist database for: '.$ip;
echo $list;
echo "<br>";
echo "0";
echo "|";
echo count($dnsbl_lookup);
********************
} else {
$list1 = explode(" ", $list);
echo ($list);
echo "<br>";
echo "Blacklisted: ".count($list1);
echo "|";
echo count($dnsbl_lookup);
}
}

You should reduce the complexity and use string interpolation for easier reading and debugging.
function dnsbllookup($ip)
{
$dnsbl_lookup =
[
'dnsbl-1.uceprotect.net', 'all.s5h.net', 'wormrbl.imp.ch',
'dnsbl-2.uceprotect.net', 'blacklist.woody.ch',
'dnsbl-3.uceprotect.net', 'combined.abuse.ch', 'dnsbl.spfbl.net',
'dnsbl.dronebl.org', 'http.dnsbl.sorbs.net'
];
$dns_count = count($dnsbl_lookup);
$list = [];
if ($ip)
{
$reverse_ip = implode(".", array_reverse(explode(".", $ip)));
foreach ($dnsbl_lookup as $host)
if (checkdnsrr("$reverse_ip.$host.", "A"))
$list[] = "$ip <font color=\"red\"><strong>is Listed in </strong></font> $host<br />\n";
}
$list_count = count($list);
if (0 === $list_count)
echo "No record was not found in the IP blacklist database for: $ip<br>\n";
else
{
$list_str = implode(" ", $list);
echo "$list_str<br>\nBlacklisted: $list_count<br>\n";
}
echo "$list_count|$dns_count\n";
}
dnsbllookup('54.201.153.20'); // 3 entries
dnsbllookup('185.12.225.17'); // 1 entry

Related

Using preg_grep to find match

I need server to return complete IDs that contain an integer(single digit or more) sent in by a user to find a match.
e.g I submit '5678', then server returns 12567891, 54356782, 90567811.
Emphasis on '5678'. My code returns no results.
<?php
$per = array(456755643, 78567561, 443321, 33267554560, 44321122, 554367533, 3390);
$thr = 675;
if(isset($_POST['search'])){
$jake = preg_grep(("/$thr+/", $per);
foreach($jake as $value){
print $value . br;
}
}
?>
try this
$per = array(456755643, 78567561, 443321, 33267554560, 44321122, 554367533, 3390);
$thr = 675;
$jake = preg_grep("/$thr/", $per);
foreach($jake as $value){
print $value . '<br>';
}
//result
456755643
78567561
33267554560
554367533

Show error when url isnt allowed list?

if $text isnt allowed list print error. Dont know how do do it
$allowedDomains = array('www.test1.com', 'www.test2.co.uk', 'test3.com');
$text = 'this is my url www.abcd.com/index.php?page=home';
try like this
$allowedDomains = array('www.test1.com', 'www.test2.co.uk', 'test3.com');
if ( !in_array('your-domain-name', $allowedDomains) {
echo 'show your error here';
} else {
echo 'do what ever you want here';
}
Here's another way of doing it: create a regex using the list of domains, and then use that to test your text strings.
$allowedDomains = array('www.test1.com', 'www.test2.co.uk', 'test3.com');
# concatenate the allowed domains with | and surround with brackets so the regex will
# match any of the array items
# i.e. $regex is (www.test1.com|www.test2.co.uk|test3.com)
$regex = "(" . implode("|", $allowedDomains) . ")";
# a couple of test strings
$texts = array('this is my url www.abcd.com/index.php?page=home',
'my home page is www.test3.com');
foreach ($texts as $t) {
if (preg_match("/$regex/", $t)) {
echo "Found a match! $t\n";
}
else {
echo "No match found: $t\n";
}
}
Output:
No match found: this is my url www.abcd.com/index.php?page=home
Found a match! my home page is www.test3.com
I've written a function for you that'll allow you to add / remove domain names and / or domain extensions as you please, taking into account that not everyone types "http(s)" and / or "www" into their domain searches and also the unpredictability of what kind of information might be behind the domain or not:
<?php
function testDomain($domain){
//Set domain names
$arrDomainNames = array("test1","test2","test3");
//Set domain extensions like .com .co .info
//Do NOT add .co.uk! .uk is taken care of in the regex
$arrDomainExt = array("com","co");
$cntDomainNames = count($arrDomainNames);
$cntDomainExt = count($arrDomainExt);
$i = 0;
$y = 0;
$DomNames = "";
$DomExt = "";
foreach($arrDomainNames as $value){
if($i == $cntDomainNames - 1){
$DomNames .= $value;
} else {
$DomNames .= $value ."|";
}
$i++;
}
unset($value);
foreach($arrDomainExt as $value){
if($y == $cntDomainExt - 1){
$DomExt .= $value;
} else {
$DomExt .= $value ."|";
}
$y++;
}
unset($value);
$pattern = "/((((http|ftp|https)+(:)+(\/{2})))?+(www\.)?(((". $DomNames .")+\.)+(". $DomExt .")+(\.uk)?(:[0-9]+)?((\/([~0-9a-zA-Z\#\+\%#\.\/_-]+))?(\?[0-9a-zA-Z\+\%#\/&\[\];=_-]+)?)?))\b/imu";
if(preg_match($pattern, $domain)){
echo "Domain match!<br />";
} else {
echo "Domain not match!<br />";
}
}
testDomain("www.test1.com"); //match
testDomain("test1.com"); //match
testDomain("http://www.test1.co.uk"); //match
testDomain("test1.com/info.php?who=you"); //match
testDomain("www.google.com"); //no match
?>
How to make it working with
$arrDomainNames = array("test1.com","test2.org","test3.co.uk","test3.net");
without
$arrDomainExt = array("com","co");

Sorting strings, in a function, is my logic faulty or?

i need to sort some strings and match them with links, this is what i do:
$name_link = $dom->find('div[class=link] strong');
Returns array [0]-[5] containing strings such as NowDownload.eu
$code_link = $dom->find('div[class=link] code');
Returns links that match the names from 0-5, as in link [0] belongs to name [0]
I do not know the order in which they are returned, NowDownload.Eu, could be $code_link[4] or $code_link [3], but the name array will match it in order.
Now, i need $code_link[4] // lets say its NowDownload.Eu to become $link1 every time
so i do this
$i = 0;
while (!empty($code_link[$i]))
SortLinks($name_link, $code_link, $i); // pass all links and names to function, and counter
$i++;
}
function SortLinks($name_link, $code_link, &$i) { // counter is passed by reference since it has to increase after the function
$string = $name_link[$i]->plaintext; // name_link is saved as string
$string = serialize($string); // They are returned in a odd format, not searcheble unless i serialize
if (strpos($string, 'NowDownload.eu')) { // if string contains NowDownload.eu
$link1 = $code_link[$i]->plaintext;
$link1 = html_entity_decode($link1);
return $link1; // return link1
}
elseif (strpos($string, 'Fileswap')) {
$link2 = $code_link[$i]->plaintext;
$link2 = html_entity_decode($link2);
return $link2;
}
elseif (strpos($string, 'Mirrorcreator')) {
$link3 = $code_link[$i]->plaintext;
$link3 = html_entity_decode($link3);
return $link3;
}
elseif (strpos($string, 'Uploaded')) {
$link4 = $code_link[$i]->plaintext;
$link4 = html_entity_decode($link4);
return $link4;
}
elseif (strpos($string, 'Ziddu')) {
$link5 = $code_link[$i]->plaintext;
$link5 = html_entity_decode($link5);
return $link5;
}
elseif (strpos($string, 'ZippyShare')) {
$link6 = $code_link[$i]->plaintext;
$link6 = html_entity_decode($link6);
return $link6;
}
}
echo $link1 . '<br>';
echo $link2 . '<br>';
echo $link3 . '<br>';
echo $link4 . '<br>';
echo $link5 . '<br>';
echo $link6 . '<br>';
die();
I know they it finds the link, i have tested it before, but i wanted to make it a function, and it messed up, is my logic faulty or is there an issue with the way i pass the variables/ararys ?
I don't know why you pass $i as reference since you use it just for reading it. You could return an array contaning the named links and using it like so :
$all_links = SortLinks($name_link,$code_link);
echo $all_links['link1'].'<br/>';
echo $all_links['link2'].'<br/>';
You will have to put your loop inside the function, not outside.

Basic PHP loop RBL checker array

I am trying to create a basic RBL checker in PHP, I can't seem to get the IP to be added on the end of the url with out error. I am not the best with PHP.
list.inc is just a list of IPs to check each IP is on a new line.
<?
$ips = file("list.inc");
foreach($ips as $ip)
{
$rblurl = 'http://rbl-check.org/rbl_api.php?ipaddress=' . $ip;
//$rblcheckurl = $rblurl . $ip;
$boom = fopen($rblurl, "r");
//print "<pre>";
//print_r($boom);
//print "</pre>";
$rbl = stream_get_contents($boom);
echo "</br>";
$data = explode(";",$rbl);
print_r($data);
echo "</br>";
fclose($boom);
}
?>
Any help would be great!
The values returned by file() include the newline at the end of each line, you need to remove them before appending them to the URL:
foreach ($ips as $ip) {
$rblurl = 'http://rbl-check.org/rbl_api.php?ipaddress=' . trim($ip);
...
}

parsing .srt files

1
00:00:00,074 --> 00:00:02,564
Previously on Breaking Bad...
2
00:00:02,663 --> 00:00:04,393
Words...
i need to parse srt files with php and print the all subs in the file with variables.
i couldn't find the right reg exps. when doing this i need to take the id, time and the subtitle variables. and when printing there musn't be no array() s or etc. must print just the same as in the orginal file.
i mean i must print like;
$number <br> (e.g. 1)
$time <br> (e.g. 00:00:00,074 --> 00:00:02,564)
$subtitle <br> (e.g. Previously on Breaking Bad...)
by the way i have this code. but it doesn't see the lines. it must be edited but how?
$srt_file = file('test.srt',FILE_IGNORE_NEW_LINES);
$regex = "/^(\d)+ ([\d]+:[\d]+:[\d]+,[\d]+) --> ([\d]+:[\d]+:[\d]+,[\d]+) (\w.+)/";
foreach($srt_file as $srt){
preg_match($regex,$srt,$srt_lines);
print_r($srt_lines);
echo '<br />';
}
Here is a short and simple state machine for parsing the SRT file line by line:
define('SRT_STATE_SUBNUMBER', 0);
define('SRT_STATE_TIME', 1);
define('SRT_STATE_TEXT', 2);
define('SRT_STATE_BLANK', 3);
$lines = file('test.srt');
$subs = array();
$state = SRT_STATE_SUBNUMBER;
$subNum = 0;
$subText = '';
$subTime = '';
foreach($lines as $line) {
switch($state) {
case SRT_STATE_SUBNUMBER:
$subNum = trim($line);
$state = SRT_STATE_TIME;
break;
case SRT_STATE_TIME:
$subTime = trim($line);
$state = SRT_STATE_TEXT;
break;
case SRT_STATE_TEXT:
if (trim($line) == '') {
$sub = new stdClass;
$sub->number = $subNum;
list($sub->startTime, $sub->stopTime) = explode(' --> ', $subTime);
$sub->text = $subText;
$subText = '';
$state = SRT_STATE_SUBNUMBER;
$subs[] = $sub;
} else {
$subText .= $line;
}
break;
}
}
if ($state == SRT_STATE_TEXT) {
// if file was missing the trailing newlines, we'll be in this
// state here. Append the last read text and add the last sub.
$sub->text = $subText;
$subs[] = $sub;
}
print_r($subs);
Result:
Array
(
[0] => stdClass Object
(
[number] => 1
[stopTime] => 00:00:24,400
[startTime] => 00:00:20,000
[text] => Altocumulus clouds occur between six thousand
)
[1] => stdClass Object
(
[number] => 2
[stopTime] => 00:00:27,800
[startTime] => 00:00:24,600
[text] => and twenty thousand feet above ground level.
)
)
You can then loop over the array of subs or access them by array offset:
echo $subs[0]->number . ' says ' . $subs[0]->text . "\n";
To show all subs by looping over each one and displaying it:
foreach($subs as $sub) {
echo $sub->number . ' begins at ' . $sub->startTime .
' and ends at ' . $sub->stopTime . '. The text is: <br /><pre>' .
$sub->text . "</pre><br />\n";
}
Further reading: SubRip Text File Format
Group the file() array into chunks of 4 using array_chunk(), then omit the last entry, since it's a blank line like this:
foreach( array_chunk( file( 'test.srt'), 4) as $entry) {
list( $number, $time, $subtitle) = $entry;
echo $number . '<br />';
echo $time . '<br />';
echo $subtitle . '<br />';
}
That is not going to match because your $srt_file array might look like this:
Array
([0] => '1',
[1] => '00:00:00,074 --> 00:00:02,564',
[2] => 'Previously on Breaking Bad...'.
[3] => '',
[4] => '2',
...
)
Your regex isn't going to match any of those elements.
If your intent is to read the entire file into one long memory-hog-of-a-string then use file_get_contents to get the entire file contents into one string. then use a preg_match_all to get all the regex matches.
Otherwise you might try to loop through the array and try to match various regex patterns to determine if the line is an id, a time range, or text and do thing appropriately. obviously you might also want some logic to make sure you are getting values in the right order (id, then time range, then text).
I made a class to convert a .srt file to array.
Each entry of the array has the following properties:
id: a number representing the id of the subtitle (2)
start: float, the start time in seconds (24.443)
end: float, the end time in seconds (27.647)
startString: the start time in human readable format (00:00:24.443)
endString: the end time in human readable format (00:00:24.647)
duration: the duration of the subtitle, in ms (3204)
text: the text of the subtitle (the Peacocks ruled over Gongmen City.)
The code is php7:
<?php
namespace VideoSubtitles\Srt;
class SrtToArrayTool
{
public static function getArrayByFile(string $file): array
{
$ret = [];
$gen = function ($filename) {
$file = fopen($filename, 'r');
while (($line = fgets($file)) !== false) {
yield rtrim($line);
}
fclose($file);
};
$c = 0;
$item = [];
$text = '';
$n = 0;
foreach ($gen($file) as $line) {
if ('' !== $line) {
if (0 === $n) {
$item['id'] = $line;
$n++;
}
elseif (1 === $n) {
$p = explode('-->', $line);
$start = str_replace(',', '.', trim($p[0]));
$end = str_replace(',', '.', trim($p[1]));
$startTime = self::toMilliSeconds(str_replace('.', ':', $start));
$endTime = self::toMilliSeconds(str_replace('.', ':', $end));
$item['start'] = $startTime / 1000;
$item['end'] = $endTime / 1000;
$item['startString'] = $start;
$item['endString'] = $end;
$item['duration'] = $endTime - $startTime;
$n++;
}
else {
if ($n >= 2) {
if ('' !== $text) {
$text .= PHP_EOL;
}
$text .= $line;
}
}
}
else {
if (0 !== $n) {
$item['text'] = $text;
$ret[] = $item;
$text = '';
$n = 0;
}
}
$c++;
}
return $ret;
}
private static function toMilliSeconds(string $duration): int
{
$p = explode(':', $duration);
return (int)$p[0] * 3600000 + (int)$p[1] * 60000 + (int)$p[2] * 1000 + (int)$p[3];
}
}
Or check it out here: https://github.com/lingtalfi/VideoSubtitles
You can use this project: https://github.com/captioning/captioning
Sample code:
<?php
require_once __DIR__.'/../vendor/autoload.php';
use Captioning\Format\SubripFile;
try {
$file = new SubripFile('your_file.srt');
foreach ($file->getCues() as $line) {
echo 'start: ' . $line->getStart() . "<br />\n";
echo 'stop: ' . $line->getStop() . "<br />\n";
echo 'startMS: ' . $line->getStartMS() . "<br />\n";
echo 'stopMS: ' . $line->getStopMS() . "<br />\n";
echo 'text: ' . $line->getText() . "<br />\n";
echo "=====================<br />\n";
}
} catch(Exception $e) {
echo "Error: ".$e->getMessage()."\n";
}
Sample output:
> php index.php
start: 00:01:48,387<br />
stop: 00:01:53,269<br />
startMS: 108387<br />
stopMS: 113269<br />
text: ┘ç┘à╪د┘ç┘┌»█î ╪▓█î╪▒┘┘ê█î╪│ ╪ذ╪د ┌ر█î┘█î╪ز ╪ذ┘┘ê╪▒█î ┘ê ┌ر╪»┌ر x265
=====================<br />
start: 00:02:09,360<br />
stop: 00:02:12,021<br />
startMS: 129360<br />
stopMS: 132021<br />
text: .┘à╪د ┘╪ذ╪د┘è╪» ╪ز┘┘ç╪د┘è┘è ╪د┘è┘╪ش╪د ╪ذ╪د╪┤┘è┘à -
┌╪▒╪د ╪ا<br />
=====================<br />
start: 00:02:12,022<br />
stop: 00:02:14,725<br />
startMS: 132022<br />
stopMS: 134725<br />
text: ..╪د┌»┘ç ┘╛╪»╪▒╪ز -
.╪د┘ê┘ ┘ç┘è┌┘ê┘é╪ز ┘à╪ز┘ê╪ش┘ç ╪▒┘╪ز┘┘à┘ê┘ ┘┘à┘è╪┤┘ç -<br />
=====================<br />
it can be done by using php line-break.
I could do it successfully
let me show my code
$srt=preg_split("/\\r\\n\\r\\n/",trim($movie->SRT));
$result[$i]['IMDBID']=$movie->IMDBID;
$result[$i]['TMDBID']=$movie->TMDBID;
here $movie->SRT is the subtitle of having format u posted in this question.
as we see, each time space is two new line,
hope u getting answer.
Simple, natural, trivial solution
srt subs look like this, and are separated by two newlines:
3
00:00:07,350 --> 00:00:09,780
The ability to destroy a planet is
nothing next to the power of the force
Obviously you want to parse the time, using dateFormat.parse which already exists in Java, so it is instant.
class Sub {
float start;
String text;
Sub(String block) {
this.start = null; this.text = null;
String[] lines = block.split("\n");
if (lines.length < 3) { return; }
String timey = lines[1].replaceAll(" .+$", "");
try {
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss,SSS");
Date zero = dateFormat.parse("00:00:00,000");
Date date = dateFormat.parse(timey);
this.start = (float)(date.getTime() - zero.getTime()) / 1000f;
} catch (ParseException e) {
e.printStackTrace();
}
this.text = TextUtils.join(" ", Arrays.copyOfRange(lines, 2, lines.length) );
}
}
Obviously, to get all the subs in the file
List<Sub> subs = new ArrayList<>();
String[] tt = fileText.split("\n\n");
for (String s:tt) { subs.add(new Sub(s)); }

Categories