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);
Related
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.');
}
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
$myfilepath = SITEROOT."/uploads/vaibhav_photo/thumbnail/".$user_avatar['thumbnail'];
if(file_exists($myfilepath))
{
echo "file exist";
}
else
{
echo "file does not exist";
}
It always goes to else part even though file is present.
if anybody have an alternate option for this in PHP please reply as fast as possible,
file_exists works on file paths only. http:// URLs are not supported.
$myfilepath = SITEROOT.DS.'uploads'.DS.'vaibhav_photo'.DS.'thumbnail'.DS.$user_avatar['thumbnail'];
NOTE::SITEROOT have actual root path and DS is constant DIRECTORY_SEPARATOR.
Pekka is correct that file_exists does not support http protocol.
You can however use file_get_contents
if(file_get_contents($myfilepath)) {
echo "file exist";
}
By default this pulls back the entire contents of the file. If this is not what you want you can optimise this by adding some flags:
if(file_get_contents($myfilepath, false, null, 0, 1)) {
echo "file exist";
}
This syntax will return the first character if it exists.
Check what your working directory is with getcwd().
Your path
example.com/uploads/etc/etc.jpg
is interpreted relative to the current directory. That's likely to be something like
/var/www/example.com
so you ask file_exists() about a file named
/var/www/example.com/example.com/uploads/etc/etc.jpg
You need to either figure out the correct absolute path (add the path containing all site roots in front of SITEROOT) or the correct relative path (relative to the directory your script is in, without a leading /).
tl;dr: try
$myfilepath = 'uploads/etc/etc.jpg';
In my script, I set the include path (so another part of the application can include files too), check that a file exists, and include it.
However, after I set the include path, file_exists() reports that the file does not exist, yet I can still include the same file.
<?php
$include_path = realpath('path/to/some/directory');
if(!is_string($include_path) || !is_dir($include_path))
{
return false;
}
set_include_path(
implode(PATH_SEPARATOR, array(
$include_path,
get_include_path()
))
);
// Bootstrap file is located at: "path/to/some/directory/bootstrap.php".
$bootstrap = 'bootstrap.php';
// Returns "bool(true)".
var_dump(file_exists($include_path . '/' . $bootstrap));
// Returns "bool(false)".
var_dump(file_exists($bootstrap));
// This led me to believe that the include path was not being set properly.
// But it is. The next thing is what puzzles me.
require_once $bootstrap;
// Not only are there no errors, but the file is included successfully!
I can edit the include path and include files without providing the absolute filepath, but I cannot check whether they exist or not. This is really annoying as every time a file that does not exist is called, my application results in a fatal error, or at best a warning (using include_once()).
Turning errors and warnings off is not an option, unfortunately.
Can anyone explain what is causing this behaviour?
file_exists does nothing more than say whether a file exists (and the script is allowed to know it exists), resolving the path relative to the cwd. It does not care about the include path.
Yes Here is the Simplest way to implement this
$file_name = //Pass File name
if ( file_exists($file_name) )
{
echo "Exist";
}
else
{
echo "Not Exist";
}
<?php
if($_FILES['Filedata']['size']>=520000)
{
echo "\n Sorry, Not Moved Size below 5.2kb or 5200 bytes Only\n";
return;
}
$ext = end(explode('.', strtolower($_FILES['Filedata']['name'])));
if(move_uploaded_file($_FILES['Filedata']['tmp_name'], "./".$_FILES['Filedata']['name']))
{
echo "\nfile moved Success\n";
return;
}
?>
When i set path, it does not work... i dont know where to exactly set path such that the file gets saved in the directory.
See the move_uploaded_file documentation.
The first argument ($_FILES['Filedata']['tmp_name']) is the source, which you shouldn't change. The second argument ("./".$_FILES['Filedata']['name']) is the destination, which will currently put the file in the current working directory with its original name (This can be a security issue; you should put the file in an upload directory that has no execute permissions.)