Iterate through text file and check if file exist on server - php

I have a txt file with 40.000 file paths with filenames that I need to check if they exist.
To check for a single file i use the following code:
$filename='/home/httpd/html/domain.com/htdocs/car/002.jpg';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
That code works.
Now I want to iterate through the txt file, that contains one path per row
/home/httpd/html/domain.com/htdocs/car/002.jpg
/home/httpd/html/domain.com/htdocs/car/003.jpg
/home/httpd/html/domain.com/htdocs/car/004.jpg
...
I tried to iterate through the txt file with this code, but i get "file does not exist" for all files.
$file = "list.txt";
$parts = new SplFileObject($file);
foreach ($parts as $filename) {
if (file_exists($filename)) { echo "The file $filename exists"; }
else { echo "The file $filename does not exist"; }
}

Your list.txt file has a newline at the end of each line. You first need to trim that off before using $filename in the file_exists() like this for example
<?php
$file = "list.txt";
$parts = new SplFileObject($file);
foreach ($parts as $filename) {
$fn = trim($filename);
if (file_exists($fn)) {
echo "The file $fn exists\n";
} else {
echo "The file $fn does not exist\n";
}
}

when you load a file try to break the string into array by explode() function.
Then you will be able to validate with file_exist function

Related

How to increment unique filename based on directory array

I'm creating an upload form that when uploading files will check to see if a file with the same name already exists in the directory. If a file with the same name is found, the script should increment the file by appending the file name with a number such as test1.txt test2.txt and so on until a match is not found. This is what I have come up with so far but wanted to see if there is a different approach I should take.
Also note, my filenames are already cleaned before they enter this part of the script so my filename and extension functions are simplified.
function filename($file){
return substr($file,0,strrpos($file,'.'));
}
function extension($file){
return strtolower(substr(strrchr($file,'.'),1));
}
$new_file = 'test.txt';
$dir = 'files';
$files = scandir($dir);
$exclude = array('.','..');
foreach($files as $file){
if(!in_array($file,$exclude)){
$file_array[] = $file;
}
}
$i = 1;
while(in_array($new_file,$file_array)){
$filename = filename($new_file);
$extension = extension($new_file);
if($i>1){
$num = strlen($filename);
$filename = substr($filename,0,-1);
$new_file = $filename.$i.'.'.$extension;
} else {
$new_file = $filename.$i.'.'.$extension;
}
echo $new_file.'<br>';
echo $i.'<br>';
$i++;
}
echo $new_file;

How can I check only file name not extension is exists

