PHP Filehandling, code never reached - php

I've got a piece of code with some error i've been trying to find all day... what this (should) does is: go through all the files in a folder, check if it's a image type, if it is, create a thumbnail in some folder. It does the job BUT: it doesnt continue afterwards, I put a echo command and its never executed. I apprechiate any help! thanks alot.
$bilddateitypen = array('gif','jpg','JPG','GIF');
$importdir = '../sync';
if ($handle = opendir($importdir)) {
while (($file = readdir($handle)) !== false) {
if (!is_dir($importdir."/".$file) && is_file($importdir."/".$file)) {
$ex = explode('.',$file);
if(in_array($ex[count($ex)-1], $bilddateitypen)) {
$file = utf8_decode($file);
$thumbnail = new thumbnail($importdir."/".$file);
$thumbnail->jpeg_quality(93);
$thumbnail->save("../shop/images/product_images/original_images/".$file);
$thumbnail->size_auto(500);
$thumbnail->save("../shop/images/product_images/popup_images/".$file);
$thumbnail->size_auto(200);
$thumbnail->save("../shop/images/product_images/info_images/".$file);
$thumbnail->size_auto(112);
$thumbnail->save("../shop/images/product_images/thumbnail_images/".$file);
} else {
continue;
}
}
}
closedir($handle);
}
echo "Hallo Welt";

It looks like you never update the value of $handle within the while loop, therefore creating an infinite loop.

Try run code only with echo without resizing images. Try var_dump variables and check what is in. Make sure you have error reporting on. If some error occur.
Check image extension this way:
public static function isImage($fileName)
{
$type = exif_imagetype($fileName);
if (!(($type == IMAGETYPE_JPEG) || ($type == IMAGETYPE_GIF) || ($type == IMAGETYPE_PNG)))
return false;
return true;
}

Related

unable to delete a last file in folder while deleting folder using php

I am calling my php function from some other website which delete a folder on my server in background.
This is a function which I am using to delete a folder.
public static function remove($dir)
{
if (is_dir($dir)) {
$diropen = opendir($dir);
while($d = readdir($diropen)) {
if ($d!= '.' && $d != '..') {
self::remove($dir . "/$d");
}
}
#rmdir($dir);
} elseif (is_file($dir)) {
#unlink($dir);
}
}
If I am having three files in folder then it deletes only two and unable to delete last file or unlink fails on last file.
If I am having two files then it deletes only one file.
I have checked writable permission using is_writable it is true for all files.
Can somebody please help me out. or how to debug this behavior as this function is getting called in background.
my directory was open in some other function , so I closedir my folder and then above function working fine.
<?php
function delete_directory($target) {
if (is_dir($target))
$dir_handle = opendir($target);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($target.'/'.$file);
}
}
closedir($dir_handle);
rmdir($target);
return true;
}
?>
use closedir and you'll be fine.

Warning with, fopen, feof and fgetcsv

