I have this script:
$uploadsDirectory = dirname($_SERVER['SCRIPT_FILENAME']) .'/slides/head/';
if ($handle = opendir($uploadsDirectory)) {
$uplo = array();
while (false !== ($file = readdir($handle))) {
array_push($uplo, $file);}
sort($uplo,SORT_NATURAL | SORT_FLAG_CASE);
$user = array();
foreach($uplo as $fname) {
if($fname != ".." && $fname != "."){
if(substr($fname,0,1) != "_")
echo "<div class='bgitem' id='head'>$fname</div>";
else
array_push($user, "$fname");}}
closedir($handle);}
It works fine, but how can I make it so it only shows the pictures? (I have other files that aren't photos, so it displays a broken picture instead.)
A simple way would be to have it test whether the file is an image in the same line where you test if the file is a parent directory or the current directory (if($fname != ".." && $fname != "."){)
You can use getimagesize() to determine if the file is any kind of image. If it is not an image, it will return zero.
$uploadsDirectory = dirname($_SERVER['SCRIPT_FILENAME']) .'/slides/head/';
if ($handle = opendir($uploadsDirectory)) {
$uplo = array();
while (false !== ($file = readdir($handle))) {
array_push($uplo, $file);}
sort($uplo,SORT_NATURAL | SORT_FLAG_CASE);
$user = array();
foreach($uplo as $fname) {
if($fname != ".." && $fname != "." && getimagesize($fname) != 0){ //Tests if file is an iamge
if(substr($fname,0,1) != "_")
echo "<div class='bgitem' id='head'>$fname</div>";
else
array_push($user, "$fname");}}
closedir($handle);}
Solution for you:
$extension = explode(".", $fname);
$extension = (isset($extension) && count($extension) > 0)?strtolower($extension[count($extension) -1]):null;
if(in_array($extension, ['jpg', 'jpeg', 'png', 'gif'])){
//Show the image
}else{
//dont show image
}
Related
I'm trying to allow user to delete images from a folder on server through html form and PHP.
Here's my html form markup along with PHP script generating list images from the folder mentioned before. I've added checkboxes with path+filename as value.
<form action="delete.php" method="POST">
<div id="formlist">
<?php
$path = ".";
$dh = opendir($path);
$i=1;
$images = glob($path."*.png");
while (($file = readdir($dh)) !== false) {
if($file != "." && $file != ".." && $file != "index.php" && $file != "form.css" && $file != ".htaccess" && $file != "error_log" && $file != "cgi-bin") {
echo "<div class='formshow'><a href='$path/$file' data-lightbox='Formularze' data-title='$file'><img class='formimg' src='$path/$file' width='500px'/></a><input type='checkbox' name='deleteform' value='$path/$file'></div>";
$i++;
}
}
closedir($dh);
?>
</div>
<input type="submit" value="Usun zaznaczone formularze">
</form>
Now, here's my delete.php file:
<?php
$path = ".";
$dh = opendir($path);
$i=1;
$deletepath = glob('deleteform');
while (($file = readdir($dh)) !== false) {
unlink($deletepath);
$i++;
}
?>
I keep this error:
Warning: unlink() expects parameter 1 to be a valid path, array given
I'm quite green with PHP, so I decided to ask you guys - how may I make this work? Should i unserialize() it and add [0], [1] counters?
To delete all itens in a folder user this:
$directory = "folder/";
if ($cat_handle = opendir($directory)) {
while (false !== ($entry = readdir($cat_handle))) {
#unlink($directory.$entry);
}
closedir($cat_handle);
}
You need delete itens or folder?
if you need delete specific item:
$file_name = "fulano.jpg";
if ($handle = opendir('folder/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
if($entry == $file_name){
#unlink('folder/'.$name);
}
}
}
closedir($handle);
}
I believe it works no seu caso, change to accept array now.
The code below will select all of my php files from the named folder and then shuffle them and echo 10 results on my page, the folder contains an index.php file which i would like to be excluded from the results.
<?php
if ($handle = opendir('../folder/')) {
$fileTab = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$fileTab[] = $file;
}
}
closedir($handle);
shuffle($fileTab);
foreach(array_slice($fileTab, 0, 10) as $file) {
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$thelist .= '<p>'.$title.'</p>';
}
}
?>
<?=$thelist?>
I have found a code to exclude index.php but I'm not sure how to incorporate it into my code above.
<?php
$random = array_values( preg_grep( '/^((?!index.php).)*$/', glob("../folder/*.php") ) );
$answer = $random[mt_rand(0, count($random) -1)];
include ($answer);
?>
Why not just modify the line
if ($file != "." && $file != "..") {
to
if ($file != "." && $file != ".." && $file != 'index.php') {
An approach based on glob() instead of readdir():
<?php
$files = glob('../folder/*.php');
shuffle($files);
$selection = array_slice($files, 0, 11);
foreach ($selection as $file) {
$file = basename($file);
if ($file == 'index.php') continue;
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
// ...
}
You can use
$it = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
$it = new RegexIterator($it, '/.php$/i', RegexIterator::MATCH);
$exclude = array("index.php");
foreach ( $it as $splFileInfo ) {
if (in_array($splFileInfo->getBasename(), $exclude))
continue;
// Do other stuff
}
Or Simply
$files = array_filter(glob(__DIR__ . "/*.php"), function ($v) {
return false === strpos($v, 'index.php');
});
You can exclude it while you reading directory content (like you do with '.' and '..'):
if ($handle = opendir('../folder/')) {
$fileTab = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && $file != "index.php") {
$fileTab[] = $file;
}
}
closedir($handle);
shuffle($fileTab);
foreach(array_slice($fileTab, 0, 10) as $file) {
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$thelist .= '<p>'.$title.'</p>';
}
}
?>
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && $file != 'index.php')
$fileTab[] = $file;
}
you could just change this line if ($file != "." && $file != "..") { to if ($file != "." && $file != ".." && $file != 'index.php') {
The code you found replaces your cumbersome directory reading loop.
And it should be just:
$files = preg_grep('~/index\.php$~', glob("../folder/*.php"), PREG_GREP_INVERT);
Get 10 elements as before:
$files = array_slice($files, 0, 10);
Then output those.
I was wondering if anyone could help me write a PHP script for me that renames all the files in a directory in a sequence.
So...
DSC_10342.JPG -> 1.JPG
DSC_10343.JPG -> 2.JPG
DSC_10344.JPG -> 3.JPG
and so on.
Here's my version:
// open the current directory (change this to modify where you're looking)
$dir = opendir('.');
$i = 1;
// loop through all the files in the directory
while (false !== ($file = readdir($dir)))
{
// if the extension is '.jpg'
if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'jpg')
{
// do the rename based on the current iteration
$newName = $i . '.jpg';
rename($file, $newName);
// increase for the next loop
$i++;
}
}
// close the directory handle
closedir($dir);
Use rename to rename the files. You can use this handy script to loop through all files in a directory:
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
Then it's just a matter of looking at the filenames ($file) and figuring out what number to give them. If you need more help than that, just tell me and I'll give more details.
Try this:
$handler = opendir($directory);
$index = 1;
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
rename($directory."/".$file, $directory."/".$index.".JPG");
$index++;
}
}
closedir($handler);
Using someone's snippet it would look like this:
<?php
$path = '.';
$i = 1;
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && is_file($path.'/'.$file)) {
$oldname = $path.'/'.$file;
$path_info = pathinfo($oldname);
rename($oldname, $path.'/'.($i++).'.'.$path_info['extension']);
}
}
closedir($handle);
}
?>
It will rename files with all extensions and skip directories that may be inside your directory.
I am using a php scan directory script that will scan the contents of a directory and then populate the page with links to the directory contents.
<?php
$count = 0;
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {$count++;
print("".$file."<br />\n");
}
}
echo '<br /><br />Return';
closedir($handle);
}
?
I am wondering how I can exclude certain files or file types like test.xml, durka.xslt or .html from showing up on the populated page. I have some code but not sure how to integrate it. Any help would be very appreciated...
?php
if ($handle = opendir(‘.’)) {
while (false !== ($file = readdir($handle)))
{
if ($file != “.” && $file != “..”
&& $file != “NOT-TO-BE-IN-1.php”
&& $file != “NOT-TO-BE-IN-2.html”
&& $file != “NOT-TO-BE-IN-3.jpg”
&& $file != “”
&& $file != “”
&& $file != “”
&& $file != “”
&& $file != “”
)
<?php
// These files will be ignored
$excludedFiles = array (
'excludeMe.file',
'excludeMeAs.well'
);
// These file extensions will be ignored
$excludedExtensions = array (
'html',
'htm',
'php'
);
// Make sure we ignore . and ..
$excludedFiles = array_merge($excludedFiles,array('.','..'));
// Convert to lower case so we are not case-sensitive
for ($i = 0; isset($excludedFiles[$i]); $i++) $excludedFiles[$i] = strtolower(ltrim($excludedFiles[$i],'.'));
for ($i = 0; isset($excludedExtensions[$i]); $i++) $excludedExtensions[$i] = strtolower($excludedExtensions[$i]);
// Loop through directory
$count = 0;
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
$extn = explode('.',$file);
$extn = array_pop($extn);
// Only echo links for files that don't match our rules
if (!in_array(strtolower($file),$excludedFiles) && !in_array(strtolower($extn),$excludedExtensions)) {
$count++;
print("".$file."<br />\n");
}
}
echo '<br /><br />Return';
closedir($handle);
}
?>
<?php
$count = 0;
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".."
&& $file != "NOT-TO-BE-IN-1.php"
&& $file != "NOT-TO-BE-IN-2.html"
&& $file != "NOT-TO-BE-IN-3.jpg"
&& substr($file,-strlen(".html")) != ".html" //if you don't want to include .html files, for instance
&& substr($file,-strlen(".js")) != ".js" //if you don't want to include .js files, for instance
&& $file != ""
) {$count++;
print("".$file."<br />\n");
}
}
echo '<br /><br />Return';
closedir($handle);
}
?>
Other way:
$excludeExtensions = array(
'php',
'html',
'jpg'
);
if ($file != "." && $file != ".." && !in_array(pathinfo($file, PATHINFO_EXTENSION), $excludeExtensions))
EDIT: again I was too late:)
you can also just use glob:
foreach (glob("*.{php|html|jpg}",GLOB_BRACE) as $file) {
echo file_get_contents($file);
}
see http://php.net/manual/en/function.glob.php for more info
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".."
&& $file != "NOT-TO-BE-IN-1.php"
&& $file != "NOT-TO-BE-IN-2.html"
&& $file != "NOT-TO-BE-IN-3.jpg"
&& $file != ""
&& $file != ""
&& $file != ""
&& $file != ""
&& $file != ""
)
echo file_get_contents($file);
will show contents of all pages which haven't name
NOT-TO-BE-IN-1.php
NOT-TO-BE-IN-2.html
NOT-TO-BE-IN-3.jpg
you can restrict certain filepath with
if (!preg_match('/(php|html|jpg)/', $file))
Try something like:
$excluded_files = array('test.xslt');
$excluded_ext = array('html');
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." &&
!in_array($file, $excluded_files) &&
!in_array(pathinfo($file, PATHINFO_EXTENSION), $excluded_ext))
{
// do stuff
}
}
I'm trying to display images in the reverse order of when they were last modified. Unfortunately, get_headers() seems to only work for urls, and both stat['mtime'] and filemtime() fail for me. Are there any other ways for me to get the last modified info for a file? Here's my code at the moment:
if (isset($_GET['start']) && "true" === $_GET['start'])
{
$images = array();
if ($dir = dir('images'))
{
$count = 0;
while(false !== ($file = $dir->read()))
{
if (!is_dir($file) && $file !== '.' && $file !== '..' && (substr($file, -3) === 'jpg' || substr($file, -3) === 'png' || substr($file, -3) === 'gif'))
{
$lastModified = filemtime($file);
$images[$lastModified] = $file;
++$count;
}
}
echo json_encode($images);
}
else { echo "Could not open directory"; }
}
You should prepend the path to the filename, before calling filemtime($file). Try
$lastMod = filemtime("images/".$file);