How can I check only file name not extension like jpeg, jpg, doc, xls. and then copy its complete name like example.jpeg or example.doc
and if possible can we store its upper two parent directory like
if example.jpeg stored in
main_dir/second_dir/example.jpeg
so I want to store this path in php variable.
I know I can use glob()
$result = glob ("./uploads/filename.*");
and check $result value.
But I want to store complete file name and possible its two parent directory path.
Below is my code
$filename = '/www/test1/'. $file . '*' ;
if (count(glob($filename)) > 0) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
Edit
Updated query as per luweiqi solution
foreach(glob("/uploads/".$productnumber."/". $productnumber."b.*", GLOB_NOSORT) as $file) {
echo "Filename: " . $file . "<br />";
$image2 = "/uploads/".$productnumber."/".$file;
}
Last letter of image varies like a to f . so can you make some correction in it.
I want to check image is exist on uploads/productnumber/productnumber (a/b/c/d/e/f).jpg or png or jpeg etc. and store that file name in php variable.
You can use file_exists() function.
$pngFile = '/path/to/foo.png';
$docFile = '/path/to/foo.doc';
// Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.
if (file_exists($filename) || file_exists($docFile)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
OR
Use glob function
$files=[];
$result = glob ("/path/to/foo.*");
foreach ($result as $file) {
echo "$file size " . filesize($file) . "\n";
$files[] = $file;
}
echo '<pre>'; print_r($files);
You can use:
<?php
foreach(glob("../directory/*{a,b,c,e,f}.*", GLOB_BRACE) as $file) {
echo "Filename: " . $file . "<br />";
}
?>
This code would get the file name and echo it, you can change it accordingly if you want to assign it to a variable.

Create html file with php script

I want to create a php script that will check if a certain html file exist or not. if it doesn't exist, then create a new one and give it a name.
I have tried the code below, but still not working.
$file = file_get_contents(site_url('appraisal/createReport'));
$filename = 'Service_delivery_report_'.date('Y-m-d', time()).'.html';
$filepath = dirname(__DIR__).'/views/sd_reports/'.$filename;
write_file($filepath, $file);
if(! file_exists ($filename))
{
$fp = fopen($filename, 'w');
fwrite($fp, $file);
fclose($fp);
}
I'm not familiar with the method you're using called 'site_url'. From a quick google search it looks like it's a method in Word Press. Ignoring the site_url method, you might want to test using a specific url, like http://ted.com for example. I've specified is_file rather than file_exists because file_exists will return true even if the path you've specified is a directory, whereas is_file will only return true if the path is an actual file. Try this code, setting the $site variable to a site url or path to a file.
I've also switched some code around, doing a check first to see if the file exists before attempting to read in the contents of $site. This way, if the file already exists, you're not needlessly reading in the contents of $site.
$filename = "Service_delivery_report_" . date("Y-m-d",
time()). ".html";
$filepath = realpath("./") . "/views/sd_reports/" . $filename;
if (!is_file($filepath))
{
$site = "http://somesite.com/somepage";
if ($content = file_get_contents($site))
{
file_put_contents($filepath,
$content);
}
else
{
echo "Could not grab the contents of some site";
}
}
Use file_exists();
<?php
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>
Then, if it doesn't exist, create a file with fopen();, like so:
$handle = fopen($filename, "w");
Try this
$file = file_get_contents(site_url('appraisal/createReport'));
$filename = 'Service_delivery_report_'.date('Y-m-d', time()).'.html';
if(! file_exists ($filename))
{
$f = fopen($filename, "w");
fwrite($f, $file);
fclose($f);
}
else
echo "file already exist";

Read only pdf files and get the filename of that pdf files in a directory

I need to read only pdf files in a directory and then read the filename of every files then I will use the filename to rename some txt files. I have tried using only eregi function. but it seems cannot read all I need. how to read them well?
here's my code :
$savePath ='D:/dir/';
$dir = opendir($savePath);
$filename = array();
while ($filename = readdir($dir)) {
if (eregi("\.pdf",$filename)){
$read = strtok ($filename,"."); //get the filenames
//to rename some txt files using the filenames that I get before
//$testfile is text files that I've read before
$testfile = "$read.txt";
$file = fopen($testfile,"r") or die ('cannot open file');
if (filesize($testfile)==0){}
else{
$text = fread($file,55024);
fclose($file);
echo "</br>"; echo "</br>";
}
}
More elegant:
foreach (glob("D:/dir/*.pdf") as $filename) {
// do something with $filename
}
To get the filename only:
foreach (glob("D:/dir/*.pdf") as $filename) {
$filename = basename($filename);
// do something with $filename
}
You can do this by filter file type.. following is sample code.
<?php
// directory path can be either absolute or relative
$dirPath = '.';
// open the specified directory and check if it's opened successfully
if ($handle = opendir($dirPath)) {
// keep reading the directory entries 'til the end
$i=0;
while (false !== ($file = readdir($handle))) {
$i++;
// just skip the reference to current and parent directory
if (eregi("\.jpg",$file) || eregi("\.gif",$file) || eregi("\.png",$file)){
if (is_dir("$dirPath/$file")) {
// found a directory, do something with it?
echo " [$file]<br>";
} else {
// found an ordinary file
echo $i."- $file<br>";
}
}
}
// ALWAYS remember to close what you opened
closedir($handle);
}
?>
Above is demonstrating for file type related to images you can do the same for .PDF files.
Better explained here

Checking if thumbnail exists in PHP

My directory structure looks like that.
...photo-album1/
...photo-album1/thumbnails/
Lets say we have image1.jpg inside photo-album1/. Thumbnail of this file is tn_image1.jpg
What I wanna do is to check every file inside photo-album1/ if they have thumbnail in photo-album1/thumbnails/. If they have just continue if not, send file name to another function : generateThumb()
How can I do that?
<?php
$dir = "/path/to/photo-album1";
// Open directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
// Walk through directory, $file by $file
while (($file = readdir($dh)) !== false) {
// Make sure we're dealing with jpegs
if (preg_match('/\.jpg$/i', $file)) {
// don't bother processing things that already have thumbnails
if (!file_exists($dir . "thumbnails/tn_" . $file)) {
// your code to build a thumbnail goes here
}
}
}
// clean up after ourselves
closedir($dh);
}
}
$dir = '/my_directory_location';
$files = scandir($dir);//or use
$files =glob($dir);
foreach($files as $ind_file){
if (file_exists($ind_file)) {
echo "The file $filexists exists";
} else {
echo "The file $filexists does not exist";
}
}
The easy way is to use PHP's glob function:
$path = '../photo-album1/*.jpg';
$files = glob($path);
foreach ($files as $file) {
if (file_exists($file)) {
echo "File $file exists.";
} else {
echo "File $file does not exist.";
}
}
Credit to soul above for the basics. I'm just adding glob to it.
EDIT: As hakre points out, glob only returns existing files, so you can speed it up by just checking to see if the filename is in the array. Something like:
if (in_array($file, $files)) echo "File exists.";

Categories