PHP cant calculate directory - php

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

Related

Name each new dir with the next available number with php

I'm working on a php file where I want to create one or more directories with names ranging from 1 to 999 or more. I'm creating the first of all directories using the following code:
<?php
$id = '001';
mkdir($id)
?>
What I want to succeed is to automatically create a new directory using as a name the next available number (i.e. 002, 003, 004, 005 etc) either as a string or an integer. However, I really stuck and I try to use:
<?php
$id = 001;
if (file_exists($id)) {
$id = $id + 1;
mkdir($id);
}
?>
..but it doesn't work. Any ideas?
I forgot to mention that the above code is part of the if statement inside the same php code.
Several ways to do this, depending on your use case. This function may work for you:
<?PHP
function makedir($id){
if(file_exists($id)){
$id++;
makedir($id);
}else{
mkdir($id);
return true;
}
}
makedir(1);
This solution of incremented directory names is going to become ugly after a while though; you should probably find a better solution to your problem.
You could do something like this:
// Loop through all numbers.
for ($i = 1; $i <= 999; $i++) {
// Get the formatted dir name (prepending 0s)
$dir = sprintf('%03d', $i);
// If the dir doesn't exist, create it.
if (!file_exists($dir)) {
mkdir($dir);
}
}
Edit: the above was assuming you wanted to make all 999 directories. You could do the following to just append the next available number:
function createDir($dir) {
$newDir = $dir;
$num = 1;
while (file_exists($newDir)) {
$newDir = $dir.sprintf('%03d', $num++);
}
return $newDir;
}

How to download images from various URL (same path)

I want to download about 200 images from an URL. For instance: Fetch www.web.com/images/001.png and download, fetch www.web.com/images/002.png and download and finish in 200.png.
I've read Grab/download images from multiple pages using php preg_match_all & cURL but I don't know how to modify the PHP to do that thing.
I'll be very appreciated if you can help me. Thank you so much
The simplest way that comes to mind, is to create a for loop, which counts from 1 to 200 and for every count, it then does a request for the image and saves it to the disk (I assume you want to save the image to your disk). Working example can be found at the bottom.
Let's start by settings some variables:
$baseUrl = 'http://www.web.com/';
$localDirectory = 'downloaded_images/';
$maxImageNumber = 200;
The first variable $baseUrl defines where the images will be loaded from. The second defines your local directory in which the images will be saved. Please make sure that this directory exists before running the code, because it will not be automatically generated. The last variable, $maxImageNumber stores the largest image number, which we will need for the for loop.
After setting the variables, we can write the for loop. Separated by semicolons ; there are three parts in the brackets. First one being the starting point of the number we will be counting upwards. The second makes sure we don't go over our limit and the last one just states that the number will be counted up, using the ++ shorthand.
for($imageNumber = 1; $imageNumber <= $maxImageNumber; $imageNumber++) {
// code goes here
}
Inside this for loop we can now generate our file name and download/save the image to the disk. The first line uses the function str_pad() to add leading 0s to the image file (just like in your example) and then adds the extension .png to the name. This allows us to reuse the file name for loading as well as for saving. Second line loads the image with the function file_get_contents() by combining the base and the image file name. In the last line we use file_put_contents() to save the $fileData, we loaded just before, to the disk (using the local directory and the image file name).
$imageFileName = str_pad($imageNumber, 3, '0', STR_PAD_LEFT) . '.png';
$fileData = file_get_contents($baseUrl . $imageFileName);
file_put_contents($localDirectory . $imageFileName, $fileData);
The complete code should look like this:
<?php
$baseUrl = 'http://www.web.com/images/';
$localDirectory = 'downloaded_images/';
$maxImageNumber = 10;
for($imageNumber = 1; $imageNumber <= $maxImageNumber; $imageNumber++) {
$imageFileName = str_pad($imageNumber, 3, '0', STR_PAD_LEFT) . '.png';
$fileData = file_get_contents($baseUrl . $imageFileName);
file_put_contents($localDirectory . $imageFileName, $fileData);
}
In the unlikely event that this all should not work, there are a few things you can try
check that the $localDirectory exists and is writable.
if the file_get_contents() should not work, you can use curl instead
make sure the computer this code is executed on can access the remote server
Thank you so much but imagine that pics are in www.web.com/image_0001_big.png and www.web.com/image_002_big.png and so on... (last will be web.com/image_0200_big.png)
This doesn't work (i don't know why)
<?php
$baseUrl = 'http://www.web.com/images';
$localDirectory = 'downloaded_images/';
$maxImageNumber = 200;
$input='image_';
for($imageNumber = 001; $imageNumber <= $maxImageNumber; $imageNumber++) {
$imageFileName = str_pad($input, $imageNumber, 4, '_big', STR_PAD_LEFT) . '.png';
$fileData = file_get_contents($baseUrl . $imageFileName);
file_put_contents($localDirectory . $imageFileName, $fileData);
}
Thanks. You're amazing! Thanks for the help! I'm learning PHP and I'm a beginner yet:(
My error:
Warning: str_pad() expects at most 4 parameters, 5 given in C:\xampp\htdocs\auto.php on line 9
Warning: file_get_contents(http://www.web.com/images/.png): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in C:\xampp\htdocs\auto.php on line 10
I've found a semi-solution:_
<?php
$baseUrl = 'http://web.com/images';
$localDirectory = 'downloaded_images/';
$maxImageNumber = 400;
$input='image0';
$input2='big';
$extension ='.png';
for($imageNumber = 100; $imageNumber <= $maxImageNumber; $imageNumber++) {
$fileData = file_get_contents($baseUrl . $input . $imageNumber . $input2 . $extension);
file_put_contents($localDirectory . $imageNumber, $fileData);
}
?>
The problem is when... 0001 0009 0010 !! I want to tell php "hey, always 4 digits"

Multiple Random Includes from Directory with Sub-Directories

I have a directory containing sub directories which each contain a series of files. I'm looking for a script that will look inside the sub directories and randomly return a specified number of files.
There are a few scripts that can search a single directories (not sub folders), and other scripts that can search sub folders but only return one file.
To put a little context on the situation, the returned files will be included as li's in an rotating banner.
Thanks in advance for any help, hopefully this is possible.
I think I've got there, not exactly what I set out to achieve but works good enough, arguably better for the purpose, I'm using the following function:
<?php function RandomFile($folder='', $extensions='.*'){
// fix path:
$folder = trim($folder);
$folder = ($folder == '') ? './' : $folder;
// check folder:
if (!is_dir($folder)){ die('invalid folder given!'); }
// create files array
$files = array();
// open directory
if ($dir = #opendir($folder)){
// go trough all files:
while($file = readdir($dir)){
if (!preg_match('/^\.+$/', $file) and
preg_match('/\.('.$extensions.')$/', $file)){
// feed the array:
$files[] = $file;
}
}
// close directory
closedir($dir);
}
else {
die('Could not open the folder "'.$folder.'"');
}
if (count($files) == 0){
die('No files where found :-(');
}
// seed random function:
mt_srand((double)microtime()*1000000);
// get an random index:
$rand = mt_rand(0, count($files)-1);
// check again:
if (!isset($files[$rand])){
die('Array index was not found! very strange!');
}
// return the random file:
return $folder . "/" . $files[$rand];
}
$random1 = RandomFile('project-banners/website-design');
while (!$random2 || $random2 == $random1) {
$random2 = RandomFile('project-banners/logo-design');
}
while (!$random3 || $random3 == $random1 || $random3 == $random2) {
$random3 = RandomFile('project-banners/design-for-print');
}
?>
And echoing the results into the container (in this case the ul):
<?php include($random1) ;?>
<?php include($random2) ;?>
<?php include($random3) ;?>
Thanks to quickshiftin for his help, however it was a little above my skill level.
For info the original script which I changed an be found at:
http://randaclay.com/tips-tools/multiple-random-image-php-script/
Scrubbing the filesystem every single time to randomly select a file to display will be really slow. You should index the directory structure ahead of time. You can do this many ways, try a simple find command or if you really want to use PHP my favorite choice would be RecursiveDirectoryIterator plus RecursiveIteratorIterator.
Put all the results into one file and just read from there when you select a file to display. You can use the line numbers as an index, and the rand function to pick a line and thus a file to display. You might want to consider something more evenly distributed than rand though, you know to keep the advertisers happy :)
EDIT:
Adding a simple real-world example:
// define the location of the portfolio directory
define('PORTFOLIO_ROOT', '/Users/quickshiftin/junk-php');
// and a place where we'll store the index
define('FILE_INDEX', '/tmp/porfolio-map.txt');
// if the index doesn't exist, build it
// (this doesn't take into account changes to the portfolio files)
if(!file_exists(FILE_INDEX))
shell_exec('find ' . PORTFOLIO_ROOT . ' > ' . FILE_INDEX);
// read the index into memory (very slow but easy way to do this)
$aIndex = file(FILE_INDEX);
// randomly select an index
$iIndex = rand(0, count($aIndex) - 1);
// spit out the filename
var_dump(trim($aIndex[$iIndex]));

