I asked a similar question previously, but didn't know how to quite ask before. Below I created a new directory based on the username I grabbed from a signup form. I just need the inclusion of the template file copied over to the new directory that was just made. The outcome I'm getting is an inclusion of the file in the directory that's up one level. The new directory is created with the username but doesn't contain the template file in its directory. I spent hours on this so I wouldn't have to bother you guys again. What am I doing wrong?
$folder = DIRECTORY_SEPARATOR; // adds the forward slash
$name = $user->username; // included from a login script I purchased
$thisdir = "../associate"; // desired directory
$folderPath = $thisdir . $folder . $name;
$file = copy('../associate/joshua/career.php', $folderPath.'.php'); // copy this file into new directory
if(!file_exists($folderPath)){
mkdir($folderPath);
chmod($folderPath,0777);
}
file_put_contents(realpath($folderPath) .'/'. $folderPath, $file);
});
If I understand you well, you want to copy career.php template from /associates/ folder to /associates/username/ folder
$rootfolder = $_SERVER['DOCUMENT_ROOT'];
$name = $user->username;
$thisdir = "/associate/";
$folderPath = $rootfolder.$thisdir.$name."/"; // desired directory
if(!is_dir($folderPath)){
mkdir($folderPath, 0777, true);
}
$currentfile = $rootfolder.$thisdir.'joshua/career.php';
$destination = $folderPath.'career.php';
copy($currentfile, $destination); // copy this file into new directory
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.";
}
I am getting following error, when I try to save data into db after file upload:
finfo_file(/tmp/phpqE6gyD): failed to open stream: No such file or directory
This is the code:
$userFolderPath = \Yii::getAlias('#webroot') . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR . \Yii::$app->user->getIdentity()->iduser;
$model = new CsFile();
$files = UploadedFile::getInstances($model, 'files');
$errors = [];
if (!file_exists($userFolderPath))
mkdir($userFolderPath, 0777, true);
foreach($files as $file):
$fileModel = new CsFile();
$fileModel->files = $file;
if($fileModel->validate()):
$filename = str_replace(' ', '_', $file->baseName);
if(file_exists($userFolderPath . DIRECTORY_SEPARATOR . $filename . "." . $file->extension)):
$filename .= "-" .uniqid();
endif;
$fileModel->files
->saveAs($userFolderPath .DIRECTORY_SEPARATOR. $filename . '.' . $fileModel->files->extension);
$fileModel->iduser = Yii::$app->user->getIdentity()->iduser;
$fileModel->name = $filename;
$fileModel->extension = $file->extension;
$fileModel->add_date = date('Y-m-d H:i:s');
$fileModel->save();
else:
endif;
endforeach;
var_dump('<pre>', $errors, '</pre>');
I had the same problem a few weeks ago. Turns out, when we rename the file before upload and try to save the model, this error will appear.
If that attribute it's only for handle your upload and have no field in your table, you can just unset this fields before saving: $files Model->files = null.
Let me know if your scenario is different than mine.
Yii2 use UploadFile class through function $model->upload() to save upload file
To fix this use inside your $model->upload function :
return copy($this->YourAttribute->tempName, $newFileName);
instead
return $model->attribute->saveAs($newFileName)
Clyff is right. But in case you are saving the path of the file in database to read later, setting the attribute to null is not going to work.
The problem is when you try to save the model still with result of UploadedFile::getInstance($model, 'file') in the file field which is already used by $model->file->saveAs();
$model->save() cannot save the path of the saved and already removed temporary files path directly.
So after successful $model->file->saveAs($path) you need to do something like:
$model->file = $path;
It was quite unclear to me and spent a bit of time after fileinfo , so hope the answer helps.
I was having same problem, I solved it with this:
$model->file->saveAs($filepath , false)
then...
$model->save(false)
Important: In the saveAs function pass false parameter.
Using false parameter in $model->save(false) that means you are ignoring model validation, which is not right.
But using false as a second parameter in $file->saveAs($path,false) means you are trying to keep the file in the temp folder after being uploaded and allow the model to access the file during validation when trying to save to the database.
If the model fails to access the file (i.e removed from the temp folder after being uploaded), you will getting an ERROR Fail to open a stream, No such file/folder
<?php
if (isset($_POST['filename']) && isset($_POST['editorpassword']) && isset($_POST['roomname'])) {
$dir = $_POST['filename']; // This must match the "name" of your input
$path = "evo/" . $dir;
if (!file_exists($path)) {
mkdir($path, 0755, true);
}
}
?>
I have this script where I'm trying to create a new folder. The script itself is ran inside of a folder called /evo and by using this code, it creates the folder in there. Where it needs to go is ../../creative however even if I try and use
$path = "./rooms/creative/" . $dir;
or something to that effect it creates it with the base folder as evo so it appears at:
../evo/rooms/creative (creating the folders that don't exist there with it as it should)
I'm just unsure what to write in for the path on where I need it created to find the right location.
Simplest solution is to remove the "evo" in $path = "evo/" . $dir;
I am making a intranet customer manager in PHP. For each customer a directory is created for the shop to add files into. What my script is supposed do is if no directory exists create it, if it does exists dont create it.
What is actually happening is if the directory already exists I am getting the following error :
Warning: mkdir() [function.mkdir]: File exists in C:\server2go\server2go\htdocs\customermgr\administrator\components\com_chronoforms\form_actions\custo m_code\custom_code.php(18) : eval()'d code on line 14
So what is happening it is trying to create it anyway, even though the if statement should stop it ?, im confused on what I am doing wrong :-S .
<?php
$customerID = $_GET['cfid'];
$directory = "/customer-files/$customerID";
if(file_exists($directory) && is_dir($directory)) {
}
else {
$thisdir = getcwd();
mkdir($thisdir ."/customer-files/$customerID" , 0777); }
?>
Replace:
if(file_exists($directory) && is_dir($directory)) {
with:
$thisdir = getcwd();
if(file_exists($thisdir.$directory) && is_dir($thisdir.$directory)) {
or better:
<?php
$customerID = $_GET['cfid'];
$directory = "./customer-files/$customerID";
if(file_exists($directory) && is_dir($directory)) {
}
else {
mkdir($directory , 0777); }
?>
Just took a short look but i would try this:
$directory = $thisdir . "/customer-files/$customerID";
and remove $thisdir from mkdir();
also you should move your $thisdir before the $directory declaration
The function file_exists() does not use relative paths, where is_dir() can. So instead, use the common denominator and pass an absolute path to these functions. Additionally you can move the call to getcwd() into the $directory assignment and reuse $directory later for creating the directory.
<?php
$customerID = $_GET['cfid'];
// Get full path to directory
$directory = getcwd() . "/customer-files/$customerID";
if(file_exists($directory) && is_dir($directory)) {
// Do nothing
}
else {
// Directory doesn't exist, make it
mkdir($directory , 0777); }
}
?>
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...