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.";
}
Related
This is the dilemma. I have a script that works perfectly for writing small video files into S3 bucket and local docker.
I need to update the script so it can handle larger files. In order to do that I am using the exec() method in which I run a php script to upload the file so it runs it in the background. This is the code I'm using:
$tempFile = $_FILES['form-file-input']['tmp_name'][$i];
$directory = $config['content_directory'];
echo (is_file($tempFile) ? 'Tempfile is a file' : 'Tempfile is not a file');
echo (is_readable($tempFile) ? ' and tempfile is readable.' : ' and tempfile is not readable.');
echo '<br>'.'This is the file name: '.$newFileName.'<br>';//already defined
chdir('/var/www/webApp/_apps/training_videos/');//required to find i-did-it.php - tested and doesn't affect saving functionality
exec("php i-did-it.php $tempFile $directory $newFileName 2>&1", $out);
var_dump($out);
//$resultado = move_uploaded_file($tempFile, $directory . '/_' . 'videos' . '/' . $newFileName);
//var_dump($resultado);
exit;
BELOW ARE THE CONTENTS OF i-did-it.php
Note that the code reviews before and after executing if the the param is a readable file and that the other params have a valid value. Also note that I set all errors, set a log file and try to catch the last error.
//Set all errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ini_set('log_errors',1);
ini_set('error_log','/var/www/siteContent/logs/log.txt');//verified that log file can be written to
//Get the params
$tempFile = $argv[1];
$directory = $argv[2];
$newFileName = $argv[3];
//Verify that it arrives as a readable file
echo (is_file($tempFile) ? 'Tempfile is a file' : 'Tempfile is not a file');
echo (is_readable($tempFile) ? ' and tempfile is readable.' : ' and tempfile is not readable.');
//Display the params
echo ' Temp file name: '.$tempFile;
echo ', the directory: '.$directory;
echo ' and new file name: '.$newFileName.' *** ';
//Move the file and dump results
$putResult = move_uploaded_file($tempFile, $directory . '/_' . 'videos' . '/' . $newFileName);//original
var_dump($putResult);
print_r(error_get_last());
So what is the problem?
move_uploaded_file commmand is not working when called via exec().
Note that if I replace this line
exec("php i-did-it.php $tempFile $directory $newFileName 2>&1", $out);
with this one
$resultado = move_uploaded_file($tempFile, $directory . '/_' . 'videos' . '/' . $newFileName);
it works!
Note that it is commented in the first snippet.
Those are the results I get
In order to troubleshoot I need to know why the move_uploaded_file command is not working since it only throws true or false. It's known it is false since it doesn't work. I would like to get more errors than that. The method recommended for the task I cannot use since my file is not set like this: $_FILES['file'] but as a variable (It has to be done that way since I'm passing it as a param) so I cannot check errors towards: $_FILES['file']['error']
Reference for the error obtaining approach
https://www.php.net/manual/en/features.file-upload.errors.php
Following the previous example I tried applying it to the var that holds the file to no avail:
if ($tempFile === UPLOAD_ERR_OK) {
//uploading successfully done
} else {
throw new UploadException($tempFile);
}
What do I need to continue?
At this point it would be helpful to know these 2 things:
How can I get the error/warning from move_uploaded_file that is coming back as false?
Any ideas why move_file_upload will work perfectly fine when called directly but fails when called via exec("php myfile.php $param1 $param2 $param3 2>&1", $output)
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.
I'm trying to use PHP unlink() function to delete away the specific document in the folder. That particular folder has already been assigned to full rights to the IIS user.
Code:
$Path = './doc/stuffs/sample.docx';
if (unlink($Path)) {
echo "success";
} else {
echo "fail";
}
It keep return fail. The sample.docx does reside on that particular path. Kindly advise.
I found this information in the comments of the function unlink()
Under Windows System and Apache, denied access to file is an usual
error to unlink file. To delete file you must to change the file's owner.
An example:
chown($tempDirectory . '/' . $fileName, 666); //Insert an Invalid UserId to set to Nobody Owern; 666 is my standard for "Nobody"
unlink($tempDirectory . '/' . $fileName);
So try something like this:
$path = './doc/stuffs/sample.docx';
chown($path, 666);
if (unlink($path)) {
echo 'success';
} else {
echo 'fail';
}
EDIT 1
Try to use this in the path:
$path = '.'
. DIRECTORY_SEPARATOR . 'doc'
. DIRECTORY_SEPARATOR . 'stuffs'
. DIRECTORY_SEPARATOR . 'sample.docx';
Try this:
$Path = './doc/stuffs/sample.docx';
if (file_exists($Path)){
if (unlink($Path)) {
echo "success";
} else {
echo "fail";
}
} else {
echo "file does not exist";
}
If you get file does not exist, you have the wrong path. If not, it may be a permissions issue.
This should work once you are done with the permission issue. Also try
ini_set('display_errors', 'On');
That will tell you whats wrong
define("BASE_URL", DIRECTORY_SEPARATOR . "book" . DIRECTORY_SEPARATOR);
define("ROOT_PATH", $_SERVER['DOCUMENT_ROOT'] . BASE_URL);
$path = "doc/stuffs/sample.docx";
if (unlink(ROOT_PATH . $Path)) {
echo "success";
} else {
echo "fail";
}
// http://localhost/book/doc/stuffs/sample.docx
// C:/xampp/htdocs\book\doc/stuffs/sample.docx
You need the full file path to the file of interest. For example: C:\doc\stuff\sample.docx. Try using __DIR__ or __FILE__ to get your relative file position so you can navigate to the file of interest.
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 have an absolute path of (verified working)
$target_path = "F:/xampplite/htdocs/host_name/p/$email.$ext";
for use in
move_uploaded_file($_FILES['ufile']['tmp_name'], $target_path
However when I move to a production server I need a relative path:
If /archemarks is at the root directory of your server, then this is the correct path. However, it is often better to do something like this:
$new_path = dirname(__FILE__) . "/../images/" . $new_image_name;
This takes the directory in which the current file is running, and saves the image into a directory called images that is at the same level as it.
In the above case, the currently running file might be:
/var/www/archemarks/include/upload.php
The image directory is:
/var/www/archemarks/images
For example, if /images was two directory levels higher than the current file is running in, use
$new_path = dirname(__FILE__) . "/../../images/" . $new_image_name;
$target_path = __DIR__ . "/archemarks/p/$email.$ext";
$target_path = "archemarks/p/$email.$ext";
notice the first "/"
/ => absolute, like /home
no "/" => relative to current folder
That is an absolute path. Relative paths do not begin with a /.
If this is the correct path for you on the production server, then PHP may be running in a chroot. This is a server configuration issue.
Assuming the /archemarks directory is directly below document root - and your example suggests that it is -, you could make the code independent of a specific OS or environment. Try using
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/archemarks/p/$email.$ext";
as a generic path to your target location. Should work fine. This notation is also independent of the location of your script, or the current working directory.
Below is code for a php file uploader I wrote with a relative path.
Hope it helps. In this case, the upload folder is in the same dir as my php file. you can go up a few levels and into a different dir using ../
<?php
if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get"))
#date_default_timezone_set('America/Anchorage');
ob_start();
session_start();
// Where the file is going to be placed
$target_path = "uploads/" . date("Y/m/d") . "/" . session_id() . "/";
if(!file_exists( $target_path )){
if (!mkdir($target_path, 0755, true))
die("FAIL: Failed to create folders for upload.");
}
$maxFileSize = 1048576*3.5; /* in bytes */
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$index = 0;
$successFiles = array();
$failFiles = null;
$forceSend = false;
if($_SESSION["security_code"]!==$_POST["captcha"]){
echo "captcha check failed, go back and try again";
return;
}
foreach($_FILES['attached']['name'] as $k => $name) {
if($name != null && !empty($name)){
if($_FILES['attached']['size'][$index] < $maxFileSize ) {
$tmp_target_path = $target_path . basename( $name );
if(move_uploaded_file($_FILES['attached']['tmp_name'][$index], $tmp_target_path)) {
$successFiles[] = array("file" => $tmp_target_path);
} else{
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "unable to copy the file on the server");
}
} else {
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "file size was greater than 3.5 MB");
}
$index++;
}
}
?>
<?php
$response = "OK";
if($failFiles != null){
$response = "FAIL:" . "File upload failed for <br/>";
foreach($failFiles as $k => $val) {
$response .= "<b>" . $val['file'] . "</b> because " . $val['reason'] . "<br/>";
}
}
?>
<script language="javascript" type="text/javascript">
window.top.window.uploadComplete("<?php echo $response; ?>");
</script>