php loop folder get the file names and size - php

I want make a loop of my fold, get all the files and make a judge, print all the files name witch size are less than 10kb. But I get nothing from this code (no php error hint, just 0 result, and I am sure there has 10 files at lest < 10kb), where is the problem? Thanks.
$folder = dirname('__FILE__')."/../images/*";
foreach(glob($folder) as files){
$size = filesize(files);
if($size<10240){
echo files.'<br />';
}
}

I think there's a typo, because
dirname('__FILE__')
should be (without quotes)
dirname(__FILE__)
and also, your variable files doesn't have a dollar sign
$size = filesize($files);
and also here echo $files
That's it, it should fix your problem

__FILE__ is a magic constant, therefore you cannot wrap it in quotes:
$folder = dirname(__FILE__)."/../images/*";
You missed a $ in files:
$size = filesize($files);
// and
echo $files.'<br />';

Are you sure
$folder = dirname('__FILE__')."/../images/*";
is valid? do you mean
dirname(__FILE__)

Related

name of images from folder not printed on screen in php

I have an html file and i have done the code for printing the names of images from a folder in PHP , but it is not printing the values to screen. if i echo any other thing it is printed on screen.
i have the set the server using xampp.
how to correct this, i make the names of images from that folder printed on screen?
do i need to do anything extra
im a newbie in php. how can i achieve this?
<?php
function findImagesInFolder()
{
$folder = $_GET['C:\xampp\htdocs\firstsite'];
$images = glob($folder . '/*.{png,jpg,jpeg,gif}', GLOB_BRACE);
echo json_encode($images);
exit();
}
?>
It seems you have misused the $_GET variable.
I thing you want to just use the string value, ie.:
$folder = 'C:\xampp\htdocs\firstsite';
And note, the exit() terminates whole script after printing the json_encoded string.
So, to make the function reusable change it to get the path as a parameter $folder:
<?php
function findImagesInFolder($folder, $filter = '*.*')
{
// note, here we expect the path does not trail with backslash
$images = glob($folder . '\\' . $filter, GLOB_BRACE);
return json_encode($images);
}
// call the function with actual path to scan:
$path = 'C:\xampp\htdocs\firstsite';
$filter = '{*.png,*.jpg,*.jpeg,*.gif}';
echo findImagesInFolder($path, $filter);
?>
Note: output as [] means empty array encoded to JSON.

PHP unlink(); No such file or directory

I searched everywhere for this problem and can't find the solution. I have this:
<?php
$file_name = $_GET['name'];
$file_delete = '../u/' . $file_name;
unlink($file_delete);
//header("location: $file_delete");
?>
unlink returns the error: No such file or directory, but if I try header("location: $file_delete"); it opens the file (picture in this case).
Where may I be wrong?
Get Absolute path first for the file to be deleted and check file exist before delete:
$file_name = $_GET['name'];
$base_dir = realpath($_SERVER["DOCUMENT_ROOT"]);
$file_delete = "$base_dir/your_inner_directories_path/$file_name";
if (file_exists($file_delete)) {unlink($file_delete);}
After some research, unlink() doesn't seem to allow you to use relative paths (with "../").
Here's an alternative:
<?php
$file_name = $_GET['name'];
$file_delete = dirname(__FILE__, 2) . '\\u\\' . $file_name;
unlink($file_delete);
?>
$file_delete here is the absolute path to the file you want to delete.
Reminder: / is used for Unix systems, \ for Windows.
PHP doc:
- http://php.net/manual/en/function.unlink.php
- http://php.net/manual/en/function.dirname.php
I also had same issue with my code. What I did to solve the issue is:
First execute:
var_dump($image_variable) // var_dump($file_delete) in your case.
It outputs: string(23)(my-image-path )
When I started counting string I just found 22 characters. I wondered where is the 23rd?
I checked and count carefully, at the end I found that there is space at the end of my image path. So I used php trim() function to remove white spaces. Like,
$trimed_path = trim($image_variable) // trim($file_delete) in your case.
Second: Now execute,
unlink($trimed_path).
OR CHECK LIKE
if(unlink($trimed_path))
{
echo "File Deleted";
}
else
{
echo "Error Deleting File";
}
Took me a couple of hours to figure out. As mentioned above unlink() is picky when it comes to paths.
Solution is:
1st) Define the path (this is how Wordpress does it btw):
define( 'ROOTPATH', dirname(dirname(__FILE__)) . '/' );
2) Do:
unlink(ROOTPATH.'public_html/file.jpg');

