php grab images from directory - php

I have this PHP script which i'm grabbing images from a directory and displaying them. The directory only has 4 image files in it and yet there are 6 li's. In firebug the images just have the paths 'Images/uploaded/.' and 'Images/uploaded/..'
Are there hidden files that this script is grabbing but not displaying correctly?
<?php
$dir = 'Images/uploaded/';
if($handle = opendir($dir)) {
while(false !== ($file = readdir($handle))) {
echo "<li><img class=\"thumb\" src=\"".$dir.$file."\" /></li>";
}
}
closedir($handle);
?>

Your test for . or .. fails... example: You load '.' and your test says:
if('." is not "." OR its not "..")
change this conditional to && (and).

Those are the entries for "current directory" and "parent directory, respectively. Just filter them out.

Related

Read and delete a text file in php

I am making a simple php script which just read a text file from server and delete it after showing on web.Script works well but it reads another file and delete another. It should delete the same file it reads. Any help please. Here is my code:
<?php
$mystr = '';
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$info = pathinfo($entry);
if ($info["extension"] == "txt") {
$mystr = $entry;
}
}
}
closedir($handle);
}
if (empty($mystr)) {
}else{
$contents = file_get_contents($mystr);
echo $contents;
unlink($mystr);
}
?>
Update
I dont know the file name, So in a loop I get the file name. I want to read any .txt file in the folder. This I read file one by one and at the same time delete it.
Your script is just this :
foreach(glob('/path/to/dir/*.txt') as $file)
{
readfile($file);
unlink($file);
}
See readfile() and glob() manual pages.

Limiting file listing by filename length in PHP

