How do i set up path and folder pattern in PHP? - php

So I am trying to set up path for my pdf files that are stored in a folder structure. The file that has to be selected depends on the user input.
I want to set up first the absolute path and then a folder pattern.
The folder where I have stored my files is:
C:\Apache24\htdocs\archivedb\Tourenfahrer\2017\5
The last three folders changes as per user input.
I have setup my root directory in my config.php like this:
define( 'ROOT_DIR', dirname(__FILE__) );
Now in my php file I am recieving my variables, which will be my folder names to search for the files.
<?php
require_once 'conf/config.php';
if (!empty($_REQUEST['magName'] && $_REQUEST['year'] && $_REQUEST['issue']
)) {
$magazineName = $_REQUEST['magName'];
$year = $_REQUEST['year'] ;
$issue = $_REQUEST['issue'] ;
}
Now Please tell how to access the respective folder using these variables?
and how can i set up a pattern with this using glob(); ?

Please try this
define('ROOT_DIR', dirname(__FILE__));
define('DS', DIRECTORY_SEPARATOR);
if (!empty($_REQUEST['magName'] && $_REQUEST['year'] && $_REQUEST['issue'])) {
$magazineName = $_REQUEST['magName'];
$year = $_REQUEST['year'];
$issue = $_REQUEST['issue'];
$dir = $magazineName . DS . $year . DS . $issue;
echo "<h3>Use scandir:</h3>";
$files = scandir(ROOT_DIR . DS . $dir);
foreach ($files as $file) {
echo basename($file) . "<br>";
}
echo "<h3>Use glob:</h3>";
foreach (glob($dir . DS . '*') as $filename) {
echo basename($filename) . "<br>";
}
}

Related

php copy function from one folder to another

Here is my code, what I am trying to do is take the file post.php or $file from the root of the directory that it is originally from, then put it inside this uniqueID directory, or it should finally arrive in the $newFolder5 variable to complete. The $root in the !copy function is a path pointing to the file inside the current directory, then it should go it the $newFolder5 directory when the copy function is executed on the page load. Can $root or the source of the copy be a string with a directory to the file?
<?php
$unique = uniqid();
$root = '/gallry/' . $dir_auth1 . '/'. 'post.php';
$folder = mkdir($unique, 0755);
$uniqueFolder = '/' . $unique . '/' . 'post.php';
$destination2 = $dir_auth1 . '/' . $unique . '/' . 'post.php';
$newFolder = '/' . $dir_auth1 . $uniqueFolder;
if (!copy($root, $newFolder)) {
echo " status not created.";
} else {
echo "Success!";
}
?>
I changed $dir_auth1 to 'aidan', since that is the root directory that the post.php is in.
In short, what Im trying to do is create a folder/directory with a uniqid() and put post.php inside of it. Or copy it.
You're not creating the same directory that you're trying to copy into.
$unique = uniqid();
$root = "/gallry/$dir_auth1/post.php";
$uniqueFolder = "/$dir_auth1/$unique";
$destFile = "$uniqueFolder/post.php";
if (mkdir($uniqueFolder)) {
if (copy($root, $destFile)) {
echo "Success!";
} else {
echo " status not created";
}
} else {
echo "Unable to create folder $uniqueFolder";
}

php function to search paths for filename WITHOUT extension

