php rename() Access is denied. (code: 5) - php

So I am trying to use rename function in php.
On the first try, if the destination folder is empty or does not contain any directories with the same name as the source folder the rename function works perfectly. However, if there is same directory name it fails. What I want is just to overwrite it and I thought rename() would suffice.
Here is my code:
/**
* Move temp folders to their permanent places
*
* $module_folder = example (violator, pnp, etc)
* $folders = name of folders within module_folder
**/
public function move_temp_to_permanent($module_folder, $folders){
$bool = false;
$module_folder_path = realpath(APPPATH . '../public/resources/temps/' . $module_folder);
$module_folder_destination_path = $_SERVER['DOCUMENT_ROOT'] . '/ssmis/public/resources/photos/' . $module_folder . '/';
foreach($folders as $folder){
$bool = rename($module_folder_path . '/' . $folder, $module_folder_destination_path . $folder);
}
return $bool;
}
The code above gives me an error saying:
Message:
rename(C:\xampp\htdocs\ssmis\public\resources\temps\violator/SJ-VIOL-2015-0002,C:/xampp/htdocs/ssmis/public/resources/photos/violator/SJ-VIOL-2015-0002):
Access is denied. (code: 5)
I am using CodeIgniter as framework.
Thank you very much!

If it is on Windows, this can be read in contributions:
rename() definitely does not follow the *nix rename convention on WinXP with PHP 5. If the $newname exists, it will return FALSE and $oldname and $newname will remain in their original state. You can do something like this instead:
function rename_win($oldfile,$newfile) {
if (!rename($oldfile,$newfile)) {
if (copy ($oldfile,$newfile)) {
unlink($oldfile);
return TRUE;
}
return FALSE;
}
return TRUE;
}
Link.

You are adding extra / in path make this like
/**
* Move temp folders to their permanent places
*
* $module_folder = example (violator, pnp, etc)
* $folders = name of folders within module_folder
**/
public function move_temp_to_permanent($module_folder, $folders){
$bool = false;
$module_folder_path = realpath(APPPATH . '../public/resources/temps/' . $module_folder);
$module_folder_destination_path = $_SERVER['DOCUMENT_ROOT'] . '/ssmis/public/resources/photos/' . $module_folder . '/';
foreach($folders as $folder){
$bool = rename($module_folder_path . $folder, $module_folder_destination_path . $folder);
}
return $bool;
}
you can also echo the path you prepared so you can check its right or not

Related

Locate file in from the file system root knowing sub-folder

I made this code below to find the path of file in my locat system, I would like to change this code to locate my-file and return its absolute path knowing that the only thing we remember about this file is that it is saved in a sub-folder /tmp/documents:
/tmp/documents can contain nested sub-folders and my-file can belong to any one of them.
If my-file cannot be found then your program should return NULL
Example:
locateFile() returns /tmp/documents/a/b/c/my-file if my-file is found into the folder /tmp/documents/a/b/c.
<?php
function locatefile(){
$flags = 0;
$pattern = 'my-file';
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir)
{
$files = array_merge($files, locatefile($dir . '/' .basename($pattern), $flags));
}
return $files;
}
// code test do not change it
$folder = '/tmp/documents/' . rand() . '/' . rand();
mkdir($folder, 0700, true);
touch($folder . '/my-file');
echo "EXAMPLE:$folder/my-file\n";
echo "RESULT:" . locatefile();

Want to take backup of code in PHP where files which are to be taken as backup is read from another specified (patch)folder.?

