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.
Related
I have a users directory and a child directory for the login/register system. I have a file, testing.php, to try to figure out how to create a directory in the users directory AND create a PHP file within that same directory. Here's my code:
<?php
$directoryname = "SomeDirectory";
$directory = "../" . $directoryname;
mkdir($directory);
$file = "../" . "ActivationFile";
fopen("$file", "w");
?>
I'm able to get mdkir($directory) to work, but not the fopen("$file", "w").
Try this, this should normally solve your problem.
PHP delivers some functions to manipulate folder & path, it's recommended to use them.
For example to get the current parent folder, you can use dirname function.
$directoryname = dirname(dirname(__FILE__)) . "/SomeDirectory";
if (!is_dir($directoryname)) {
mkdir($directoryname);
}
$file = "ActivationFile";
$handle = fopen($directoryname . '/' . $file, "w");
fputs($handle, 'Your data');
fclose($handle);
This line is equivalent to "../SomeDirectory"
dirname(dirname(__FILE__)) . "/SomeDirectory";
So when you open the file, you open "../SomeDirectory/ActivationFile"
fopen($directoryname . '/' . $file, "w");
You can use the function touch() in order to create a file:
If the file does not exist, it will be created.
You also forgot to re-use $directory when specifying the filepath, so the file was not created in the new directory.
As reported by Fred -ii- in a comment, error reporting should also be enabled. Here is the code with these changes:
<?php
// Enable error output, source: http://php.net/manual/en/function.error-reporting.php#85096
error_reporting(E_ALL);
ini_set("display_errors", 1);
$directoryname = "SomeDirectory";
$directory = "../" . $directoryname;
mkdir($directory);
$file = $directory . "/ActivationFile";
touch($file);
try this:
$dirname = $_POST["DirectoryName"];
$filename = "/folder/{$dirname}/";
if (file_exists($filename)) {
echo "The directory {$dirname} exists";
} else {
mkdir("folder/{$dirname}", 0777);
echo "The directory {$dirname} was successfully created.";
}
note.. all folders chmod set to 777 for testing.
Okay, so i have been trying to design a simple cloud storage file system in php.After users log in they can upload and browse files in their account.
I am having an issue with my php code that scans the user's storage area. I have a script called scan.php that is called to return all of the users files and folders that they saved.
I originally placed the scan script in the directory called files and it worked properly, when the user logged in the scan script scanned the users files using "scan(files/usernamevalue)".
However I decided that I would prefer to move the scan script inside the files area that way the php script would only have to call scan using "scan(usernamevalue)". However now my script does not return the users files and folders.
<?php
session_start();
$userfileloc = $_SESSION["activeuser"];
$dir = $userfileloc;
// Run the recursive function
$response = scan($dir);
// This function scans the files folder recursively, and builds a large array
function scan($dir)
{
$files = array();
// Is there actually such a folder/file?
$i=0;
if(file_exists($dir))
{
foreach(scandir($dir) as $f)
{
if(!$f || $f[0] === '.')
{
continue; // Ignore hidden files
}
if(!is_dir($dir . '/' . $f))
{
// It is a file
$files[] = array
(
"name" => $f,
"type" => "file",
"path" => $dir . '/' . $f,
"size" => filesize($dir . '/' . $f) // Gets the size of this file
);
//testing that code actually finding files
echo "type = file, ";
echo $f .", ";
echo $dir . '/' . $f. ", ";
echo filesize($dir . '/' . $f)." ";
echo"\n";
}
else
{
// The path is a folder
$files[] = array
(
"name" => $f,
"type" => "folder",
"path" => $dir . '/' . $f,
"items" => scan($dir . '/' . $f) // Recursively get the contents of the folder
);
//testing that code actually finding files
echo "type = folder, ";
echo $f .", ";
echo $dir . '/' . $f. ", ";
echo filesize($dir . '/' . $f)." ";
echo"\n";
}
}
}
else
{
echo "dir does not exist";
}
}
// Output the directory listing as JSON
if(!$response)
{ echo"failes to respond \n";}
header('Content-type: application/json');
echo json_encode(array(
"name" => $userfileloc,
"type" => "folder",
"path" => $dire,
"items" => $response
));
?>
As you can see i added i echoed out all of the results to see if there
was any error in the scan process, here is what i get from the output as you
can see the function returns null, but the files are being scanned, i cant
seem to figure out where i am going wrong. Your help would be greatly
appreciated. Thank you.
type = file, HotAirBalloonDash.png, test/HotAirBalloonDash.png, 658616
type = folder, New directory, test/New directory, 4096
type = file, Transparent.png, test/Transparent.png, 213
failes to respond
{"name":"test","type":"folder","path":null,"items":null}
You forgot to return files or folders in scan function, just echo values. That is the reason why you get null values in the response.
Possible solution is to return $files variable in all cases.
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");
}
?>
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.
I'm trying to recursively iterate through a group of dirs that contain either files to upload or another dir to check for files to upload.
So far, I'm getting my script to go 2 levels deep into the filesystem, but I haven't figured out a way to keep my current full filepath in scope for my function:
function getPathsinFolder($basepath = null) {
$fullpath = 'www/doc_upload/test_batch_01/';
if(isset($basepath)):
$files = scandir($fullpath . $basepath . '/');
else:
$files = scandir($fullpath);
endif;
$one = array_shift($files); // to remove . & ..
$two = array_shift($files);
foreach($files as $file):
$type = filetype($fullpath . $file);
print $file . ' is a ' . $type . '<br/>';
if($type == 'dir'):
getPathsinFolder($file);
elseif(($type == 'file')):
//uploadDocsinFolder($file);
endif;
endforeach;
}
So, everytime I call getPathsinFolder I have the basepath I started with plus the current name of the directory I'm scandirring. But I'm missing the intermediate folders in between. How to keep the full current filepath in scope?
Very simple. If you want recursion, you need to pass the whole path as a parameter when you call your getPathsinFolder().
Scanning a large directory tree might be more efficient using a stack to save the intermediate paths (which would normally go on the heap), rather than use much more of the system stack (it has to save the path as well as a whole frame for the next level of the function call.
Thank you. Yes, I needed to build the full path inside the function. Here is the version that works:
function getPathsinFolder($path = null) {
if(isset($path)):
$files = scandir($path);
else: // Default path
$path = 'www/doc_upload/';
$files = scandir($path);
endif;
// Remove . & .. dirs
$remove_onedot = array_shift($files);
$remove_twodot = array_shift($files);
var_dump($files);
foreach($files as $file):
$type = filetype($path . '/' . $file);
print $file . ' is a ' . $type . '<br/>';
$fullpath = $path . $file . '/';
var_dump($fullpath);
if($type == 'dir'):
getPathsinFolder($fullpath);
elseif(($type == 'file')):
//uploadDocsinFolder($file);
endif;
endforeach;
}