I've set up an XAMPP server and trying to upload image files using a custom admin page. The page works fine when I set it up on a online server running ubuntu.
But when trying the same script in localhost gives me the following error.
Warning : move_upload_file(../img/products/fw000001.jpg) : failed to open stream. No such file or directory in C:\xampp\htdocs\OBS\store\kish\bin\functions.php on line 64
Here is the file upload part of functions.php
function upload_image($image,$code)
{
define("UPLOAD_DIR", "../img/products/");
if (!empty($image)) {
$myFile = $image;
if ($myFile["error"] !== UPLOAD_ERR_OK) {
return null;
}
//check if the file is an image
$fileType = exif_imagetype($_FILES["image"]["tmp_name"]);
$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
if (!in_array($fileType, $allowed)) {
exit();
}
// ensure a safe filename
$name = $myFile["name"];
$parts = pathinfo($name);
$extension = $parts["extension"];
$savename = $code . "." . $extension;
// don't overwrite an existing file
$i = 0;
if(file_exists(UPLOAD_DIR . $savename)) {
unlink(UPLOAD_DIR . $savename);
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $savename);
if (!$success) {
exit();
}
else
{
return $savename;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
}
I'm not pretty sure about directory separator. Directory separator is represent with (/) on Linux based OS. Widows is using ( \ ) for directory separator. So, please change this line and tested it.
define("UPLOAD_DIR", "../img/products/");
to
define("UPLOAD_DIR", "..".DIRECTORY_SEPARATOR."img".DIRECTORY_SEPARATOR."products".DIRECTORY_SEPARATOR.");
Change this line
// preserve file from temporary directory
$success = move_uploaded_file($_FILES["image"]["tmp_name"],UPLOAD_DIR . $savename);
Related
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'm trying to implement file transfer using PHP.
I'm getting the following errors:-
Using Html form to upload a file. PHP file to fetch the file using
$_files. How do I get the original file name with extension from the
php object? basename method gives a different name.
I tried uploading a .txt file. It gets converted into php file and gets
uploaded on the server.
On the download part, I'm using ftp_get. I want the file to get
downloaded to my laptop. However it is getting saved on the server
itself with the whole path which i specify in $fileToy. No error
displayed, also file doesn't get downloaded. Here for simplicity
I've given the path directly considering I've uploaded a .txt file.
Please help for general case(any file format).
Here is my code
if ((isset($_FILES['myfile']['tmp_name'])))
$myfile = $_FILES['myfile']['tmp_name'];
else echo "upload not possible";
$fileFrom = $myfile;
$fileTo = 'photos/'. basename($myfile); //photos is directory created on server
echo $fileTo;
$ftpObj -> uploadFile($fileFrom, $fileTo);
$fileFrom = $fileTo ; # The location on the server
$fileToy = 'Downloads\techppr.txt' ; # Local dir to save to
// *** Download file
$ftpObj->downloadFile($fileFrom, $fileToy);
public function uploadFile ($fileFrom, $fileTo)
{
// *** Set the transfer mode
$asciiArray = array('txt', 'csv');
$extension = end(explode('.', $fileFrom));
if (in_array($extension, $asciiArray)) {
$mode = FTP_ASCII;
} else {
$mode = FTP_BINARY;
}
// *** Upload the file
$upload = ftp_put($this->connectionId, $fileTo, $fileFrom, $mode);
}
public function downloadFile ($fileFrom, $fileTo)
{
// *** Set the transfer mode
$asciiArray = array('txt', 'csv');
$extension = end(explode('.', $fileFrom));
if (in_array($extension, $asciiArray)) {
$mode = FTP_ASCII;
} else {
$mode = FTP_BINARY;
}
if (ftp_get($this->connectionId, $fileTo, $fileFrom, $mode, 0)) {
return true;
$this->logMessage(' file "' . $fileTo . '" successfully downloaded');
} else {
return false;
$this->logMessage('There was an error downloading file "' . $fileFrom . '" to "' . $fileTo . '"');
}
}
I'm using the following code to upload some files, but well, some get replaced since the names get to be alike. I just wanna know how do i change the name, i tried but i kinda find myself messing the entire code.
PHP
if (!empty($_FILES["ambum_art"])) {
$myFile = $_FILES["ambum_art"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
$success = move_uploaded_file($myFile["tmp_name"],UPLOAD_DIR . '/'.$name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
} else {
$Dir = UPLOAD_DIR .'/'. $_FILES["ambum_art"]["name"];
}
chmod(UPLOAD_DIR .'/'. $name, 0644);
unset($_SESSION['video']);
$_SESSION['album_art'] = $Dir;
$ambum_art_result = array();
$ambum_art_result['content'] = $Dir;
echo json_encode($ambum_art_result);
}
I would like each file to have something from this variable generated from time.
$rand_name = microtime().microtime().time().microtime();
Thanks.
I don't want to first check if file exists as that adds to the processes, i just want to use time() and some random string. to just get a unique name.
Please see this website for a decent example of file uploading and an explanation. Also this site appears to be where you found this particular script from or if not offers a good explanation.
I have modified your code to include some comments so you and others can understand what is going on better. In theory, the code shouldn't be overwriting existing files like you say it does but I have added what you would need to change to set the name of the file to a random string.
In addition you are storing the original filename into the session and not the modified filename.
define("UPLOAD_DIR", "/path/to/uploads/");
if (!empty($_FILES["ambum_art"]))
{
// The file uploaded
$myFile = $_FILES["ambum_art"];
// Check there was no errors
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// Rename the file so it only contains A-Z, 0-9 . _ -
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// Split the name into useful parts
$parts = pathinfo($name);
// This part of the code should continue to loop until a filename has been found that does not already exist.
$i = 0;
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// If you want to set a random unique name for the file then uncomment the following line and remove the above
// $name = uniqid() . $parts["extension"];
// Now its time to save the uploaded file in your upload directory with the new name
$success = move_uploaded_file($myFile["tmp_name"], UPLOAD_DIR . '/'.$name);
// If saving failed then quit execution
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// Set file path to the $Dir variable
$Dir = UPLOAD_DIR .'/'. $name;
// Set the permissions on the newly uploaded file
chmod($Dir, 0644);
// Your application specific session stuff
unset($_SESSION['video']);
$_SESSION['album_art'] = $Dir; // Save the file path to the session
$ambum_art_result = array();
$ambum_art_result['content'] = $Dir;
echo json_encode($ambum_art_result);
}
Read more about PHPs uniqid.
I would also strongly advise doing some filetype checking as currently it appears as though any file can be uploaded. The second link above has a section titled 'Security Considerations' that I would recommend reading through vary carefully.
This code is filtering the name, then checks if file with exactly same name is already sent. If it is - name is changed with with number.
If you want to change the file name as in many sites - you may modify this line $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
For example into: $name = time().'_'.preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
If user sends file calle 'hello.jpg' this code will change it to _hello.jpg if file with the same name exists already the name _hello-.jpg will be used instead.
First you need to copy that file which you want to upload and after that you have to rename that. Ex.
//copy
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}
?>
//rename
rename('picture', 'img506.jpg');
Reference Link for copy
Rename file
Edited:
Replace your code with this and then try
<?php
if (!empty($_FILES["ambum_art"])) {
$myFile = $_FILES["ambum_art"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
if (file_exists($myFile["name"])) {
rename($myFile["name"], $myFile["name"].time()); //added content
}
$success = move_uploaded_file($myFile["tmp_name"],UPLOAD_DIR . '/'.$name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
} else {
$Dir = UPLOAD_DIR .'/'. $_FILES["ambum_art"]["name"];
}
chmod(UPLOAD_DIR .'/'. $name, 0644);
unset($_SESSION['video']);
$_SESSION['album_art'] = $Dir;
$ambum_art_result = array();
$ambum_art_result['content'] = $Dir;
echo json_encode($ambum_art_result);
}
?>
This will rename your existing file and then copy your file
I have a problem here im trying to upload a file
first time it is moving the filename from temp it its respective directory,
but again i try ot upload the aa different file with the same name it should rename the
first time uploaded file
with date_somefilename.csv and give the filename to its original state
for example a file test.csv ,im uploading it for first time it will upload to
corresponding directory as
test.csv,when i upload a different csv file with same name test.csv
I need to get the
test.csv (latest uploaded file)
06222012130209_test.csv(First time uploaded file)
The code is below
$place_file = "$path/$upload_to/$file_name";
if (!file_exists('uploads/'.$upload_to.'/'.$file_name))
{
move_uploaded_file($tmp, $place_file);
}else{
move_uploaded_file($tmp, $place_file);
$arr1 = explode('.csv',$file_name);
$todays_date = date("mdYHis");
$new_filename = $todays_date.'_'.$arr1[0].'.csv';
echo $str_cmd = "mv " . 'uploads/'.$upload_to.'/'.$file_name . " uploads/$upload_to/$new_filename";
system($str_cmd, $retval);
}
See comments in code.
$place_file = "$path/$upload_to/$file_name";
if (!file_exists($place_file)) {
move_uploaded_file($tmp, $place_file);
} else {
// first rename
$pathinfo = pathinfo($place_file);
$todays_date = date("mdYHis");
$new_filename = $pathinfo['dirname'].DIRECTORY_SEPARATOR.$todays_date.'_'.$pathinfo['basename'];
rename($place_file, $new_filename)
// and then move, not vice versa
move_uploaded_file($tmp, $place_file);
}
DIRECTORY_SEPARATOR is php constant. Value is '/' or '\', depending of operation system.
pathinfo() is php function, that return information about path: dirname, basename, extension, filename.
What about...
$place_file = "$path/$upload_to/$file_name";
if (file_exists($place_file)) {
$place_file = date("mdYHis")."_".$file_name;
}
if (!move_uploaded_file($tmp, $place_file)) {
echo "Could not move file";
exit;
}
I would not add a date to the file if it already exists. Instead I would just add a number to the end of it. Keep it simple.
$counter = 0;
do {
// destination path path
$destination = $path.'/'.$upload_to.'/';
// get extension
$file_ext = end(explode('.', $file_name));
// add file_name without extension
if (strlen($file_ext))
$destination .= substr($file_name, 0, strlen($file_name)-strlen($file_ext)-1);
// add counter
if ($counter)
$destination .= '_'.$counter;
// add extension
if (strlen($file_ext))
$destination .= $file_ext;
$counter++;
while (file_exists($destination));
// move file
move_uploaded_file($tmp, $destination);
$target = "uploads/$upload_to/$file_name";
if (file_exists($target)) {
$pathinfo = pathinfo($target);
$newName = "$pathinfo[dirname]/" . date('mdYHis') . "_$pathinfo[filename].$pathinfo[extension]";
rename($target, $newName);
}
move_uploaded_file($tmp, $target);
Beware though: Security threats with uploads.
how about something like this?
<?php
$tmp = '/tmp/foo'; // whatever you got out of $_FILES
$desitnation = '/tmp/bar.xyz'; // wherever you want that file to be saved
if (file_exists($desitnation)) {
$file = basename($destination)
$dot = strrpos($file, '.');
// rename existing file to contain its creation time
// "/temp/bar.xyz" -> "/temp/bar.2012-12-12-12-12-12.xyz"
$_destination = dirname($destination) . '/'
. substr($file, 0, $dot + 1)
. date('Y-m-d-H-i-s', filectime($destination))
. substr($file, $dot);
rename($destination, $_destination);
}
move_uploaded_file($tmp, $destination);