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.
}
Related
I'm trying to copy one file from a directory to another upon execution of an sql query but it doesn't work.
if($result){
$path = "forms/uploads/";
$file = $path.$request_name."docx";
if(file_exists($file)){
move_uploaded_file($file, "forms/requests/") ;
}
echo 400;
The $path is the directory where the file currently exists.
You can try use copy function and unlink old file
https://www.php.net/manual/en/function.copy.php
if($result){
$path = "forms/uploads/";
$file = $path.$request_name."docx";
$newfile = $path.$request_name."docx";
if(file_exists($file)){
if (!copy($file, "forms/requests/".$newfile)) {
echo "failed to copy $file...\n";
}
unlink($file);
}
echo 400;
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";
}
$targetFolder = '/LP/media/image'; // Relative to the root
if (!empty($_FILES)) {
$tmpName = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
//$ext = end(explode('.', $_FILES['Filedata']['name']));
$targetFile = rtrim($targetPath, '/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
echo $targetFile;
$fileParts = pathinfo($_FILES['Filedata']['name']);
$fileTypes = array('jpg', 'jpeg', 'png','JPG','JPEG','PNG'); // File extensions
if (in_array($fileParts['extension'], $fileTypes)) {
move_uploaded_file($tmpName, $targetFile);
//echo '1'.$fileParts['filename'];
// echo $fileParts['filename'];
$aimage = file_get_contents($tmpName);
// echo '<img src="data:image/jpeg;base64,' . base64_encode($aimage) . '" width=\'100\' height=\'100\' />';
} else {
echo 'Invalid file type.';
}
}
?>
Same code is working on my local machine, but deployed on remote server. Then getting below error.
/home/username/public_html/LP/media/image/default_avatar.png
Warning: move_uploaded_file(/home/username/public_html/LP/media/image/default_avatar.png): failed to open stream: No such file or directory in /home/username/public_html/uploadify/gallery.php on line 28
Warning: move_uploaded_file(): Unable to move '/tmp/phpoe0fBd' to '/home/username/public_html/LP/media/image/default_avatar.png' in /home/username/public_html/uploadify/gallery.php on line 28
The code you provide isn't very clear to tell the source of the problem, so I will provide you with a full snippet where you can take better conclusions.
In this case, I sent an array from JavaScript to my PHP file using a formdata under the name "documents". I also modify the name of the file so it becomes: "filename_optional_$i(int)".
for($i=0; $i<count($_FILES['documents']['name']); $i++){
list($dump, $extention) = explode(".", (string)$_FILES['documents']['name'][$i]);
$document_name = $file_name.'_optionnel'.$i;
if(($_FILES['documents']['size'][$i] < 500000)){
if ($_FILES['documents']["error"][$i] > 0){
echo 'Erreur.';
}else{
if(file_exists( $directory_path . $document_name . "." . $extention)) {
echo 'Le fichier existe déjà.';
}else{
$sourcePath = $_FILES['documents']['tmp_name'][$i];
$targetPath = $directory_path . $file_name ."/". $document_name . "." . $extention;
array_push($attachments, $targetPath);
move_uploaded_file($sourcePath, $targetPath);
}
}
}else{
echo 'Le fichier est trop grand.';
}
}
Make sure your path variables are pointing to the correct folder. Say, for instance, if you want your file to go to the foldier images, you have to do:
path_to_folder/images/ and not path_to_folder/images
EDIT:
Here's how your filename and directory path variables should look like:
/*$nom, $prenom and $user_id come from database values*/
$file_name = $nom."_".$prenom."_".$user_id;
$directory_path = dirname( __FILE__ ) . '/user_docs/';
/* Create mask */
$oldmask = umask(0);
/* Create the folder for user */
$directory = mkdir($directory_path.$file_name, 0777);
/* redo the mask */
umask($oldmask);
I'm quite new to this site, but the least I can do for you is offer you this code I've done to help you out. I've written some comments to guide you through.
Full code source for upload
I have this little function (not the best) but it "works" in my case the uploaded files must be moved or they get deleted, so I move them to a folder next to my PHP file and echo a link to it (you can them move it any where else, rename it or whatever:
function save_file() {
$gs_name = $_FILES['uploaded_files']['tmp_name'];
if(is_readable($gs_name) && $_FILES['uploaded_files']['error'] == 0) { //Tells whether a file exists and is readable. no error during upload (0)
move_uploaded_file($gs_name, 'upload/'.$_FILES['uploaded_files']['name']);
echo "saved.<a href='upload/".$_FILES['uploaded_files']['name']."' target='_blank'/>".$_FILES['uploaded_files']['name']."</a><br/>";
echo "<p><a href='upload/' target='_self'>Uploaded files.</a></p>";
echo "<p><a href='upload_file.php' target='_self'>Continue...</a></p>";
}
}
The important part about it is this if:
if(is_readable($gs_name) && $_FILES['uploaded_files']['error'] == 0)
it allow it to check if the file can be copied and if there were no errors that could leave the file damage... I point at this because the path seems to be ok, other already mention the file and folder permissions.
Try the following code. It should be easy to identify the error:
<?php
$upload_dir = $_SERVER['DOCUMENT_ROOT'] . '/LP/media/image';
if (isset($_FILES['Filedata'])) {
$file = $_FILES['Filedata'];
if ($file['error'] !== UPLOAD_ERR_OK) {
echo 'error: ', $file['error'], PHP_EOL;
exit;
}
$allowed = array('jpg', 'jpeg', 'png');
$extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($extension, $allowed)) {
echo 'error: invalid file extension', PHP_EOL;
exit;
}
$target = $upload_dir . '/' . basename($file['name']);
if (!move_uploaded_file($file['tmp_name'], $target)) {
echo 'error: move_uploaded_file failed', PHP_EOL;
print_r(error_get_last());
exit;
}
echo 'success', PHP_EOL;
echo $target, PHP_EOL;
}
whom still have this problem after tried all solutions suggested here.. they have to try this small thing is to respect the letter sensitive case of the name of folders.. folder "Upload" <> "upload".. thx
I have this code which reads files from directory:
//directory to read
$dir = ($_REQUEST['dir']);
if(file_exists($dir)==false){
echo 'Directory \'', $dir, '\' not found!';
}else if( !is_readable($dir) ) {
echo 'Directory \'', $dir, '\' is not readable! Check your permissions.';
}else{
$di = new RecursiveDirectoryIterator($dir);
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
$file_type = explode(".", $filename);
$extension = strtolower(array_pop($file_type));
if(in_array($extension, $allowed_files) == true){
$mediaArr[] = $filename;
}
}
echo json_encode($mediaArr);
}
If I enter path as this:
http://www.mydomain.com/some_folder/
I get an error "Directory http://www.mydomain.com/some_folder/ not found"
Why is this?
The PHP file system functions work with file system paths. There are different protocol wrappers you can use with the file system functions, but I don't see how they would be of any help here.
Just use the file system paths.
I have a folder 'items' in which there are 3 files item1.txt, item2.txt and item3.txt.
I want to delete item2.txt file from folder. I am using the below code but it not deleting a file from folder. Can any body help me in that.
<?php
$data="item2.txt";
$dir = "items";
$dirHandle = opendir($dir);
while ($file = readdir($dirHandle)) {
if($file==$data) {
unlink($file);
}
}
closedir($dirHandle);
?>
Initially the folder should have 777 permissions
$data = "item2.txt";
$dir = "items";
while ($file = readdir($dirHandle)) {
if ($file==$data) {
unlink($dir.'/'.$file);
}
}
or try
$path = $_SERVER['DOCUMENT_ROOT'].'items/item2.txt';
unlink($path);
No need of while loop here for just deleting a file, you have to pass path of that file to unlink() function, as shown below.
$file_to_delete = 'items/item2.txt';
unlink($file_to_delete);
Please read details of unlink() function
http://php.net/manual/en/function.unlink.php
There is one bug in your code, you haven't given the correct path
<?php
$data="item2.txt";
$dir = "items";
$dirHandle = opendir($dir);
while ($file = readdir($dirHandle)) {
if($file==$data) {
unlink($dir."/".$file);//give correct path,
}
}
closedir($dirHandle);
?>
unlink
if($file==$data) {
unlink( $dir .'/'. $file);
}
It's very simple:
$file='a.txt';
if(unlink($file))
{
echo "file named $file has been deleted successfully";
}
else
{
echo "file is not deleted";
}
//if file is in other folder then do as follows
unlink("foldername/".$file);
try renaming it to the trash or a temp folder that the server have access **UNLESS IT'S sensitive data.
rename($old, $new) or die("Unable to rename $old to $new.");