I am currently generating a list of links (to files in a single directory) using this PHP script:
### BEGIN Directory Listing
PHP script to list files in a dir, currently lists dummy files as well, but it works.
<?php
$dir="./content"; // Directory where files are stored
if ($dir_list = opendir($dir)) {
while(($filename = readdir($dir_list)) !== false) {
//this kills the annoying .. and . directory listing
if($filename == ".." || $filename == ".") continue; ?>
<p><?php echo $filename; ?></p>
<?php
}
closedir($dir_list);
}
?>
### END Directory Listing
I now wish to only list files with a filename length of 8 characters (the ./content folder contains multiple length filenames but only one filetype). It should also be noted, the files do NOT show/have file extensions.
As always, your help and knowledge is greatly appreciated!
Check the length with strlen()
if (strlen($filename) !== 8) continue;
if ($dir_list = opendir($dir)) {
while(($filename = readdir($dir_list)) !== false) {
if(strlen($filename) !== 8) continue;
//this kills the annoying .. and . directory listing
if($filename == ".." || $filename == ".") continue; ?>
Check it with strlen() function
if(strlen($filename) ==8)){
//do something }

File renaming using php

Have the following script.
<?php
if ($handle = opendir('files/')) {
while (false !== ($fileName = readdir($handle))) {
$newName = str_replace("SKU#","",$fileName);
rename(fileName, $newName);
}
closedir($handle); } ?>
my script is in the root directory of iss.
inetpub/wwwroot
And I am trying to as a result access the folder files/, which is one level up to wwwroot. Where contains one image called:
"WV1716BNSKU#.zoom.1"
I am using a windows OS, any idea why this is not working, code looks file.
What error do you get? Make sure PHP is setup to display all errors.
Your script will also have to be in the same folder as your files you want to rename as all your paths are relative.
Try this:
if ($handle = opendir('./')){
while (false !== ($fileName = readdir($handle))){
$newName = str_replace("SKU#", "", $fileName);
rename($fileName, $newName);
}
closedir($handle);
}

finding files in a dir

I have a directory with a lot of files inside:
pic_1_79879879879879879.jpg
pic_1_89798798789798789.jpg
pic_1_45646545646545646.jpg
pic_2_12345678213145646.jpg
pic_3_78974565646465645.jpg
etc...
I need to list only the pic_1_ files. Any idea how I can do?
Thanks in advance.
Use the glob() function
foreach (glob("directory/pic_1_*") as $filename) {
echo "$filename";
}
Just change directory in the glob call to the proper path.
This does it all in one shot versus grabbing the list of files and then filtering them.
The opend dir function will help you
$dir ="your path here";
$filetoread ="pic_1_";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (strpos($file,$filetoread) !== false)
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
good luck see php.net opendir
This is what glob() is for:
glob — Find pathnames matching a pattern
Example:
foreach (glob("pic_1*.jpg") as $file)
{
echo $file;
}
Use scandir to list all the files in a directory and then use preg_grep to get the list of files which match the pattern you are looking for.
This is one of the samples from the manual
http://nz.php.net/manual/en/function.readdir.php
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
you can modify that code to test the filename to see if it starts with pic_1_
using something like this
if (substr($file, 0, 6) == 'pic_1_')
Manual reference for substr
http://nz.php.net/manual/en/function.substr.php

is_dir does not recognize folders

I am trying to make a function that scans a folder for subfolders and then returns
a numeric array with the names of those folders.
This is the code i use for testing. Once i get it to print out the folder names and not just "." and ".." for present and above folder all will be well, and I can finish the function.
<?php
function super_l_getthemes($dir="themes")
{
if ($handle = opendir($dir)) {
echo "Handle: {$handle}\n";
echo "Files:\n";
while (false !== ($file = readdir($handle))) {
echo "{$file}<br>";
}
closedir($handle);
}
?>
The above code works fine, and prints out all the contents of the folder: files, subfolders and the "." and ".."
but if i replace:
while (false !== ($file = readdir($handle))) {
echo "{$file}<br>";
}
with:
while (false !== ($file = readdir($handle))) {
if(file_exists($file) && is_dir($file)){echo "{$file}";}
}
The function only prints "." and ".." , not the two folder names that I'd like it to print.
Any help is appreciated.
You must provide the absolute path to file_exists, otherwise it will look for it in the current execution path.
while (false !== ($file = readdir($handle))) {
$file_path = $dir . DIRECTORY_SEPARATOR . $file;
if (file_exists($file_path) && is_dir($file_path)) {
echo "{$file}";
}
}
The problem with readdir is that it only reads the strings of the named entries inside of the directory.
For instance, if you had file "foo" inside of directory "/path/to/files/", when using readdir on "/path/to/files/", you would eventually come to the string "foo".
Normally this wouldn't be a problem if it were in the same directory as the current working directory of the script, but, since you are reading from an arbitrary director, when you are attempting to inspect the entry (file, directory, whatever), you are calling is_dir on the bare string "foo".
I would try prefixing the name you pull out using readdir with the path to the file.
if ($handle = opendir($dir)) {
echo "Handle: {$handle}\n";
echo "Files:\n";
while ($file = readdir($handle)) {
/*** make $file into an absolute path ***/
$absolute_path = $dir . '/' . $file;
/*** NOW try stat'ing it ***/
if (is_dir($absolute_path)) {
/* it's a directory; do stuff */
}
}
closedir($handle);
}
You need to use:
while (false !== ($file = readdir($handle))) {
if(file_exists($dir.'/'.$file) && is_dir($dir.'/'.$file)){echo "{$file}";}
}
See http://php.net/readdir
If you only want the directories of the starting folder, you can simply do:
glob('/some/path/to/search/in/*', GLOB_ONLYDIR);
which would given you only those foldernames in an array. If you want all directories below a given path, try SPL's RecursiveDirectoryIterator
$fileSystemIterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/some/path/to/look/in'),
RecursiveIteratorIterator::SELF_FIRST);
Iterators can be used with foreach:
$directories = array();
foreach($fileSystemIterator as $path => $fileSystemObject) {
if($fileSystemObject->isDir()) {
$directories[] = $path;
}
}
You will then have an array $directories with all directories under the given path.
$files = array();
foreach(new DirectoryIteraror('/path') as $file){
if($file->isDir() /* && !$file->isDot()*/) $files[] = $file->getFilename();
}
[edit: though you wanted to skip the dot, commented it out)
I don't think you need both file_exists and is_dir,
You just need the is_dir function. From the manual:
is_dir Returns TRUE if the filename exists and is a directory, FALSE otherwise.
Use this:
while (false !== ($file = readdir($handle))) {
if(is_dir($file)){echo "{$file}";}
}
is_dir will also check whether it's a relative path or an absolute path.
$directory = scandir($path);
foreach($directory as $a){
if(is_dir($path.$a.'/') && $a != '.' && $a != '..'){
echo $a.'<br/>';
}
}
With the path given as shown, it displays the folders present in the path.
I agree with nuqqsa's solution, however, I'd like to add something to it.
Instead of specifying the path, you can change the current directory instead.
For example,
// open directory handle
// ....
chdir($dir);
while (false !== ($file = readdir($handle)))
if(is_dir($file))
echo $file;
// close directory handle

Categories