File upload-how to create destination folder with user name - php

I need to upload file using php and I done it...Now my problem is I want to create a new folder for every user let me explain to you how??
My task is for user can login and access their account and file uploads. If the user will upload any file it goes to my destination folder named as 'uploads'. Now I want to create new folder inside the uploads folder with the particular username who uploads the file... so I want to create new folder for each and every users with their username... Can anyone tell me how to do this???
This is my php code for destination :
if(move_uploaded_file($_FILES['upl']['tmp_name'], '../uploads/'.$_FILES['upl']['name']))
{
echo '{"status":"success"}';
exit;
}
Thanks in advance

What you're looking for is the mkdir function. You can create a directory by using:
mkdir('/path/to/dir', 0700);
as noted in the PHP documentation.

Try with -
//check if the folder not exists then create it
if (!file_exists('<rootpath>/<username>')) { //<rootpath> will be the path from document root and <username> will be the username you want
mkdir('<rootpath>/<username>');
}
if(move_uploaded_file($_FILES['upl']['tmp_name'], '<path>/<username>/'.$_FILES['upl']['name'])) // <path> be the relative path
{
echo '{"status":"success"}';
exit;
}
Suppose You want to upload the file inside uploads/username folder.
$path = $_SERVER['DOCUMENT_ROOT'].'/uploads';
Now create the folder -
mkdir($path."/".$username); //$username be the username you want
Now upload the file
move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/'.$username.'/'.$_FILES['upl']['name'])

Use mkdir() function to create a folder upon user registration.
Upon login create a $_SESSION variable storing the username.
When using move_uploaded_file() function add session variable to path.
move_uploaded_file($_FILES['upl']['tmp_name'], '../uploads/'.$_SESSION['username'].'/'.$_FILES['upl']['name'])
http://php.net/manual/en/function.mkdir.php
http://php.net/manual/en/reserved.variables.session.php

Thanks SGT... I got the answer with this code
$userfolder = $_SESSION['email'];
//echo $userfolder;
$path = $_SERVER['DOCUMENT_ROOT'].'register/uploads';
if (!file_exists('$path')) {
mkdir($path."/".$userfolder);
}
if(move_uploaded_file($_FILES['upl']['tmp_name'], '../uploads/'.$userfolder.'/'.$_FILES['upl']['name'])){
echo '{"status":"success"}';
exit;
}
Thanks Again

Related

Remove "Attachments" folder after PHPMailer email is sent

I've got a web form which has a unique upload folder for each user (using their PHP session_id() as the folder name) which works well. When the form is submitted (after error checking) PHPMailer is used to send the email and the attachments. This is also working well. However, after the email is sent, I would like to remove the uploads from the folder and then the folder itself (sort of a self-cleanup!) The files are removed as expected but the folder remains (albeit empty). I wonder if the folder is somehow "still in use" so doesn't get deleted or something similar? This is the code:
// Empty the contents of the upload folder
if (is_dir($dir)) { // Target directory ($dir) is set above in photos POST section
// Check for any files inside the directory
$files = glob($dir.'/*'); // Get all file names
foreach($files as $file) { // Iterate through the files
if(is_file($file)) { // Check its a file
unlink($file); // Delete the file
}
}
// Remove the upload folder
rmdir($dir); //NOT WORKING? NEEDS SOME TROUBLESHOOTING...
}
Any other ideas on why this folder is remaining?
Ben
I would guess that your folders might contain hidden files (starting with .) which the default glob pattern won't match, so try this:
$files = glob($dir . '/{,.}*'); // Get all file names including hidden ones
foreach($files as $file) { // Iterate through the files
if(is_file($file)) { // Check its a file
unlink($file); // Delete the file
}
}
Also check the return value on both unlink and rmdir so you can see exactly where it's failing.
Turns out after much testing that the problem was not actually with rmdir at all! My web form uses a Dropzone for photo uploads to a unique folder for each user using their php session_id() and this folder is supposed to be created when they add a photo to Dropzone (if it doesn’t already exist). Problem was I’d put the folder creation code outside of the actual upload script so the folder was in fact being deleted but them instantly created again when the form submitted and the page reloads! Sorry about that but thanks for all your help. :)

How to show image from folder using url

