echo partially hidden (IPV4 or IPV6) ip in a table - php

I have a table where a variable in a row containing IP information is being echoed. I think there's an issue with my if statement, because if I use the following then I can get the variable to echo:
echo $row['log_ip'] = substr_replace ($row['log_ip'], $ipv4replacement, stripos ($row['log_ip'], $ipv4needle, $offset = 2));
My current code:
$ipv6needle = ':';
$ipv4needle = '.';
$ipv4replacement = '.***.***.***';
$ipv6replacement = ':****:****:****:****:****:****:****';
if (strpos($row['log_ip'], ':') !== FALSE) {
echo $row['log_ip'] = substr_replace ($row['log_ip'], $ipv4replacement, stripos ($row['log_ip'], $ipv4needle, $offset = 2));
else
echo $row['log_ip'] = substr_replace ($row['log_ip'], $ipv6replacement, stripos ($row['log_ip'], $ipv6needle, $offset = 2)); }

Your code is full of weird assignments, I don't know what you want to achieve with them, but here's a corrected and refactored code.
<?php
$offset = 2;
if (strpos($row["log_ip"], ":") !== false) {
$needle = ".";
$replacement = ".***.***.***";
}
else {
$needle = ":";
$replacement = ":****:****:****:****:****:****:****";
}
$row["log_ip"] = substr_replace($row["log_ip"], $replacement, stripos($row["log_ip"], $needle, $offset));
echo $row["log_ip"];
Answer to the question in the comment:
<?php
function mask_ip_address($ip_address) {
if (strpos($ip_address, ".") !== false) {
$parts = explode(".", $ip_address);
return $parts[0] . str_repeat(".***", 3);
}
$parts = explode(":", $ip_address);
return $parts[0] . str_repeat(":****", 7);
}
function mask_ip_address_test($ip_address, $expected) {
assert($expected === mask_ip_address($ip_address));
}
mask_ip_address_test("17.0.0.1", "17.***.***.***");
mask_ip_address_test("fe80::200:5aee:feaa:20a2", "fe80:****:****:****:****:****:****:****");

Related

Issue with duplicate array values from preg_match_all