I'm in trouble, I am failing to understand why this error is happening.
So when I only run this code,
function getClientProject($cliente)
{
$file = fopen("Projetos.csv","r");
$ArrayCount = 0;
$bool = false;
while(! feof($file))
{
$data = fgetcsv($file);
if($data[0] != '')
{
if(substr_compare($data[0],$cliente, 0, 3) == 0)
{
if($ArrayCount > 0)
{
$total = count($OpenProject);
for($i=0;$i<$total;$i++)
{
if($OpenProject[$i] == $data[0])
$bool = true;
}
if($bool == false)
{
$OpenProject[$ArrayCount] = $data[0];
$ArrayCount++;
}
}else
{
$OpenProject[$ArrayCount] = $data[0];
$ArrayCount++;
}
}
}
}
fclose($file);
return $OpenProject;
}
It works and returns the Array. But when I call the function this way,
include_once 'CRM files/TSread.php';
$arrayC = getClientProject('SLA');
var_dump($arrayC);
No longer works and me these errors,
What am I doing wrong?
path, the file i'm using is "Projeto.php":
and my CRM files folder:
You are opening the file using a relative path. You assume that Projetos.csv is always in the same directory as the TSread.php file. Although, when including it, you seem to be in a higher directory (outside of the CRM files directory), therefor PHP can no longer find your CSV file, since it's trying to open it relative to the upper directory now.
You could pass the full path to your getClientProject method to avoid this. So, you would get something like:
$arrayC = getClientProject('SLA', __DIR__ . '/CRM files/Projectos.csv');
Obviously, you will need to change your function a little to work with this new constructor, so it should like something like this:
function getClientProject($cliente, $csv) {
$file = fopen($csv, "r");
// Followed by the rest of your function

Website Self Destruct from Browser Bar

IS there a file that I can upload onto my website (my website is a website that contains very very very sensitive information) that when navigated to in the browser (www.example.com/script.php) can be executed to delete all files from the folder it is uplaoded into/ I want to be able to delete this information easy as that. Kind of like a Self Destruct Button. MY website is used for testing sensitive equiptment commands for diamond blade cutters. We got almost the perfect cut for a diamond which makes ours very valuable. Our site was hacked and there was nothn gi could do in the backend because the password was changed on us so i want to put a secret file in there that does this.
i would not recommend that as a solution,
why don't you secure the script instead ?
anyway just for the fun of it here is a function that will delete a folder
function deleteAll($directory, $empty = false) {
$t= time(); // you can also use it to delete old files by subtracting from this
if(substr($directory,-1) == "/") {
$directory = substr($directory,0,-1);
}
if(!file_exists($directory) || !is_dir($directory)) {
return false;
} elseif(!is_readable($directory)) {
return false;
} else {
$directoryHandle = opendir($directory);
while ($contents = readdir($directoryHandle)) {
if($contents != '.' && $contents != '..') {
if(filemtime($directory . "/" . $contents) < $t) {
$path = $directory . "/" . $contents;
if(is_dir($path)) {
#deleteAll($path);
} else {
#unlink($path);
}
}
}
}
closedir($directoryHandle);
if($empty == false) {
if(!#rmdir($directory)) {
return false;
}
}
return true;
}
}
(!) be careful when you use it it will DELETE everything you can call it like this deleteAll(".", true);
but this is not a solution look into securing your script

Make PHP include randomizer not repeat itself

Situation
I have a relatively short php code I found and tweaked that includes a random html file from my 'randomizer' folder into my page.
Here is the code
<?php
error_reporting(0);
function random_file($string){
return ((file_exists($string))&&(preg_match('#(\.html)$#i',$string))) ? true : false ;
}
define('OUTPUT_TYPE','text');
define('RANDOM_FILES_FOLDER','randomizer/');
$my_array = Array();
$my_dir = RANDOM_FILES_FOLDER ;
if ($dir = #opendir("$my_dir")) {
while (($file = readdir($dir)) !== false) {
if ($file != "." && $file != ".." && !is_dir($my_dir.$file))
{
switch(OUTPUT_TYPE):
case'text':
if(random_file($my_dir.$file)){
$my_array[] = $file;
}
break;
default:
break;
endswitch;
}
}
closedir($dir);
}
if(count($my_array)>0){
$random_number = rand(0, count($my_array)-1);
$random_file = $my_array[$random_number];
switch(OUTPUT_TYPE):
case'text':
include($my_dir.$random_file);
break;
default:
break;
endswitch;
}
?>
Question
It does what it is supposed to do (perhaps someone can trim/optimize that code for me) but I have only a few files to randomize and I don't want the same file to appear twice when I refresh or open the page a day after.
I think cookies may be the answer, but not sure how to do anything with them.
Can anyone write a piece code to add to mine to do that or provide a code that has all those attributes? keep in mind it must include files at random from a folder, I don't want the code from those files on my actual page code for CMS purposes
Keep in mind I am a PHP and Javascript beginner with VERY basic knowledge, so please dumb it down for me.
Thanks!
Very rough:
session_start();
$dir = 'randomizer/';
if (empty($_SESSION['files'])) {
$_SESSION['files'] = array_filter(scandir($dir), function ($file) use ($dir) {
return is_file($dir . $file) && preg_match('#(\.html)$#i', $file);
});
shuffle($_SESSION['files']);
}
include $dir . array_shift($_SESSION['files']);
Keep a list of all candidate files in the session, use them one by one. That way all files will be displayed once in random order before the cycle starts again. Only not recommended if the list is very long.
It's worth noting that the array_filter callback syntax requires PHP 5.3.
This is not the perfect way to do this but it will work(intentionally simple):
Include this after the line $random_file = $my_array[$random_number];
$oldFile = ''
if(!empty($_COOKIE['oldfilename']) {
$oldFile = $_COOKIE['oldfilename'];
}
while ($oldFile == $random_file) {
$random_number = rand(0, count($my_array)-1);
$random_file = $my_array[$random_number];
}
setcookie('oldfilename', $random_file);

Best way to check if a dir is empty whith php

Is there a better way to check if a dir is empty than parsing it?
Don't think so. Shortest/quickest way I can think of is the following, which should work as far as I can see.
function dir_is_empty($path)
{
$empty = true;
$dir = opendir($path);
while($file = readdir($dir))
{
if($file != '.' && $file != '..')
{
$empty = false;
break;
}
}
closedir($dir);
return $empty;
}
This should only go through a maximum of 3 files. The two . and .. and potentially whatever comes next. If something comes next, it's not empty, and if not, well then it's empty.
Not really, but you can try to delete it. If it fails, its not empty (or you just can't delete it ;))
function dirIsEmpty ($dir) {
return rmdir($dir) && mkdir($dir);
}
Update:
It seems, that the answer, that takes the condition "without parsing" into account, doesn't find much friends ;)
function dirIsEmpty ($dir) {
return count(glob("$dir/**/*")) === 0:
}
Note, that this assumes, that the directory and every subdirectory doesn't contain any hidden file (starting with a single .).

Categories