PHP: Move uploaded file to a dynamically created path - php

In this PHP code I'm going to upload a file (sent from AS3) to a directory that already created for each user with same name his username. The problem is that I don't know how to move the file into a folder associated to a user. If a user doesn't have his own folder, some code should be able to get the user's name from $_SESSION['myusername'] and then dynamically create it and then move the file:
<?php
session_start();
$username =$_SESSION['myusername'];
$uploads_dir = $_SERVER['DOCUMENT_ROOT'].'/upload/'.'/$username/';
if ( ! is_dir($uploads_dir)) {
mkdir($uploads_dir);
}
if( $_FILES['Filedata']['error'] == 0 ){
if( move_uploaded_file( $_FILES['Filedata']['tmp_name'],
$uploads_dir.$_FILES['Filedata']['name'] ) ){
exit();
}
}
echo 'error';
exit();
?>
But this code move file into "upload" directory and if the uploaded file name be xxx then file name change to xxx$username. How can do this please?

You have the right idea, you just need to also add the file name to the end of your path, something like:
$uploads_dir = "upload/".$username."/".$_FILES['Filedata']['name']
Then use move_uploaded_file() like so:
move_uploaded_file( $_FILES['Filedata']['tmp_name'],
$uploads_dir )
Also, its always a good idea to go ahead and make sure the directory exists before hand with file_exists().
I've also found that move_uploaded_file() likes full paths for the destinations, you can use $_SERVER[DOCUMENT_ROOT] to get this

Related

move_uploaded_file function save to different directory folder problem

I am using move_uploaded_file function to save my file into two folders, the folders name are uploads_meeting_document and uploads_filing_file. It just can let me upload my file to this folder name uploads_meeting_document, it can't save to uploads_filing_filefolder. Anyone can guide me which part I have problem in below the coding:
<?php
require_once("../conf/db_conn.php");
// Getting uploaded file
$file = $_FILES["file"];
// Uploading in "uplaods" folder
$pname = date("ymdhi")."-".$_FILES["file"]["name"];
//$title_name = $_FILES["file"]["name"];
$tname = $_FILES["file"]["tmp_name"];
$uploads_dir = 'uploads_meeting_document';
move_uploaded_file($tname, $uploads_dir.'/'.$pname);
$uploads_dir2 = 'uploads_filing_file';
move_uploaded_file($tname, $uploads_dir2.'/'.$pname);
?>
Below is my file path need to save to these folders(red arrow there)
In your example, the second move_uploaded_file does not work, because the file was already moved to /upload_meeting_document
You will need to copy your file from there:
...
$uploads_dir2 = 'uploads_filing_file';
copy($uploads_dir.'/'.$pname, $uploads_dir2.'/'.$pname);
In case this does not work, you may have insufficient permissions for the /uploads_filing_file directory. Chech its owner and permissions.

Get full path while opening a directory