Right so i'm making a configuration class that will use an array of different file types in 4 main locations. Now I want to make it so that the configuration class will search these locations in order at the moment i'm using the following
if (file_exists(ROOT . DS . 'Application/Config/' . APP_ENV . DS . $file)) {
$this->filePath = ROOT . DS . 'Application/Config/' . APP_ENV . DS . $file;
echo $this->filePath;
} else {
if (file_exists(ROOT . DS . "Application/Config/$file")) {
$this->filePath = ROOT . DS . "Application/Config/$file";
echo $this->filePath;
} else {
if (file_exists(CARBON_PATH . 'Config' . DS . APP_ENV . DS . $file)) {
$this->filePath = CARBON_PATH . 'Config' . DS . APP_ENV . DS . $file;
echo $this->filePath;
} else {
if (file_exists(CARBON_PATH . "Config/$file")) {
$this->filePath = CARBON_PATH . "Config/$file";
echo $this->filePath;
} else {
throw new \Exception("Unable to locate: $file, Please check it exists");
}
}
}
}
pretty messy and not very flexible.
What I want to be able to do is search the locations in the same order BY FILE NAME ONLY after finding the first match It would then return the file with the extension for the configuration class to use the correct method to parse into a php array and so on.
What is the best way to search these locations for a file name
Example
Say we want a database configuration file as you can see there are 2
ConfigLocation1/Dev/
/file.php
/database.json
ConfigLocation1/
/database.ini
/anotherfile.json
I would want to use the function like so
config::findFile('database');
and it return
$result = ConfigLocation1/Dev/database.json
but if it wasnt found here then then
$result = ConfigLocation1/database.ini
Not very good at explaining things so hope the example helps
As you mentioned you need to check for file in 4 locations, so instead of if conditions, create an array of directories and loop through.
and you can use glob, to find a file irrespective of extension. see my example below:-
//Make a array of directory where you want to look for files.
$dirs = array(
ROOT . DS . 'Application/Config/' . APP_ENV . DS,
CARBON_PATH . 'Config' . DS . APP_ENV . DS
);
function findFiles($directory, $filename){
$match = array();
foreach ($directory => $dir) {
$files = glob($dir.$filename);
foreach ($files as $file) {
$match[] = $file;
}
}
return $match;
}
// to find database
$results = findFiles($dirs, 'database.*');

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 - JPath Moving Multiple files to correct directory

See my last question as this links to it: PHP - Moving multiple files with different files names to own directory
So i decided to using the Joomla API however, the documentation was for 1.5 and 2.5 system only but i'm using 3.0. 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)
Updated: 23/10/14 - 14:05:
My new code creates the folder but won't move the file in the upload into that new folder, code is below:
<?php
define( '_JEXEC', 1);
define('JPATH', dirname(__FILE__) );
if (!defined('DS')){
define( 'DS', DIRECTORY_SEPARATOR );
$parts = explode( DS, JPATH );
$script_root = implode( DS, $parts ) ;
// check path
$x = array_search ( 'administrator', $parts );
if (!$x) exit;
$path = '';
for ($i=0; $i < $x; $i++){
$path = $path.$parts[$i].DS;
}
// remove last DS
$path = substr($path, 0, -1);
if (!defined('JPATH_BASE')){
define('JPATH_BASE', $path );
}
if (!defined('JPATH_SITE')){
define('JPATH_SITE', $path );
}
/* Required Files */
require_once ( JPATH_SITE . DS . 'includes' . DS . 'defines.php' );
require_once ( JPATH_SITE . DS . 'includes' . DS . 'framework.php' );
require_once ( JPATH_SITE . DS . 'libraries' . DS . 'joomla' . DS . 'factory.php' );
//Import filesystem libraries. Perhaps not necessary, but does not hurt
jimport('joomla.filesystem.path');
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
jimport('joomla.user.user');
//First we set up parameters
$searchpath = JPATH_BASE . DS . "upload";
//Then we create the subfolder called png
if ( !JFolder::create($searchpath . DS ."Images") ) {
//Throw error message and stop script
}
//Now we read all png files and put them in an array.
$png_files = JFolder::files($searchpath,'.png');
//Now we need some stuff from the JFile:: class to move all files into the new folder
foreach ($png_files as $file) {
JFile::move($searchpath. DS . ".png" . $file, $searchpath . DS. "Images" . $file);
}
//Lastly, we are moving the complete subdir to the root of the component.
if (JFolder::move($searchpath . DS. "Images",JPATH_COMPONENT) ) {
//Redirect with perhaps a happy message
} else {
//Throw an error
}
}
?>
Only error i get is Notice: Use of undefined constant JPATH_COMPONENT - assumed 'JPATH_COMPONENT' in /upload.php on line 70. But doesn't stop it working, am so close on this any help is greatly appreciated. I want to know where its taking the image, i think i have worked out the "DS" now.
Thanks

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

Categories