Reputation: 268
I need to know what to use for a destination path for PHP's move_uploaded_file function. (see http://php.net/manual/en/function.move-uploaded-file.php)
Right now, I have code that works fine. My domain's root directory contains the following items (among others):
uploads <-this is a folder
add-photo-submit.php <-this is a PHP file that uses move_uploaded_file
In add-photo-submit.php, I have the following line of code:
$target_path = "uploads/" . basename($_FILES['uploadedFile']['name']);
$target_path is used as the destination parameter for the function. This works just fine when I access the file through www.mydomain.com/add-photo-submit.php
However, I recently changed the .htaccess file to remove the .php and add a trailing slash. Now the PHP file is accessed at www.mydomain.com/add-photo-submit/ I think the PHP file is interpreting the target path as "www.mydomain.com/add-photo-submit/uploads/filename.jpg"
I tried using an absolute path, but it said I didn't have permission...
In the future I would like my root directory to be setup like this:
root
-admin (folder)
-add-photo-submit.php
-uploads
What frame of reference does move_uploaded_file have?
Upvotes: 9
Views: 63856
Reputation: 447
$file_name ="eg-db.sql";
echo "<br>";
echo $target_file = __DIR__.'/'.$file_name;
echo "<br>";
echo $target_location = __DIR__."/targetfolder/". pathinfo($target_file, PATHINFO_BASENAME);
echo "<br>";
if (file_exists($target_file)){
echo "<br> file exist <br>";
if (rename($target_file,$target_location))
{
echo "<br>done";
}else{
echo "<br>nothing";
}
}
Upvotes: 0
Reputation: 31
We can use dirname(__FILE__)
instead of server root
declare below line in any of root file(index.php)
$_SESSION["uploads_base_url"]=dirname(__FILE__);
and you can now use this in any files where upload is needed.
echo $uploads_base_url=$_SESSION["uploads_base_url"];
Upvotes: 2
Reputation: 1365
You should use document_root to get absolute path like this:
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . basename($_FILES['uploadedFile']['name']);
Upvotes: 32
Reputation: 360672
PHP's local filename operations have no idea what mod_rewrite did to your urls, and deal only with actual raw file system paths. You could have mod_rewrite turn your nice simple example.com/index.php
into a hideous example.com/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/yz
and PHP would still be running in the same physical directory on the server.
If the PHP script lives at /home/sites/example.com/html/index.php
, and you use uploads/example.jpg
as your move path, then PHP will attempt to put that image into /home/sites/example.com/html/uploads/example.jpg
, regardless of what the requested URL was.
Upvotes: 3