I need to take backup of code for my Project, but the condition is :-
I generate a Patch folder through SVN, which has files structured in the same way as it is in the main Project folder (the patch has lesser files than the main project). I want to write a code which reads the main project and picks only those files which are present in the patch and saves it in a new backup folder.
The code which i wrote is :-
/*Patch Folder */
$frmFoldr = 'patch_test/';
$basepath = '/var/www/html/TestingBackupCron/';
/*The Folder where files are to be backed up it would use basepath and toFoldr folder name. */
$toFoldr = 'axisdirectcheck/';
/* Read/Copy File from this folder. */
$prodMainFolder = '';
$prodBasePath = '/var/www/html/TestingBackupCron/sijucheckfiles/';
$dir_iterator = new RecursiveDirectoryIterator($basepath . $frmFoldr);
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $file) {
$readDir = strstr($file->getPathname(), $frmFoldr);
$tofileminpath = str_replace($frmFoldr, "", $readDir);
$fromExPath = $prodBasePath . $tofileminpath;
$toExPath = $basepath . $toFoldr . $tofileminpath;
if (strpos($fromExPath, '.php') || strpos($fromExPath, '.js') || strpos($fromExPath, '.css')) {
if (file_exists($fromExPath)) {
copy($fromExPath, $toExPath);
print_r('Files copied to ' . $toExPath . ".\n");
}else{
print_r($fromExPath." ::: Read path not found.\n");
}
}
}
The above code gives me the error "failed to open stream: No such file or directory". I think copy doesn't create folders. Please help guys.
Found a solution. Below code would create folders first and then on the next loop it would write the copied files onto those folders.
public function run($args) {
/*Patch Folder */
$frmFoldr = 'patch_test/';
$basepath = '/var/www/html/TestingBackupCron/';
/*The Folder where files are to be backed up it would use basepath and toFoldr folder name. */
$toFoldr = 'axisdirectcheck/';
/* Read/Copy File from this folder. */
$prodMainFolder = '';
$prodBasePath = '/var/www/html/TestingBackupCron/sijucheckfiles/';
if (file_exists($basepath . $frmFoldr)) {
$dir_iterator = new RecursiveDirectoryIterator($basepath . $frmFoldr);
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
} else{
print_r("Read Directory '$basepath$frmFoldr' not Found. Please check the read directory filename.\n");
exit;
}
$fromDir = array();
$sendToArray = array();
/* this foreach would create folders inside the path ($toFoldr) specified */
foreach ($iterator as $file) {
$readDir = strstr($file->getPathname(), $frmFoldr);
$tofileminpath = str_replace($frmFoldr, "", $readDir);
$fromExPath = $basepath . $readDir;
$toExPath = $basepath . $toFoldr . $tofileminpath;
$sendToArray[] = $tofileminpath;
if (strpos($file, '/.')) {
if (!file_exists($toExPath)) {
$oldmask = umask(0);
mkdir("$toExPath", 0777, true);
umask($oldmask);
}
}
}
/* this foreach would copy files from PROD/UAT and paste inside the path($toExPath) specified */
foreach ($sendToArray as $fPath) {
$fromExPath = $prodBasePath . $fPath;
$toExPath = $basepath . $toFoldr . $fPath;
if (strpos($fromExPath, '.php') || strpos($fromExPath, '.js') || strpos($fromExPath, '.css')) {
if (file_exists($fromExPath)) {
copy($fromExPath, $toExPath);
print_r('Files copied to ' . $toExPath . ".\n");
}else{
print_r($fromExPath." ::: Read path not found.\n");
}
}
}
}
Thanks..

Losing variable value when trying to copy file using mailReader.php

I'm using the mailReader script found here: https://github.com/stuporglue/mailreader
I am trying to copy the file(s) after upload to another folder.
The file(s) upload correctly to the folder where the script resides.
When I try to run a copy command, the filename variable is empty.
Here is the portion of the code I am working with: The last three lines are what I added.
private function saveFile($filename,$contents,$mimeType = 'unknown'){
$filename = preg_replace('/[^a-zA-Z0-9_-]/','_',$filename);
$unlocked_and_unique = FALSE;
while(!$unlocked_and_unique){
// Find unique
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4); // added 1-19-2016
while(file_exists($this->save_directory . $name)) {
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4);
}
// Attempt to lock
$outfile = fopen($this->save_directory.$name,'w');
if(flock($outfile,LOCK_EX)){
$unlocked_and_unique = TRUE;
}else{
flock($outfile,LOCK_UN);
fclose($outfile);
}
}
fwrite($outfile,$contents);
fclose($outfile);
if (copy($this->save_directory.$name, "/attachments/" . TRANS_ID . "/". $name)) {
unlink( $this->save_directory.$name );
}
I receive confirmation by email that the file(s) are uploaded, then another email with the error message.
Warning: copy(/attachments/W7652222-546/1453406138_residential-print_from_td.pdf): failed to open stream: No such file or directory in /home/myhost/public_html/mailreader/mailReader.php on line 224
224 being the line number of my added code.
The source filename is missing from in front of /attachments...
Anyone have any thoughts?
$name is defined in the while loop and may not be accessible on the upper scopes my suggestion is to change your code to this:
private function saveFile($filename,$contents,$mimeType = 'unknown'){
$filename = preg_replace('/[^a-zA-Z0-9_-]/','_',$filename);
$unlocked_and_unique = FALSE;
$name = '';
while(!$unlocked_and_unique){
// Find unique
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4); // added 1-19-2016
while(file_exists($this->save_directory . $name)) {
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4);
}
// Attempt to lock
$outfile = fopen($this->save_directory.$name,'w');
if(flock($outfile,LOCK_EX)){
$unlocked_and_unique = TRUE;
}else{
flock($outfile,LOCK_UN);
fclose($outfile);
}
}
fwrite($outfile,$contents);
fclose($outfile);
if (copy($this->save_directory.$name, "/attachments/" . TRANS_ID . "/". $name)) {
unlink( $this->save_directory.$name );
}
I hope this solves your problem
I ended up defining a constant of email_id in the private function saveToDb, then running a script after everything else is finished to query the table using the email_id and looping through the records moving the files.

Flysystem local asset from outside public folder in Laravel 4

