PHP define the destination folder for an upload - php

I use the following PHP script to upload an image to my server. Actually it moves the file in the same folder where my script is (root). I would like to move it into the folder root/imageUploads. Thank you for your hints!
$source = $_FILES["file-upload"]["tmp_name"];
$destination = $_FILES["file-upload"]["name"];
...
if ($error == "") {
if (!move_uploaded_file($source, $destination)) {
$error = "Error moving $source to $destination";
}
}

You will need to check if the destination folder exists.
$destination = $_SERVER['DOCUMENT_ROOT'] . '/imageUploads/'
if (! file_exists($destination)) { // if not exists
mkdir($destination, 0777, true); // create folder with read/write permission.
}
And then try to move the file
$filename = $_FILES["file-upload"]["name"];
move_uploaded_file($source, $destination . $filename);

So now your destination looks like this:
some-file.ext
and it's dir is same as file that executes it.
You need to append some dir path to current destination. E.g.:
$path = __DIR__ . '/../images/'; // Relative to current dir
$path = '/some/path/in/server/images'; // Absolute path. Start with / to mark as beginning from root dir
And then move_uploaded_file($source, $path . $destination)

Full path to the destination folder should be provided to avoid and path issue for moving uploaded files, I have added three variations for destination paths below
$uploadDirectory = "uploads";
// Gives the full directory path of current php file
$currentPath = dirname(__FILE__);
$source = $_FILES["file-upload"]["tmp_name"];
// If uploads directory exist in current folder
// DIRECTORY_SEPARATOR gices the directory seperation "/" for linux and "\" for windows
$destination = $currentPath.DIRECTORY_SEPARATOR.$uploadDirectory.DIRECTORY_SEPARATOR.$_FILES["file-upload"]["name"];
if (!move_uploaded_file($source, $destination)) {
echo $error = "Error moving $source to $destination";
}
// If to current folder where php script exist
$destination = $currentPath.DIRECTORY_SEPARATOR.$_FILES["file-upload"]["name"];
if (!move_uploaded_file($source, $destination)) {
echo $error = "Error moving $source to $destination";
}
// If uploads directory exist outside current folder
$destination = $currentPath.DIRECTORY_SEPARATOR."..".DIRECTORY_SEPARATOR.$uploadDirectory.DIRECTORY_SEPARATOR.$_FILES["file-upload"]["name"];
if (!move_uploaded_file($source, $destination)) {
echo $error = "Error moving $source to $destination";
}

Related

php- Output directory does not exist

I am trying to save new file to my initial directory in my Symfony project but whatever I tried it throws:
Output directory does not exist
As I am sure that path exist a want to create a .txt file in it!
$path = "/var/www/app/web/uploads/my-file.txt";
$file = basename($path);
$txt = new File();
$txt->setSavePath($file);
$txt->save();
and:
public function setSavePath($savePath)
{
if (!is_dir($savePath)) {
throw \Exception("Output directory does not exist");
}
// Add trailing directory separator the save path
if (substr($savePath, -1) != DIRECTORY_SEPARATOR) {
$savePath .= DIRECTORY_SEPARATOR;
}
$this->savePath = $savePath;
}
Use dirname instead basename.
Because
$path = "/var/www/app/web/uploads/my-file.txt";
$file = basename($path);
// $file is `my-file.txt` and not the path `/var/www/app/web/uploads` you expect
You are checking if the $savePath is a directory is_dir, you are passing a file path, because of that your exception is thrown.
You should check is $savePath is a directory and its writable.
public function setSavePath($savePath)
{
if (!is_writable(dirname($savePath))) {
throw \Exception("Output directory does not exist or not writable.");
}
//... rest of code.
}
ref: http://php.net/is_dir
ref: http://php.net/is_writable

How to store uploaded files in a directory of the main domain from a subdomain upload form