first time resorting to actually posting on SO.
Also sorry if this has been asked many times, i think ive about read most of them here, but still no dice.
I have a generated log file continaing text i wish to extract the line in the log file is this:
{22:30:47} System:"Obambivas" StarPos:(-59.938,7.375,56.813)ly Body:13 RelPos:(-0.529636,-0.130899,0.838064)km NormalFlight
So far ive manaaged to get the matches via preg_match_all, and works fine.
However i really need each System:"" only once as the log may have several exacly the same.
Ive tried to use array_unique, but im fairly sure im using it wrong as it either retruns nothing or the same results, ie 10+ matches for each match found
So i need just each unique match from the matches found in the log file.
My code so far (sorry if its messy)
And thanks in advance
if (is_dir($log) && is_readable($log)) {
if (!$files = scandir($log, SCANDIR_SORT_DESCENDING)) {
}
$newest_file = $files[0];
if (!$line = file($log . "/" . $newest_file)) {
} else {
foreach ($line as $line_num => $line) {
$pos = strpos($line, 'System:"');
$pos2 = strrpos($line, "ProvingGround");
if ($pos !== false && $pos2 === false) {
preg_match_all("/\System:\"(.*?)\"/", $line, $matches);
$cssystemname = $matches[1][0];
$curSys["name"] = $cssystemname;
preg_match_all("/\StarPos:\((.*?)\)/", $line, $matches2);
$curSys["coordinates"] = $matches2[1][0];
$coord_parts = explode(",", $curSys["coordinates"]);
$curSys["x"] = $coord_parts[0];
$curSys["y"] = $coord_parts[1];
$curSys["z"] = $coord_parts[2];
echo $curSys["name"].' | Coords: '.$curSys["x"].','.$curSys["y"].','.$curSys["z"].'<br />';
}
}
}
}
I added $hash array to avoid duplicates
if (is_dir($log) && is_readable($log)) {
if (!$files = scandir($log, SCANDIR_SORT_DESCENDING)) {
}
$newest_file = $files[0];
if (!$line = file($log . "/" . $newest_file)) {
} else {
$hash = array();
foreach ($line as $line_num => $line) {
$pos = strpos($line, 'System:"');
$pos2 = strrpos($line, "ProvingGround");
if ($pos !== false && $pos2 === false) {
preg_match_all("/\System:\"(.*?)\"/", $line, $matches);
$cssystemname = $matches[1][0];
if ($hash[$cssystemname] == "")
{
$curSys["name"] = $cssystemname;
preg_match_all("/\StarPos:\((.*?)\)/", $line, $matches2);
$curSys["coordinates"] = $matches2[1][0];
$coord_parts = explode(",", $curSys["coordinates"]);
$curSys["x"] = $coord_parts[0];
$curSys["y"] = $coord_parts[1];
$curSys["z"] = $coord_parts[2];
echo $curSys["name"].' | Coords: '.$curSys["x"].','.$curSys["y"].','.$curSys["z"].'<br />';
}
} else $hash[$cssystemname] = "inhash";
}
}

How to seperate the string of the variable in PHP from requested word

$t = ABCDEFPN03KSASDEID;
$r = stristr($t, 'PN03', true);
My Value is $r = ABCDEF
and in if condition while i plan to seperate it throws output wrong
But i want output $s = PNO3KSASDEID like this
My code:
(I used variable as my own)
$r = stristr($t, 'PN03', true);
if( ($s = substr($t, 'PNO3', false)) == true) {
$s = stristr($t, 'PNO3', false);
print_r($s);
}
output: PN03KSASDEID is needed.
Please suggest me solution.
Get in the habit of encapsulating your behaviours in reusable functions
function str_split_term($string, $term) {
$pos = strpos($string, $term);
if ($pos === false)
return $string;
else
return substr($string, $pos);
}
Your use case
echo str_split_term('ABCDEFPN03KSASDEID', 'PN03'); // PN03KSASDEID
If the term is not found in the string, the string will output unaltered
echo str_split_term('ABCDEFPN03KSASDEID', 'ZZZ'); // ABCDEFPN03KSASDEID
PHP7
If you're are using a current version of PHP, I suggest you add type hints to the function
function str_split_term(string $string, string $term): string {
$pos = strpos($string, $term);
if ($pos === false)
return $string;
else
return substr($string, $pos);
}

how to replace everything after specific word in php

$url =file("list.txt");
foreach ($url as $sites) {
$sites = trim($sites);
echo $sites . " </ br>";
}
and list.txt contain some urls
http://example.com/cms/wp-content/themes/
http://example.com/wp-content/plugins/
http://example.com/wp-content/themes/Avada-Child-Theme/
how could i remove the word "/wp-content/" and everything after it
to be
http://example.com/cms
http://example.com
http://example.com
Take a look at the the parameter $before_needle at http://docs.php.net/strstr
$o = strstr($url, '/wp-content/', true);
How about using preg_replace?
Something like that:
$sites = trim(preg_replace( '#/wp-content.*#', '', $sites));
This should work:
<?php
$url =file("list.txt");
foreach ($url as $sites) {
$sites = trim($sites);
$pos = strpos($sites, 'wp-content');
$newStr = substr($sites,0,$pos );
echo $newStr . " </ br>";
}
?>
$lines = file('list.txt');
$find = '/wp-content/';
foreach ($lines as $line) {
$line = trim($line);
$pos = strpos($line, $find);
if($pos !== false) {
echo substr($line, 0, $pos) . '<br>';
} else {
echo 'Not found ' . $find . '<br>';
}
}
First explode your content by new line then loop through each and use substr function to remove the matches. Following function my be useful to you:
<?php
// can remove variables from: full url, from urls related to site root, form just a query string like "a=1&b=2"
if(!function_exists("remove_var_from_url")){
function remove_var_from_url($variable_name, $url_string){
// this is anything before the "?" sign
$base_url = '';
// the variable separator, can be "?" if is a full URL or can be empty, if we just have "&sort=sales&oprder=asc"
$separator = "";
$start_pos = 0;
$return_string = "";
//
if(strpos($url_string,"?")!==false){
$start_pos = strpos($url_string, "?")+1;
$separator = "?";
$base_url = substr($url_string, 0, $start_pos-1);
}
// start building the string from the base url (which can be empty)
$return_string = $base_url;
$url_vars_string = substr($url_string, $start_pos);
$names_and_values = explode("&", $url_vars_string);
//
foreach($names_and_values as $value){
list($var_name, $var_value) = explode("=", $value);
if($var_name != $variable_name){
// add the "?" once if needed
if(!$separator_added){
$return_string.= $separator;
$separator_added = true;
} else {
$return_string.= "&";
}
$return_string.= $var_name."=".$var_value;
}
}
// remove "&" from margins
$return_string = trim($return_string, "&");
// remove the "?" if is at the end, it means it was just one variable that was removed
$return_string = rtrim($return_string, "?");
return $return_string;
}
}
?>
I would rather suggest you to apply strpos on each of the string first. Strpos will return you the position of first occurance of a string. Then use substr to fetch everything prior to that string.
` $lines = file('list.txt');
$find = '/wp-content/';
foreach ($lines as $line) {
$position = strpos($line, '/wp-content');
if($position)
$string = substr($line, 0, $position);
}`

How to find string position php

I want to get the position of 'ja' in each of the words in $string, but its not working. what am i doing wrong?
<?php
$offset = 0;
$find = 'ja';
$find_length = strlen($find);
$string = 'jasim jasmin jassir';
while ($string_position = strpos($string, $find, $offer)) {
echo $find.' found at '.$string_position.'<br>';
$offset = $string_position + $find_length;
}
?>
Change the variable name to $offset
strpos may return 0 and while will treat it as false
So replace your while statement with:
while (($string_position = strpos($string, $find, $offset)) !== false) {
<?php
// stack overflow area
$offset = 0;
$find = 'ja';
$find_length = strlen($find);
$string = 'jasim jasmin jassir';
if (strpos($string, $find) === false) {
echo "not found";
}
else {
while (strpos($string, $find, $offset) !== false) {
$string_position = strpos($string, $find, $offset);
echo $find.' found at '.$string_position.'<br>';
$offset = $string_position + $find_length;
}
}
?>
Little workaround, but it apparently works.
Output:
ja found at 0
ja found at 6
ja found at 13
try changing offest
<?php
$offset = 1;
$find = 'ja';
$find_length = strlen($find);
$string = 'jasim jasmin jassir';
while ($string_position = strpos($string, $find, $offset)) {
echo $find.' found at '.$string_position.'<br>';
$offset = $string_position + $find_length;
}
?>
// output :- ja found at 6
ja found at 13
if you don't want to change offset use
$string = ' jasim jasmin jassir'; (without space not be jasim it's 'jasim )
then it will output 3
ja found at 1
ja found at 7
ja found at 14
OR try to change your condition check
while (($string_position = strpos($string, $find, $offset)) !== false) {
Probably you should code this way to find string positions
$positions = array();
$offset = -1;
while (($pos = strpos($string, $find, $offset+1)) !== false) {
$positions[] = $offset;
}
$result = implode(', ', $positions);
print this result

solve a bad Url to clean Url in php?

when I spide a website ,I got a lot of bad url like these.
http://example.com/../../.././././1.htm
http://example.com/test/../test/.././././1.htm
http://example.com/.//1.htm
http://example.com/../test/..//1.htm
all of these should be http://example.com/1.htm.
how to use PHP codes to do this ,thanks.
PS: I use http://snoopy.sourceforge.net/
I get a lot of repeated link in my database , the 'http://example.com/../test/..//1.htm' should be 'http://example.com/1.htm' .
You could do it like this, assuming all the urls you have provided are expected tobe http://example.com/1.htm:
$test = array('http://example.com/../../../././.\./1.htm',
'http://example.com/test/../test/../././.\./1.htm',
'http://example.com/.//1.htm',
'http://example.com/../test/..//1.htm');
foreach ($test as $url){
$u = parse_url($url);
$path = $u['scheme'].'://'.$u['host'].'/'.basename($u['path']);
echo $path.'<br />'.PHP_EOL;
}
/* result
http://example.com/1.htm<br />
http://example.com/1.htm<br />
http://example.com/1.htm<br />
http://example.com/1.htm<br />
*/
//or as a function #lpc2138
function getRealUrl($url){
$u = parse_url($url);
$path = $u['scheme'].'://'.$u['host'].'/'.basename($u['path']);
$path .= (!empty($u['query'])) ? '?'.$u['query'] : '';
return $path;
}
You seem to be looking for a algorithm to remove the dot segments:
function remove_dot_segments($abspath) {
$ib = $abspath;
$ob = '';
while ($ib !== '') {
if (substr($ib, 0, 3) === '../') {
$ib = substr($ib, 3);
} else if (substr($ib, 0, 2) === './') {
$ib = substr($ib, 2);
} else if (substr($ib, 0, 2) === '/.' && ($ib[2] === '/' || strlen($ib) === 2)) {
$ib = '/'.substr($ib, 3);
} else if (substr($ib, 0, 3) === '/..' && ($ib[3] === '/' || strlen($ib) === 3)) {
$ib = '/'.substr($ib, 4);
$ob = substr($ob, 0, strlen($ob)-strlen(strrchr($ob, '/')));
} else if ($ib === '.' || $ib === '..') {
$ib = '';
} else {
$pos = strpos($ib, '/', 1);
if ($pos === false) {
$ob .= $ib;
$ib = '';
} else {
$ob .= substr($ib, 0, $pos);
$ib = substr($ib, $pos);
}
}
}
return $ob;
}
This removes the . and .. segments. Any removal of any other segment like an empty one (//) or .\. is not as per standard as it changes the semantics of the path.
You could do some fancy regex but this works just fine.
fixUrl('http://example.com/../../../././.\./1.htm');
function fixUrl($str) {
$str = str_replace('../', '', $str);
$str = str_replace('./', '', $str);
$str = str_replace('\.', '', $str);
return $str;
}

Categories