I have the following method that will get an asset depending on which CDN is used:
public function getAsset($filename, $dir = null, $prefix = null)
{
$extension = File::extension($filename);
$name = File::name($filename);
$filename = $dir . $prefix . $name . '.' . $extension;
if(Flysystem::getDefaultConnection() == 'awss3') return Flysystem::getAdapter()->getClient()->getObjectUrl('xxxx', $filename);
if(Flysystem::getDefaultConnection() == 'local') return Flysystem::getAdapter()->getClient()->getObjectUrl($filename);
}
When 'local' storage is selected (in a config) I want to be able to get the asset from the app/storage/temp/media/ directory and display them to the as an image in a tag, how can I modify the above to work like that?
How do I even get an asset from outside the public directory anyway?

Create Folder and Insert if Not Present

I wonder whether someone may be able to help me please.
I'm using Aurigma's Image uploader software to allow users to upload images for locations they visit. The information is saved via the script shown below:
<?php
//This variable specifies relative path to the folder, where the gallery with uploaded files is located.
//Do not forget about the slash in the end of the folder name.
$galleryPath = 'UploadedFiles/';
require_once 'Includes/gallery_helper.php';
require_once 'ImageUploaderPHP/UploadHandler.class.php';
/**
* FileUploaded callback function
* #param $uploadedFile UploadedFile
*/
function onFileUploaded($uploadedFile) {
$packageFields = $uploadedFile->getPackage()->getPackageFields();
$username=$packageFields["username"];
$locationid=$packageFields["locationid"];
global $galleryPath;
$absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR;
$absThumbnailsPath = $absGalleryPath . 'Thumbnails' . DIRECTORY_SEPARATOR;
if ($uploadedFile->getPackage()->getPackageIndex() == 0 && $uploadedFile->getIndex() == 0) {
initGallery($absGalleryPath, $absThumbnailsPath, FALSE);
}
$locationfolder = $_POST['locationid'];
$locationfolder = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $locationfolder);
if (!is_dir($absGalleryPath . $locationfolder)) {
mkdir($absGalleryPath . $locationfolder, 0777);
}
$dirName = $_POST['folder'];
$dirName = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $dirName);
if (!is_dir($absGalleryPath . $dirName)) {
mkdir($absGalleryPath . $dirName, 0777);
}
$path = rtrim($dirName, '/\\') . '/';
$originalFileName = $uploadedFile->getSourceName();
$files = $uploadedFile->getConvertedFiles();
// save converter 1
$sourceFileName = getSafeFileName($absGalleryPath, $originalFileName);
$sourceFile = $files[0];
/* #var $sourceFile ConvertedFile */
if ($sourceFile) {
$sourceFile->moveTo($absGalleryPath . $sourceFileName);
}
// save converter 2
$thumbnailFileName = getSafeFileName($absThumbnailsPath, $originalFileName);
$thumbnailFile = $files[1];
/* #var $thumbnailFile ConvertedFile */
if ($thumbnailFile) {
$thumbnailFile->moveTo($absThumbnailsPath . $thumbnailFileName);
}
//Load XML file which will keep information about files (image dimensions, description, etc).
//XML is used solely for brevity. In real-life application most likely you will use database instead.
$descriptions = new DOMDocument('1.0', 'utf-8');
$descriptions->load($absGalleryPath . 'files.xml');
//Save file info.
$xmlFile = $descriptions->createElement('file');
$xmlFile->setAttribute('name', $_POST['folder'] . '/' . $originalFileName);
$xmlFile->setAttribute('source', $sourceFileName);
$xmlFile->setAttribute('size', $uploadedFile->getSourceSize());
$xmlFile->setAttribute('originalname', $originalFileName);
$xmlFile->setAttribute('thumbnail', $thumbnailFileName);
$xmlFile->setAttribute('description', $uploadedFile->getDescription());
//Add additional fields
$xmlFile->setAttribute('username', $username);
$xmlFile->setAttribute('locationid', $locationid);
$xmlFile->setAttribute('folder', $dirName);
$descriptions->documentElement->appendChild($xmlFile);
$descriptions->save($absGalleryPath . 'files.xml');
}
$uh = new UploadHandler();
$uh->setFileUploadedCallback('onFileUploaded');
$uh->processRequest();
?>
In additon to the original script I've added code that creates a folder, with it's name based on the current 'locationid'. This is shown below.
$locationfolder = $_POST['locationid'];
$locationfolder = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $locationfolder);
if (!is_dir($absGalleryPath . $locationfolder)) {
mkdir($absGalleryPath . $locationfolder, 0777);
}
What I like to incorporate, is a check that looks to see whether there is a folder already setup with the current 'locationid' value, if not create the folder. I'm ceratianly no expert in PHP, but I know that to check to see whether a file exists, the if(file exists....) can be used, but I just wondered whether someone could tell me please how I can implement this check for the folder name?
Many thanks
Chris
I think is_dir() is what you are looking for.
UPDATE:
The code you have:
if (!is_dir($absGalleryPath . $locationfolder)) {
mkdir($absGalleryPath . $locationfolder, 0777);
}
Does exactly what you want. It checks for the folder and if it does not exist then it creates one for you (with CHMOD 777). Don't see what your question is then...

Categories