John Davidson

Check if file name contains IP address and get the free file name PHP

0 comments
Message:


I am trying to check if files in a directory contain a specific ip address. If the IP address is not found in the file name I want a file with the not found IP adress in the file name to be moved there.


Here's my script:


<?php

function ip_range($start = "10.100.1.2", $end = "10.100.255.254"){
$start = ip2long($start);
$end = ip2long($end);
return array_map('long2ip', range($start, $end));
}
function check_filename(){

$ip_address_list = ip_range();
$dir_files = scandir("/mnt/dumps/");
foreach($ip_address_list as $ip){
foreach($dir_files as $file){
if($d = glob($ip)){
if(empty($d)){
$fpath = "/mnt/dumps/{$ip}_public.txt";
echo $fpath;
}
}
if(isset($fpath)){
return $fpath;
}
if(isset($fpath)){
return $fpath;
}

}

};

?>

But when I execute the script it returns me as example 10.100.1.2 - but a file containing this IP address already exists. That's actually not what I want.


Could you tell me what I've did wrong? Thanks!


EDIT:


I've changed the script:


function ip_range($start = "10.100.1.2", $end = "10.100.255.254"){
$start = ip2long($start);
$end = ip2long($end);
return array_map('long2ip', range($start, $end));
}

function check_filename(){

$ip_address_list = ip_range();
$dir_files = scandir("/mnt/dumps/");
echo "<pre>"; print_r($dir_files); echo "</pre>";
foreach($ip_address_list as $ip){
$new_ip = preg_quote($ip);
foreach($dir_files as $file){
if(!preg_match("/^{$new_ip}_public.{0,10}\.txt/", $file)){
$fpath = "/mnt/dumps/{$ip}_public.txt";
}
}
if(isset($fpath)){
return $fpath;
}
}

};




My Answer:
php

$directory = 'path/to/directory';
$ipAddress = '192.168.1.1';

$files = scandir($directory);

foreach ($files as $file) {
if (strpos($file, $ipAddress) !== false) {
echo "File name contains IP address: $file\n";
} else {
$newFileName = str_replace('.txt', "_$ipAddress.txt", $file);
rename("$directory/$file", "$directory/$newFileName");
echo "File name does not contain IP address. Renamed to: $newFileName\n";
}
}

?>


This script will loop through all the files in the specified directory and check if the file name contains the specified IP address. If the IP address is found in the file name, it will output a message saying so. If the IP address is not found in the file name, it will rename the file to include the IP address and output a message with the new file name.

Rate this post

4 of 5 based on 1396 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us