I'm creating a script to run through a given folder and list all files inside it.
The problem is: The user may or may not give the full path or just the folder name (if the target folder is inside the script folder).
Is there a way to get the full/absolute path of that folder even if the user gives only its name ?
//Check if the folder path was given as an argument
if( $argc >= 2) {
$folderPath = $argv[1]; //Read the folder path argument
if( !is_dir($folderPath) ) {
echo "Folder does NOT exists !";
}
else {
if( $handle = opendir($folderPath) ) {
//Find the $folderPath absolute path here
$folderPath may be:
- C:\wamp64\www\myfolder\documents
- Or just: documents
either cases the script will find the folder, open it and list it's files. But I need to write the fullPath later on the code.
You may want realpath, which cuts through all the issues - relative paths, symbolic links, etc.

php move_uploaded_file not creating file

I am having a problem with move_uploaded_file().
I am trying to upload a image path to a database, which is working perfectly and everything is being uploaded and stored into the database correctly.
However, for some reason the move_uploaded_file is not working at all, it does not produce the file in the directory where I want it to, in fact it doesn't produce any file at all.
The file uploaded in the form has a name of leftfileToUpload and this is the current code I am using.
$filetemp = $_FILES['leftfileToUpload']['tmp_name'];
$filename = $_FILES['leftfileToUpload']['name'];
$filetype = $_FILES['leftfileToUpload']['type'];
$filepath = "business-ads/".$filename;
This is the code for moving the uploaded file.
move_uploaded_file($filetemp, $filepath);
Thanks in advance
Try this
$target_dir = "business-ads/";
$filepath = $target_dir . basename($_FILES["leftfileToUpload"]["name"]);
move_uploaded_file($_FILES["leftfileToUpload"]["tmp_name"], $filepath)
Reference - click here
Try using the real path to the directory you wish to upload to.
For instance "/var/www/html/website/business-ads/".$filename
Also make sure the web server has write access to the folder.
You need to check following details :
1) Check your directory "business-ads" exist or not.
2) Check your directory "business-ads" has permission to write files.
You need to give permission to write in that folder.
make sure that your given path is correct in respect to your current file path.
you may use.
if (is_dir("business-ads"))
{
move_uploaded_file($filetemp, $filepath);
} else {
die('directory not found.');
}

file_exists() not working as expected

In the code below, file_exists() is not working as expected. Even when I'm trying to upload the same file, the else part gets executed. (ie file_exists() returns false in every case.) What is the reason behind this behavior?
if (isset($_FILES['file']['name']) && isset($_FILES['file']['size']) && isset($_FILES['file']['type']) && isset($_FILES['file']['tmp_name']))
{
if (!empty($_FILES['file']['name']) && strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION))=='jpg' || strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION))=='jpeg')
{
if(file_exists($_FILES['file']['name']))
{
echo 'file exists';
}
else
{
move_uploaded_file($_FILES['file']['tmp_name'], 'Images/'.$_FILES['file']['name']);
echo $_FILES['file']['name'].' Uploaded'.'<br>';
}
}
}
else{
echo 'select your file';
}
The problem
When you use file_exists, you only use the short name of the file.
if(file_exists($_FILES['file']['name']))
For example, if you upload a file called test.jpg, it checks if ./test.jpg exists.
But, when you actually move the uploaded file, you put it in a directory called Images:
move_uploaded_file($_FILES['file']['tmp_name'], 'Images/'.$_FILES['file']['name']);
Now, if you upload that test.jpg, it's moved to ./Images/test.jpg, which isn't found by your other code.
The solution
You should use the same file name in both cases. So, just change the if with the file_exists call to:
if(file_exists('Images/'.$_FILES['file']['name']))
This code adds the folder name to the file name, so that you check for the correct path; uploading test.jpg leads to checking the file ./Images/test.jpg.
$_FILES['file']['name'] is your INPUT / POST data, not your real file;
You should check $your_dir_path_to_file . '/'.$_FILES['file']['name']
Set up the default file system separator (system dependent):
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
If you can, try using absolute path not a relative one and secure the system from names like "../../file.jpg":
defined('BASE_PATH') ? null : define('BASE_PATH', 'C:'.DS.'www'.DS.'Images'.DS);

PHP move_uploaded_file doesn't work

I'm using HTTP post to upload image to server and I have the following PHP code:
$base_path = "";
$target_path = $base_path . basename ( $_FILES ['uploadfile'] ['name'] );
if (move_uploaded_file ( $_FILES ['uploadfile'] ['tmp_name'], $target_path )) {
echo "Good";
} else {
echo "FAIL";
}
I'm sure the image has been uploaded to temp. But no matter what, I just can't store image file. my current permission is 664 for testing.
You need to set your $base_path variable to an absolute path to where you are storing the file. ( ie. /path/to/your/document/root/image/directory/ )
Additionally, make sure the directory you will be storing the images in is either owned by the apache user or that it is writable by the apache user (chmod 777).
Try this:
Pl check the uploaded path is correct before move the file
&&
Set the folder permission to 777 where you upload the file.
Thanks!

Categories