i am using php code for creating folder at run time where i am storing some images.
when i try to accecss these image it does not show images asa well as folder name using appropriate URL.
but when i logedin using cpanel it shows folder name.
Here is my code
$dir="1buyerseller";
$desired_dir=$email;
$filename= $dir.'/'.$email.'/'.$file_name;
//echo $filename;
$query="INSERT into buysellsetailads (id,ads,cid) VALUES('seller','$filename','$cid'); ";
if(empty($errors)==true){
if(is_dir($dir.'/'.$desired_dir)==false){
mkdir("$dir/$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$dir/$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$dir/$desired_dir/".$file_name);
}else{ // rename the file if another one exist
$new_dir="$dir/$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
mysql_query($query);
}
Using this code i am creating folder and uploding image into this folder.
whnen i try like this
http://www.xpokerala.com/admin/1square/
Here some folder are showing which created hardcoded but dyanamic created not showing
Why i dondt no.
How can i resolve this issue
Thanks
$query="INSERT into buysellsetailads (id,ads,cid) VALUES('seller','$filename','$cid'); ";
should this be buysellretailads?

Cannot unlink file in Codeigniter

In my project I have a folder secure in root. The project package looks like:
application
secure
system
...........
Inside secure folder I am uploading some images on form submit using
$config1['upload_path'] = './secure/';
$ext = end(explode(".", $_FILES['thumb_image']['name']));
$config1['file_name'] = time().$_FILES['thumb_image']['name'];
$config1['allowed_types'] = 'jpg|png|jpeg|gif|bmp|jpe|tiff|tif';
$this->load->library('upload', $config1);
$this->upload->initialize($config1);
$this->upload->do_upload('thumb_image');
and it is working properly. Now while on editing the details, using another form, if I am uploading a new image instead of the current image file, I want to unlink the current one and then upload new file.
For this I am using the code:
unlink(base_url("secure/".$data['row']->videothumbnail));
I also tried with
unlink('/secure/'.$data['row']->videothumbnail);
where $data['row']->videothumbnail) is the current image file from database. New file is successfully uploaded. But old file is not getting unlinked. I have set the permission of secure folder to 777. But the images are uploaded with read only permission. Is it because of this, it is not getting unlinked?
Can anyone help me to solve this?
Thanks in advance.
Try this:
Set the permission dynamically using:
#chmod('./secure/'.$data['row']->videothumbnail, 0777);
then try unlink:
#unlink('./secure/'.$data['row']->videothumbnail);
Try echoing the path that you are providing to unlink function.
It should be something like this:
base_url()."secure/".$data['row']->videothumbnail;
I also had this issue even after setting the right permission on the folder. But the following code worked for me.
unlink(realpath(APPPATH . '../uploads').'/'.$ImageName);
Try to use $_SERVER['DOCUMENT_ROOT'] instead of base_url
$this->load->helper("file")
unlink(base_url('folder/file.ext'));
location:
\app\controller
\system\libraries
**folder\file.ext**
$unlinkUrl = "secure/".$data['row']->videothumbnail;
if(file_exists($unlinkUrl)){
unlink($unlinkUrl);
}
else{
echo $unlinkUrl." is not available";
}
I think you are just making a stupid mistake.
Firstly, the first param of unlink should be a relative path or absolute path, but base_url function will return you a path contains domain name, HOW CAN YOU DELETE A FILE ON REMOTE SERVER ?
Secondly, '/secure/'.$data['row']->videothumbnail here is not a relative path but a absolute path
YOU MUST change it into /the/absolute/path/to/secure/ or ./the/relative/path/to/secure/ (DO NOT MISS THE DOT)
use this to unlink
$oldthumb = "secure/".$data['row']->videothumbnail;
#unlink($oldthumb);
First Load the $this->load->helper("file") and then unlink it
unlink("secure/".$data['row']->videothumbnail);
if ($rowAffected > 0) {
if ($isMediaUpload)
if (file_exists('./uploads/' . $this->input->post('img_url')))
unlink('./uploads/' . $this->input->post('img_url'));
redirect('/admin/configration', 'location');
}
Though i came in late but someone might need this .
unlink(FCPATH."secure/".$data['row']->videothumbnail)
**FCPATH** - path to front controller, usually index.php
**APPPATH** - path to application folder
**BASEPATH** - path to system folder.

PHP - upload and overwrite a file (or upload and rename it)?

I have searched far and wide on this one, but haven't really found a solution.
Got a client that wants music on their site (yea yea, I know..). The flash player grabs the single file called song.mp3 and plays it.
Well, I am trying to get functionality as to be able to have the client upload their own new song if they ever want to change it.
So basically, the script needs to allow them to upload the file, THEN overwrite the old file with the new one. Basically, making sure the filename of song.mp3 stays intact.
I am thinking I will need to use PHP to
1) upload the file
2) delete the original song.mp3
3) rename the new file upload to song.mp3
Does that seem right? Or is there a simpler way of doing this? Thanks in advance!
EDIT: I impimented UPLOADIFY and am able to use
'onAllComplete' : function(event,data) {
alert(data.filesUploaded + ' files uploaded successfully!');
}
I am just not sure how to point THAT to a PHP file....
'onAllComplete' : function() {
'aphpfile.php'
}
???? lol
a standard form will suffice for the upload just remember to include the mime in the form. then you can use $_FILES[''] to reference the file.
then you can check for the filename provided and see if it exists in the file system using file_exists() check for the file name OR if you don't need to keep the old file, you can use perform the file move and overwrite the old one with the new from the temporary directory
<?PHP
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name.".".$type;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
?>
try this piece of code for upload and replace file
if(file_exists($newfilename)){
unlink($newfilename);
}
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newfilename);

Php File upload, rename file, and then return new filename on 'successful upload' page?

I'm trying to return the name of a file uploaded using PHP after changing image files name upon uploading it.
I thought I could create a $_session['image_name'] and then call that session up on the subsequent "successful upload" page. I can't seem to get it correct. I need the name so that I can store it in the mysql database. Here's the part of my upload code that does the renaming and my attempt at creating a session:
/
/ make a unique filename for the uploaded file and check it is
// not taken... if it is keep trying until we find a vacant one
$now = time();
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
$now++;
$_SESSION['image_name'] = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name'];
}
On my successfulUpload php page I was returning:
<p>Congratulations! Your file <? echo $_Session['image_name']; ?> upload was successful</p>
I have session_start(); at the very top of both the uploadProcessing code and the Successful uploads page.
Thanks for any help!
I see now, on your success page, $_SESSION should be capitalized.

Categories