Extract a folder and then search for specific file in PHP - php

I´m building a php programm which uploads a zip file, extracts it and generates a link for a specific file in the extracted folder. Uploading and extracting the folder works fine. Now I´m a bit stuck what to do next. I have to adress the just extracted folder and find the (only) html file that is in it. Then a link to that file has to be generated.
Here is the code I´m using currently:
$zip = new ZipArchive();
if ($zip->open($_FILES['zip_to_upload']['name']) === TRUE)
{
$folderName = trim($zip->getNameIndex(0), '/');
$zip->extractTo(getcwd());
$zip->close();
}
else
{
echo 'Es gab einen Fehler beim Extrahieren der Datei';
}
$dir = getcwd();
$scandir = scandir($dir);
foreach ($scandir as $key => $value)
{
if (!in_array($value,array(".",".."))) //filter . and .. directory on linux-systems
{
if (is_dir($dir . DIRECTORY_SEPARATOR . $value) && $value == $folderName)
{
foreach (glob($value . "/*.html") as $filename) {
$htmlFiles[] = $filename; //this is for later use
echo "<a href='". SK_PICS_SRV . DIRECTORY_SEPARATOR . $filename . "'>" . SK_PICS_SRV . DIRECTORY_SEPARATOR . $filename . "</a>";
}
}
}
}
So this code seems to be working. I just noticed a rather strange problem. The $zip->getNameIndex[0] function behaves differently depending on the program that created the zip file. When I make a zip file with 7zip all seems to work without a problem. $folderName contains the right name of the main folder which I just extracted. For example "folder 01". But when I zip it with the normal windows zip programm the excat same folder (same structure and same containing files) the $zip->getNameIndex[0] contains the wrong value. For example something like "folder 01/images/" or "folder 01/example.html". So it seems to read the zip file differently/ in a wrong way. Do you guys know where that error comes from or how I can avoid it? This really seems strange to me.

Because you specify the extract-path by yourself you can try finding your file with php's function "glob"
have a look at the manual:
Glob
This function will return the name of the file matching the search pattern.
With your extract-path you now have your link to the file.
$dir = "../../suedkurier/werbung/"
$scandir = scandir($dir);
foreach ($scandir as $key => $value)
{
if (!in_array($value,array(".",".."))) //filter . and .. directory on linux-systems
{
if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
{
foreach (glob($dir . DIRECTORY_SEPARATOR . $value . "/*.html") as $filename) {
$files[] = $value . DIRECTORY_SEPARATOR $filename;
}
}
}
}
The matched files will now be saved in the array $files (with the subfolder)
So you get your path like
foreach($files as $file){
echo $dir . DIRECTORY_SEPARATOR . $file;
}

$dir = "the/Directory/You/Extracted/To";
$files1 = scandir($dir);
foreach($files1 as $str)
{
if(strcmp(pathinfo($str, PATHINFO_EXTENSION),"html")===0||strcmp(pathinfo($str, PATHINFO_EXTENSION),"htm")===0)
{
echo $str;
}
}
Get an array of each file in the directory, check the extension of each one for htm/html, then echo the name if true.

Related

rename images and move the renamed images in newly created directory

Here i want to create a new directory called c:/xampp/htdocs/haha/tour/ and in the directory i want to move my renamed images .Here ,i managed to create the new directory but can't move and rename my images.How can i solve this problem??
$dir='c:/xampp/htdocs/practice/haha';
$i=1;
if(is_dir($dir)){
echo dirname($dir).'</br>';
$file=opendir($dir);
while(($data=readdir($file))!==false){
if($data!='.' && $data!='..'){
$info=pathinfo($data,PATHINFO_EXTENSION);
if(!file_exists($dir.'/tour')){
mkdir($dir.'/tour/');
}
rename($dir.$data,$dir.'/tour/'.'image '.$i.'.jpg');
$i++;
}
}
}
You're missing some /:
rename($dir.$data,$dir.'/tour/'.'image '.$i.'.jpg');
^---
$data doesn't contain ANY /, so what you're building is
rename('c:/xampp/htdocs/practice/haha' . 'foo', etc...)
which becomes
rename('c:/xampp/htdocs/practice/hahafoo', etc...)
^^^^^^^---doesn't exist
Try
rename($dir .'/' . $data,$dir.'/tour/'.'image '.$i.'.jpg');
^^^^^^^^
instead.
This should work for you:
Here I just get all images from your directory with glob(). I create the directory if it doesn't exist already with mkdir() and then move all images
with rename().
<?php
$dir = "c:/xampp/htdocs/practice/haha";
$files = glob($dir . "/*.{jpg,png,gif,jepg}", GLOB_BRACE);
//Create directory
if (!file_exists($dir . "/tour")) {
mkdir($dir . "/tour");
}
//Move all images
foreach($files as $key => $file) {
rename($dir . "/" .$data, $dir . "/tour/image" . ($key+1) . ".jpg");
}
?>