php loop folder get the file names and size

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__)

My delete function does not delete the targeted file

Basically I could upload files based on a project. Whenever I create a project, a new directory is created with the directory name as the project_name e.g. this is a test -> this-is-a-test. But my problem is I couldn't delete a file in a directory.
function delete_image($id)
{
$this->load->model(array('work_model', 'project_model'));
$result = $this->work_model->get_work($id);
$result = $this->project_model->get_project($result->project_id);
$dir = str_replace(" ", "-", $result->project_name);
$result = $this->work_model->delete($id);
if (isset($result)){
unlink('./uploads/' . $dir . '/' . $result->full_path);
}
redirect('admin/project/view_project/' . $result->project_id);
}
Need help on this thanks.
Well the error message is self-explanatory.
$result is not an object.
Your problem is matter of debugging, not SO question. And matter of reading error messages, of course. Why do you ask here what's going wrong if you already have explanation from your PHP? And, on the other hand, noone here know your code and have no idea what type of variable get_work($id) supposed to return.
This line is brilliant:
if (isset($result)){
Of course it is set, you have set it 3 times!
Use different variable names for each result you return. Why not use:
function delete_image($id)
{
$this->load->model(array('work_model', 'project_model'));
$work = $this->work_model->get_work($id);
$project = $this->project_model->get_project($work->project_id);
$dir = str_replace(" ", "-", $project->project_name);
if ($this->work_model->delete($id))
{
unlink('./uploads/' . $dir . '/' . $project->full_path);
}
redirect('admin/project/view_project/' . $project->project_id);
}
If that doesn't work, try some debug steps.
var_dump($this->work_model->delete($id));
That will tell you TRUE/FALSE, I'd assume right now it is FALSE which is why unlink isn't erroring or succeeding.
Debug is the way forward. We can't do it for you!

Categories