How can I check only file name not extension is exists - php

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.

Related

Iterate through text file and check if file exist on server

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

How to rename each file before uploading to server to a time-stamp

I'm using the following code to upload some files, but well, some get replaced since the names get to be alike. I just wanna know how do i change the name, i tried but i kinda find myself messing the entire code.
PHP
if (!empty($_FILES["ambum_art"])) {
$myFile = $_FILES["ambum_art"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
$success = move_uploaded_file($myFile["tmp_name"],UPLOAD_DIR . '/'.$name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
} else {
$Dir = UPLOAD_DIR .'/'. $_FILES["ambum_art"]["name"];
}
chmod(UPLOAD_DIR .'/'. $name, 0644);
unset($_SESSION['video']);
$_SESSION['album_art'] = $Dir;
$ambum_art_result = array();
$ambum_art_result['content'] = $Dir;
echo json_encode($ambum_art_result);
}
I would like each file to have something from this variable generated from time.
$rand_name = microtime().microtime().time().microtime();
Thanks.
I don't want to first check if file exists as that adds to the processes, i just want to use time() and some random string. to just get a unique name.
Please see this website for a decent example of file uploading and an explanation. Also this site appears to be where you found this particular script from or if not offers a good explanation.
I have modified your code to include some comments so you and others can understand what is going on better. In theory, the code shouldn't be overwriting existing files like you say it does but I have added what you would need to change to set the name of the file to a random string.
In addition you are storing the original filename into the session and not the modified filename.
define("UPLOAD_DIR", "/path/to/uploads/");
if (!empty($_FILES["ambum_art"]))
{
// The file uploaded
$myFile = $_FILES["ambum_art"];
// Check there was no errors
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// Rename the file so it only contains A-Z, 0-9 . _ -
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// Split the name into useful parts
$parts = pathinfo($name);
// This part of the code should continue to loop until a filename has been found that does not already exist.
$i = 0;
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// If you want to set a random unique name for the file then uncomment the following line and remove the above
// $name = uniqid() . $parts["extension"];
// Now its time to save the uploaded file in your upload directory with the new name
$success = move_uploaded_file($myFile["tmp_name"], UPLOAD_DIR . '/'.$name);
// If saving failed then quit execution
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// Set file path to the $Dir variable
$Dir = UPLOAD_DIR .'/'. $name;
// Set the permissions on the newly uploaded file
chmod($Dir, 0644);
// Your application specific session stuff
unset($_SESSION['video']);
$_SESSION['album_art'] = $Dir; // Save the file path to the session
$ambum_art_result = array();
$ambum_art_result['content'] = $Dir;
echo json_encode($ambum_art_result);
}
Read more about PHPs uniqid.
I would also strongly advise doing some filetype checking as currently it appears as though any file can be uploaded. The second link above has a section titled 'Security Considerations' that I would recommend reading through vary carefully.
This code is filtering the name, then checks if file with exactly same name is already sent. If it is - name is changed with with number.
If you want to change the file name as in many sites - you may modify this line $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
For example into: $name = time().'_'.preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
If user sends file calle 'hello.jpg' this code will change it to _hello.jpg if file with the same name exists already the name _hello-.jpg will be used instead.
First you need to copy that file which you want to upload and after that you have to rename that. Ex.
//copy
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}
?>
//rename
rename('picture', 'img506.jpg');
Reference Link for copy
Rename file
Edited:
Replace your code with this and then try
<?php
if (!empty($_FILES["ambum_art"])) {
$myFile = $_FILES["ambum_art"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
if (file_exists($myFile["name"])) {
rename($myFile["name"], $myFile["name"].time()); //added content
}
$success = move_uploaded_file($myFile["tmp_name"],UPLOAD_DIR . '/'.$name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
} else {
$Dir = UPLOAD_DIR .'/'. $_FILES["ambum_art"]["name"];
}
chmod(UPLOAD_DIR .'/'. $name, 0644);
unset($_SESSION['video']);
$_SESSION['album_art'] = $Dir;
$ambum_art_result = array();
$ambum_art_result['content'] = $Dir;
echo json_encode($ambum_art_result);
}
?>
This will rename your existing file and then copy your file

how to get each file size individually from directory PHP

can anyone help me to get each file size individually from a local directory ?.
$files = scandir('soft');
foreach($files as $file) {
echo $file . "<br />";
}
From here
$files = scandir('soft');
foreach($files as $file) {
if (!in_array($file,array(".","..")))
{
echo $file . "<br />";
echo filesize('soft/'.$file) . ' bytes';
}
}
Just need to keep in mind that scandir gets only the filenames in that dir, and not the relative path to it. that's why you need to use 'soft/'.$file and not $file
<?
$files = scandir('.');
foreach($files as $file) {
echo filesize($file) . " bytes<br>";
}
?>
use filesize($filename) php function, it will give size in bytes

Echo all the folder names in a folder

I want to print all the folder names inside a parent folder. The current issue I am facing is, though I have 400+ folders in a folder only 257 are getting printed. Again, this is not at all issue related with permissions.
Please find my code below:
$newdir = "content/";
$dircnt = 0;
// Open a known directory, and proceed to read its contents
if (is_dir($newdir)) {
if ($dh = opendir($newdir)) {
while (($file = readdir($dh)) !== false) {
$dircnt++;
if(filetype($newdir. $file) == 'dir') {
echo "filename: $file : filetype: " . filetype($newdir. $file) . "dircnt:" .$dircnt. "<br>";
}
}
closedir($dh);
}
}
}
You can use glob() function - returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.
$filesDirectories = glob($newdir.'*', GLOB_BRACE);
foreach($filesDirectories as $key=>$file) {
echo "$file size " . filesize($file) . "\n";
}
I would use glob:
$newdir = "content/";
$dirs = glob($newdir.'*',GLOB_ONLYDIR);
foreach($dirs as $index=>$dir){
echo "filename ". $dir." filetype ".filetype($newdir.$dir)." dircnt:".($index+1)."<br/>";
}

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