PHP - Moving multiple files with different files names to own directory

Hi wonder if you can help,
I'm looking to do this in PHP if someone can help me. I have a number of files that look like this:
"2005532-JoePharnel.pdf"
and
"1205121-HarryCollins.pdf"
Basically I want to create a PHP code that when someone ftp uploads those files to the upload folder that it will 1) Create a directory if it doesn't exist using there name 2) Move the files to the correct directory (E.g. JoePharnel to the JoePharnel Directory ignoring the number at the beginning)
I have looked through alot of code and found this code and have adapted it:
<?php
$attachments = array();
preg_match_all('/([^\[]+)\[([^\]]+)\],?/', $attachments, $matches, PREG_SET_ORDER);
foreach ($matches as $file) {
$attachments[$file[1]] = $file[2];
}
foreach ($attachments as $file => $filename) {
$uploaddir = "upload" . $file;
$casenumdir = "upload/JoePharnel" . $CaseNumber;
$newfiledir = "upload/JoePharnel" . $CaseNumber .'/'. $file;
$each_file = $CaseNumber .'/'. $file;
if(is_dir($casenumdir)==false){
mkdir("$casenumdir", 0700); // Create directory if it does not exist
}
if(file_exists($casenumdir.'/'.$file)==false){
chmod ($uploaddir, 0777);
copy($uploaddir,$newfiledir);
}
$allfiles = $CaseNumber .'/'. $file . "[" . $filename . "]" . ",";
$filelistfinished = preg_replace("/,$/", "", $allfiles);
echo $filelistfinished;
// displays multiple file attachments on the page correctly as: casenumber/testfile1.pdf[testfile1.pdf],casenumber/testfile2.pdf[testfile2.pdf],
],
}
?>
Sorry for the lack of code but best i could find.
Any help is much appreciated.
Thanks.

php foreach using a template html

i have a folder with some folder names, for example 3 folders:
2012-2013, 2013-2014 ,2014-2015
is any way with some php code, to show the names folders in my php like this:
<option value="2012-2013">2012-2013</option>
<option value="2013-2014">2013-2014</option>
<option value="2014-2015">2014-2015</option>
untill I use to show the stuff with php-foreach using a html-template inside the folders.
but i want to show direct the stuff without using the template in the data-folder, is any way? thx.
I suppose you want to recursive the folder in a directory. Below please find the code.
<?php
$folder_name = "c:\\your_folder\\";
$folders = scandir($folder_name);
echo '<select>';
foreach($folders as $folder){
if (is_dir($folder_name . $folder)){
if ($folder != '.' && $folder != '..')
echo '<option value="' . $folder . '">' . $folder . '</option>';
}
}
echo '</select>';
?>
You need to read the directory and print an option tag for each time you find a file that is a folder.
first thing you need to open file handler to your directory by giving the main folder path, than itterate over the directory by using the read method on the folder handler.
By using the "is_dir" function you can determine if the file is a folder, and if so print the file.
I added my solution which is recursive.
function printFolders($path = "", $c = 0) {
if ( empty($path) || !is_dir($path) )
{
return false;
}
//Folder handler
$handler = dir($path);
//Read each file name inside the directory
while(($file = $handler->read()) !== false)
{
// "." is the current folder and ".." is the parent folder
// We skip those folders
if ( $file == "." || $file == ".." )
{
continue;
}
// The current file path
$filePath = $path . "/" . $file;
if ( is_dir($filePath) )
{
//Just to make things more pretty
for($i=0; $i<=$c; $i++) {echo "-";}
//Printing the folder name
echo $file . "<br>";
//Calling the function again with the folder we found
printFolders($filePath, $c+1);
}
}
}
printFolders("path/to/folder");

PHP Delete File script