If file with name.jpg exists do A else do B

I need to develop a little PHP script that I can run from a cron job which in pseudo code does the following:
//THIS IS PSEUDO CODE
If(file exists with name 'day.jpg')
rename it to 'fixtures.jpg'
else
copy 'master.jpg' to 'fixtures.jpg'
Where day.jpg should be the current day of the month.
I started to replace the pseudo code with the stuff I'm pretty sure how to do:
<?php
if(FILE EXISTS WITH NAME DAY.JPG) {
rename ("DAY.JPG", "fixtures.jpg");
} else {
copy ("master.jpg", "fixtures.jpg");
}
?>
Clearly there are still a few things missing. Like I need to get the filename with the current day of the month and I need to check if the file exists or not.
I guess I need to do something like this $filename='date('j');'.jpg to get the filename, but it isn't really working so I kinda need a bit help there. Also I don't really know how to check if a file exists or not?
$path = __DIR__; // define path here
$fileName = sprintf("%s%d.jpg", $path, date("j"));
$fixtures = $path . DIRECTORY_SEPARATOR . "fixtures.jpg";
$master = $path . DIRECTORY_SEPARATOR . "master.jpg";
file_exists($fileName) ? rename($fileName, $fixtures) : copy($master, $fixtures);
Basicly you need script like above but you need to work on your path. Your code above had syntax problem.
You have a basic syntax problem, it should be:
$filename = date('j') . '.jpg';
You don't put function calls inside quotes, you need quotes around the literal string '.jpg', and you need to use . to concatenate them.
I recommend you read the chapter on Strings in a PHP tutorial.

PHP cant calculate directory

I got a small problem with my PHP webpage. I want to calculate the size of a directory, but I got 2 folders in them, that I don't want to include in the final size. I use following:
function foldersize($directory){
$size = 0;
foreach (glob(rtrim($directory, '/').'/*', GLOB_NOSORT) as $each) {
$size += is_file($each) ? filesize($each) : foldersize($each);
}
return $size;
}
$home_directory = "./files/" . $user_data['unique_id'] . "/";
$dir = foldersize($home_directory);
$dirdel = foldersize($home_directory . "del/");
$dirtmp = foldersize($$home_directory . "tmp/");
$userspace = $dir - $dirdel - $dirtmp;
When I test, which variable the server is able to return I get following result: The server is able to calculate $dir, but it seems to have problems with calculating $dirdel and $dirtmp. So it returns 0. Both folders, however, have files in them. I hope anybody can help me with that. Thank you
i have tried your code and I think is OK - except one small mistake,
$dirtmp = foldersize($$home_directory . "tmp/"); ... there is typo, double dollar, $$home_directory ... other results from function are fine I think

php Update filename from directory

so the title is not full clear, my question , I'm using the code to rename the file from directory present in the server the problem is i have to use the HTML form and php to update the file name, i want to do this : there will be an option on every file for renaming it when i click on the option the box pops up and i have to type the new name for file and save it , any help will be appreciated. (before down voting think about the question.)
The code that I'm using to update the file name
<?php
include("configuration.php");
$target = $_POST['filename'];
$newName = $_POST['newfilename'];
$actfoler = $_REQUEST['folder'];
$file = "files/users/";
$new ="files/users/";
$renameResult = rename($file, $new);
// Evaluate the value returned from the function if needed
if ($renameResult == true) {
echo $file . " is now named " . $new;
} else {
echo "Could not rename that file";
}
header("Location:".$_SERVER["HTTP_REFERER"]);
?>
Try changing these lines:
$file = "uploads/$loggedInUser->username$actfolder/$target";
$new ="uploads/$loggedInUser->username$actfolder/$newName";
To:
$file = "uploads/{$loggedInUser->username}{$actfolder}/{$target}";
$new ="uploads/{$loggedInUser->username}{$actfolder}/{$newName}";
To explain why:
You are using variables inside a string, which means you will want to tell PHP where the variable ends. Especially when referencing objects or arrays, but also when you are placing variables right next to each other. I'm guessing PHP evaluated your original line to uploads/[Object]->usernamePizza/newname
I don't think you can call object properties in a string as you do.
try replace these lines :
$file = "uploads/".$loggedInUser->username."$actfolder/$target";
$new ="uploads/".$loggedInUser->username."$actfolder/$newName";
You may think about echoing $file and $new to confirm the path is nicely built.
On a side note, I'd recommend to really check the entries because this code can obviously lead to major security issues.

Categories