please how can store uploaded file in my main domain directory should it be like this:
move_uploaded_file(https://example.com/uploads)
First step is to start here with handling uploaded files:
http://php.net/manual/en/function.move-uploaded-file.php
The first example is almost exactly what you want:
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>
You will need to make two edits. The $uploads_dir will need to have a relative path to where the files are uploaded. Let's say your form is in the root of your subdomain in subdomain.example.com/ and you want to move them to public_html/uploads. Your new $uploads_dir should look like the following:
$uploads_dir = __DIR__ . '/../public_html/uploads';
__DIR__ will give you the current director your php file is running in. This allows you to create a relative path to other directories.
The second edit is to update the $_FILES array to loop through the proper structure of what you are uploading. It might not be pictures as in the example.
This would be a quick and dirty way to do it( assuming you're in the root directory of your subdomain and your main domain is its own folder( if your main directory does not have its own folder remove the 2nd chdir)
Im assuming youre uploading an image. if not make the changes as necessary
chdir(dirname("../"));// this takes you up one level
chdir("main_directory");// use this only if main directory is inside a folder
$filepath = getcwd() . DIRECTORY_SEPARATOR . 'images' .DIRECTORY_SEPARATOR;
if (!file_exists($filepath)) {
mkdir($filepath, 0755);// this is only to create a new images folder if it doesnt exist
}
chdir($filepath);
$filename = 'file_name_you_want';
$info = pathinfo($_FILES['img']['name']);
$ext = $info['extension'];
$newname = $filename . "." . $ext;
$types = array('image/jpeg', 'image/jpg', 'image/png');
if (in_array($_FILES['img']['type'], $types)) {
if (move_uploaded_file($_FILES["img"]["tmp_name"], $newname)) {
$img_path = 'images' . DIRECTORY_SEPARATOR . $newname;
} else {
// do what needs to be done
}
If youre using php 7 you might want to take a look at string
dirname ( string $path [, int $levels = 1 ] );// the 2nd param would be how many levels up you want to go and $path can be your current directory using __DIR__

PHP file not uploading to localhost

I've set up an XAMPP server and trying to upload image files using a custom admin page. The page works fine when I set it up on a online server running ubuntu.
But when trying the same script in localhost gives me the following error.
Warning : move_upload_file(../img/products/fw000001.jpg) : failed to open stream. No such file or directory in C:\xampp\htdocs\OBS\store\kish\bin\functions.php on line 64
Here is the file upload part of functions.php
function upload_image($image,$code)
{
define("UPLOAD_DIR", "../img/products/");
if (!empty($image)) {
$myFile = $image;
if ($myFile["error"] !== UPLOAD_ERR_OK) {
return null;
}
//check if the file is an image
$fileType = exif_imagetype($_FILES["image"]["tmp_name"]);
$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
if (!in_array($fileType, $allowed)) {
exit();
}
// ensure a safe filename
$name = $myFile["name"];
$parts = pathinfo($name);
$extension = $parts["extension"];
$savename = $code . "." . $extension;
// don't overwrite an existing file
$i = 0;
if(file_exists(UPLOAD_DIR . $savename)) {
unlink(UPLOAD_DIR . $savename);
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $savename);
if (!$success) {
exit();
}
else
{
return $savename;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
}
I'm not pretty sure about directory separator. Directory separator is represent with (/) on Linux based OS. Widows is using ( \ ) for directory separator. So, please change this line and tested it.
define("UPLOAD_DIR", "../img/products/");
to
define("UPLOAD_DIR", "..".DIRECTORY_SEPARATOR."img".DIRECTORY_SEPARATOR."products".DIRECTORY_SEPARATOR.");
Change this line
// preserve file from temporary directory
$success = move_uploaded_file($_FILES["image"]["tmp_name"],UPLOAD_DIR . $savename);

PHP rename folder in directory

How can i get $filename to be one specific path? Not a specific folder?
I want to rename several folders in folder named output.
I tried this:
$fileName = '/path/folder/output';
Here is my original code:
<?php
$fileName = '351437-367628';
$newNametemp = explode("-",$fileName);
if(is_array($newNametemp)){
$newName = $newNametemp[0];
print_r($newName); // lar navnet stå att etter første bindestrek
rename($fileName, $newName);
}
?>
$file_path = "uploads/";
$input = $_POST['name_of _the_folder_You WIsh']; // this is the new folder you'll create
$file_path .= $input . '/';
if (!file_exists($file_path)) {
mkdir($file_path);
}
chmod($file_path, 0777);
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
Here is a sample script that does (I think) what you're looking for. It loops through a directory, renaming all subdirectories.
Save code to demo.php, and chmod +x demo.php && ./demo.php.
If you'd prefer an object-oriented approach, or need any changes let me know and I'll modify the code.
#!/usr/bin/php
<?php
//root directory
$outputDir = '/path/folder/output';
//get all subdirectories in the root directory
$dirs = scandir($outputDir);
if ($dirs === FALSE) {
echo "scandir() failed.\n";
exit(1);
}
//loop through each subdirectory and rename.
foreach($dirs as $dir) {
$newName = "${dir}.tmp"; //rename as needed; here we append ".tmp" to the subdirectory.
$success = rename($dir, $newName);
if (!$success)
echo "Rename of $dir failed.\n"; //there was an error during rename, handle it.
}

file rename while uploading

I have a problem here im trying to upload a file
first time it is moving the filename from temp it its respective directory,
but again i try ot upload the aa different file with the same name it should rename the
first time uploaded file
with date_somefilename.csv and give the filename to its original state
for example a file test.csv ,im uploading it for first time it will upload to
corresponding directory as
test.csv,when i upload a different csv file with same name test.csv
I need to get the
test.csv (latest uploaded file)
06222012130209_test.csv(First time uploaded file)
The code is below
$place_file = "$path/$upload_to/$file_name";
if (!file_exists('uploads/'.$upload_to.'/'.$file_name))
{
move_uploaded_file($tmp, $place_file);
}else{
move_uploaded_file($tmp, $place_file);
$arr1 = explode('.csv',$file_name);
$todays_date = date("mdYHis");
$new_filename = $todays_date.'_'.$arr1[0].'.csv';
echo $str_cmd = "mv " . 'uploads/'.$upload_to.'/'.$file_name . " uploads/$upload_to/$new_filename";
system($str_cmd, $retval);
}
See comments in code.
$place_file = "$path/$upload_to/$file_name";
if (!file_exists($place_file)) {
move_uploaded_file($tmp, $place_file);
} else {
// first rename
$pathinfo = pathinfo($place_file);
$todays_date = date("mdYHis");
$new_filename = $pathinfo['dirname'].DIRECTORY_SEPARATOR.$todays_date.'_'.$pathinfo['basename'];
rename($place_file, $new_filename)
// and then move, not vice versa
move_uploaded_file($tmp, $place_file);
}
DIRECTORY_SEPARATOR is php constant. Value is '/' or '\', depending of operation system.
pathinfo() is php function, that return information about path: dirname, basename, extension, filename.
What about...
$place_file = "$path/$upload_to/$file_name";
if (file_exists($place_file)) {
$place_file = date("mdYHis")."_".$file_name;
}
if (!move_uploaded_file($tmp, $place_file)) {
echo "Could not move file";
exit;
}
I would not add a date to the file if it already exists. Instead I would just add a number to the end of it. Keep it simple.
$counter = 0;
do {
// destination path path
$destination = $path.'/'.$upload_to.'/';
// get extension
$file_ext = end(explode('.', $file_name));
// add file_name without extension
if (strlen($file_ext))
$destination .= substr($file_name, 0, strlen($file_name)-strlen($file_ext)-1);
// add counter
if ($counter)
$destination .= '_'.$counter;
// add extension
if (strlen($file_ext))
$destination .= $file_ext;
$counter++;
while (file_exists($destination));
// move file
move_uploaded_file($tmp, $destination);
$target = "uploads/$upload_to/$file_name";
if (file_exists($target)) {
$pathinfo = pathinfo($target);
$newName = "$pathinfo[dirname]/" . date('mdYHis') . "_$pathinfo[filename].$pathinfo[extension]";
rename($target, $newName);
}
move_uploaded_file($tmp, $target);
Beware though: Security threats with uploads.
how about something like this?
<?php
$tmp = '/tmp/foo'; // whatever you got out of $_FILES
$desitnation = '/tmp/bar.xyz'; // wherever you want that file to be saved
if (file_exists($desitnation)) {
$file = basename($destination)
$dot = strrpos($file, '.');
// rename existing file to contain its creation time
// "/temp/bar.xyz" -> "/temp/bar.2012-12-12-12-12-12.xyz"
$_destination = dirname($destination) . '/'
. substr($file, 0, $dot + 1)
. date('Y-m-d-H-i-s', filectime($destination))
. substr($file, $dot);
rename($destination, $_destination);
}
move_uploaded_file($tmp, $destination);

Categories