I have a basic PHP script that displays the file contents of a directory. Here is the script:
<?php
$Dept = "deptTemplate";
if(isset($_REQUEST['dir'])) {
$current_dir = $_REQUEST['dir'];
} else {
$current_dir = 'docs';
}
if ($handle = opendir($current_dir)) {
while (false !== ($file_or_dir = readdir($handle))) {
if(in_array($file_or_dir, array('.', '..'))) continue;
$path = $current_dir.'/'.$file_or_dir;
if(is_file($path)) {
echo '`'.$file_or_dir.' - [Delete button/link]<br/>`';
} else {
echo '``'.$file_or_dir."\n`` - [Delete button/link]`<br/>`";
}
}
closedir($handle);
}
?>
I am trying to create a delete link/button that displays next to each file and when clicked, the corresponding file will be deleted. Would you know how to do this?
Use the built-in unlink($filepath) function.
Sure, you'd have to use unlink() and rmdir(), and you'd need a recursive directory removal function because rmdir() doesn't work on directories with files in them. You'd also want to make sure that the deletion script is really secure to stop people from just deleting everything.
Something like this for the recursive function:
function Remove_Dir($dir)
{
$error = array();
if(is_dir($dir))
{
$files = scandir($dir); //scandir() returns an array of all files/directories in the directory
foreach($files as $file)
{
$fullpath = $dir . "/" . $file;
if($file == '..' || $file == '.')
{
continue; //Skip if ".." or "."
}
elseif(is_dir($fullpath))
{
Remove_Dir($fullpath); //recursively remove nested directories if directory
}
elseif(is_file($fullpath))
{
unlink($fullpath); //Delete file otherwise
}
else
{
$error[] = 'Error on ' . $fullpath . '. Not Directory or File.' //Should be impossible error, because everything in a directory should be a file or directory, or . or .., and thus should be covered.
}
}
$files = scandir($dir); //Check directory again
if(count($files) > 2) //if $files contains more than . and ..
{
Remove_Dir($dir);
}
else
{
rmdir($dir); //Remove directory once all files/directories are removed from within it.
}
if(count($error) != 0)
{return $error;}
else
{return true;}
}
}
Then you just need to pass the file or directory to be deleted through GET or something to the script, probably require urlencode() or something for that, make sure that it's an authorized user with permissions to delete trying to delete the stuff, and unlink() if it's a file, and Remove_Dir() if it's a directory.
You should have to prepend the full path to the directory or file to the directory/file in the script before removing the directory/file.
Some things you'll want for security is firstly making sure that the deletion is taking place in the place it's supposed to, so someone can't do ?dir=/ or something and attempt to delete the entire filesystem from root, which can probably be circumvented by prepending the appropriate path onto the input with something like $dir = '/home/user/public_html/directories/' . $_GET['dir'];, of course then they can potentially delete everything in that path, which means that you need to make sure that the user is authorized to do so.
Need to keep periodic backups of files just in case.
Something like this? Not tested...
<?php
echo '`'.$file_or_dir.' - [Delete button/link]<br/>`';
?>
<?php
if ($_GET['del'] == 1 && isset($_GET['file_or_dir']){
unlink ("path/".$_GET['file_or_dir']);
}
?>
I've worked it out:
I added this delete link on the end of each listed file in the original script:
- < a href="delete.php?file='.$file_or_dir.'&dir=' . $dir . '"> Delete< /a>< br/>';
This link takes me to the download script page, which looked like this:
<?php
ob_start();
$file = $_GET["file"];
$getDir = $_GET["dir"];
$dir = 'docs/' . $getDir . '';
$isFile = ($dir == "") ? 'docs/' . $file . '' : '' . $dir . '/' . $file . '';
if (is_file($isFile)){
if ($dir == "")
unlink('docs/' . $file . '');
else
unlink('' . $dir . '/' . $file . '');
echo '' . $file . ' deleted';
echo ' from ' . $dir . '';
}
else{
rmdir('' . $dir . '/' . $file . '');
echo '' . $dir . '/' . $file . ' deleted';}
header("Location: indexer.php?p=" . $getDir . "");
ob_flush();
?>
It all works brilliantly now, thank you all for your help and suggestions :)

Moving files into directory in foreach loop?

i've no idea how to do that and need your help!
i have an array of filenames called $bundle. (file_one.jpg, file_two.pdf, file_three.etc)
and i have the name of the folder stored in $folder. (my_directory)
i now would like to move all the files stored in $bundle to move to the directory $folder.
how can i do that?
//print count($bundle); //(file_one.jpg, file_two.pdf, file_three.jpg)
$folder = $folder = PATH . '/' . my_directory;
foreach ($bundle as $value) {
//rename(PATH.'/'.$value, $folder . '/' . $value);
}
just so it's not confusing: PATH just stores the local file-path im using for my project. in my case it's just the folder i'm working in-so it's "files".
i have no idea which method i have to use for this and how i could solve that!
thank you for your help!
The code given by you should work with minor changes:
$folder = PATH . '/' . 'my_directory'; // enclose my_directory in quotes.
foreach ($bundle as $value) {
$old = PATH.'/'.$value, $folder;
$new = $folder . '/' . $value;
if(rename($old,$new) !== false) {
// renamed $old to $new
}else{
// rename failed.
}
}
$folder = PATH . '/' . $folder;
foreach ($bundle as $value) {
$old = PATH.'/'.$value;
$new = $folder . '/' . $value;
if(rename($old,$new) !== false) {
// renamed $old to $new
}else{
// rename failed.
}
}
Untested but should work:
function bulkMove($src, $dest) {
foreach(new GlobIterator($src) as $fileObject) {
if($fileObject->isFile()) {
rename(
$fileObject->getPathname(),
rtrim($dest, '\\/') . DIRECTORY_SEPARATOR . $fileObject->getBasename()
);
}
}
}
bulkMove('/path/to/folder/*', '/path/to/new/folder');
Could add some checks to see if the destination folder is writable. If you dont need wildcard matching, change the GlobIterator to DirectoryIterator. That would also eliminate the need for PHP5.3

Categories