ARRAY is preceding renamed filenames after upload - PHP - php

I am running a PHP script to upload files from a HTML form, rename them and place them on my server. It is uploading and renaming, however every file name now starts with the word "Array"
ie: ArrayTest Document v1.0.pdf
I am fairly confident it isn't my $newfn variable as I display that in a table and it doesnt show up.
//This gets all the other information from the form
$name=$_POST['docname'];
$version=$_POST['docver'];
$date=$_POST['docdate'];
$type=$_POST['doctype'];
$author=$_POST['docauth'];
$file=$_FILES['uploaded']['name'];
//target directory is assigned
$target = $directory;
$target = $target . basename($file) ;
//grab file extension
$filetypes = array(
'image/png' => '.png',
'image/gif' => '.gif',
'image/jpeg' => '.jpg',
'image/bmp' => '.bmp',
'application/pdf' => '.pdf');
$ext = $filetypes[$_FILES['uploaded']['type']];
//generate new filename variable "name v??.xxx"
$newfn = $name . ' ' . 'v' . $version . $ext;
//Check to see if file exists
if (file_exists($directory . $file))
{
echo $_FILES["uploaded"]["name"] . " already exists. ";
}
else
{
//if its a new file, change name and upload
if (move_uploaded_file($_FILES["uploaded"]["tmp_name"],
$directory . $_FILES["uploaded"] . $newfn))
{
echo "The file ". basename($file). " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
}
I feel like it's related to my $FILES['uploaded'] section in the move_uploaded_file command. I've tried googling but as soon as I mention "Array" my google results are nothing remotely the same.
Ok so thanks to below I solved it. For anyone in the future I removed the entire $_FILES array so the code reads as
//if its a new file, change name and upload
if (move_uploaded_file($_FILES["uploaded"]["tmp_name"],
$directory . $newfn))
Everything now uploads with the correct name structure. Thanks.

Should be
move_uploaded_file($_FILES["uploaded"]["tmp_name"],$directory . $_FILES["uploaded"]["name"] . $newfn)
You forgot to include ["name"] after $_FILES["uploaded"]

In your move_uploaded_file you are using the whole $_FILE['uploaded'] array as the name, not just the filename. A small tweak:
if (move_uploaded_file($_FILES["uploaded"]["tmp_name"],
$directory . $_FILES["uploaded"]["name"] . $newfn))
{
And you should be all good.

Related

Create random filename but check it's not already used

I am trying to upload image files to a server and creating a random name when doing so. The issue I am having is that sometimes (far too often) it creates the same file name but for files with a different extension.
My code for the upload is below, what I want to do is add a check to make sure the name is not in use but with a different extension.
Example -
da4fb5c6e93e74d3df8527599fa62642.jpg & da4fb5c6e93e74d3df8527599fa62642.JPG
if ($_FILES['file']['name']) {if (!$_FILES['file']['error']){
$name = md5(mt_rand(100, 200));
$ext = explode('.', $_FILES['file']['name']);
$filename = $name . '.' . $ext[1];
$destination = $_SERVER['DOCUMENT_ROOT'] . '/images/infopages/' . $filename; //change this directory
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo '/images/infopages/' . $filename;
}else{
echo $message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
Any help is appreciated.
You can use PHP uniqid & rand functions combinedly. In this way you will never get duplicate values.
$filename = uniqid (rand(1000000,9999999), true) '.' . $ext[1];

Laravel: The file was not uploaded due to an unknown error

I am trying to upload a file to two different locations. The lcoations being /2x/ adn /3x/. It uploads the file on 3x but doesn't on 2x and throws this error:
The file was not uploaded due to an unknown error
Here is what i am doing:
$photo = $request->file('photo');
if (isset($photo)) {
if ($photo != null || $photo != '') {
$imageSize = getimagesize($photo);
$resolution = $imageSize[0] . 'x' . $imageSize[1];
if ($resolution == '300x300' || $resolution == '450x450') {
if (!file_exists(base_path('uploads/custom_avatar'))) {
mkdir(base_path('uploads/custom_avatar'), 0777, true);
}
$resolution = "3x";
$uploadPath = base_path('uploads/custom_avatar/' . $resolution . '/');
$otherImageResolution = '2x';
$otherImagePath = base_path('uploads/custom_avatar/' . $otherImageResolution . '/');
//echo $otherImagePath;exit;
// saving image
$fileName = $child->id . '_' . time() . '.png';
$photo->move($uploadPath, $fileName);
$photo->move($otherImagePath, $fileName);
// creating records
$childImage = Images::addPhoto($child->id, $fileName, $resolution);
$otherImage = Images::addPhoto($child->id, $fileName, $otherImageResolution);
if ($childImage && $otherImage) {
$result = Child::createChildResponseData($child);
\Log::info('Child avatar added Successfully' . json_encode($childImage));
return response()->json([
'status' => $this->SUCCESS,
'response' => $result,
], $this->SUCCESS);
}
Any help?
Check your code if your file upload code is running two times.
I was facing the same issue & then I find that my file upload code is running two times.
after commenting one of them it's working fine.
You can try this:
$request->file('photo')->move($destination_path, $file_name);
Add DIRECTORY_SEPARATOR between path and filename if needed and
copy that file at new location
copy($destination_path.$file_name, $new_path.$new_file_name);
Check your code if your file upload code is running two times.
You can check this part of the code. Make sure you type it correctly and not repeat it twice.
// Original size upload file
$section_image_file->move($folder, $section_image_name);

Adding random number to uploaded file in PHP

I have my upload php code where my intent is , obtained file from $_files,
add a random number between 0 and 9999 to the name of image like this:
image sent : image.jpg
before saving : image321.jpg
the image is saved in my upload folder but the filename are like
"php2983204tmp"
if ($file !== null) {
$rand = rand(0000,9999);
$path = "some_path";
$file_name = $file->getClientOriginalName(); // file
$extension = $file->getClientOriginalExtension(); // jpg
$file->move($path, $file_name.$rand.$extension);
$response = "File loaded successfully: " . $file_name.$extension;
$response .= '<br>size: ' . filesize($path . '/' . $file->getClientOriginalName()) / 1024 . ' kb';
return new Response($response);
any ideas to fix?
The filename in your example is php and your extension is tmp. None of them have the . that you are missing.
You need to add the dot . as a string after the $file_name and $rand, before the $extension like this:
$file->move($path, $file_name.$rand. "." .$extension);
TIME is always unique identity, use it as below (maybe helpful):
if ($file !== null) {
$rand = rand(0000,9999).time();
$path = "some_path";
$file_name = $file->getClientOriginalName(); // file
$extension = $file->getClientOriginalExtension(); // jpg
$file->move($path, $file_name.$rand.$extension);
$response = "File loaded successfully: " . $file_name.$extension;
$response .= '<br>size: ' . filesize($path . '/' . $file->getClientOriginalName()) / 1024 . ' kb';
return new Response($response);
You need add in the desired chars to the actual string.
$file->move($path, $file_name.$rand.".".$extension);
But I have to say, I am against how you've done this, you don't even check if the "newly" created string already exists in the directory. Its better to hash the time of upload with the original filename, rename the file to the new hash and use a database to point to the file as this way the filename collisions don't occur.
$fn = md5(microtime(true) . $extension . $file_name);
$file->move($path, $fn);

move_uploaded_file(): Unable to move

$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

Php file upload strange behaviour, occasionally upload is empty

I use this script to upload files via POST from my android app to my server. 95% of the time it works ok, but sometimes the upload folder of my clients is empty. The file is sent definitely, because I get the name and phone numbers (without a file selected the app will not pass any data), but the uploaded file is not written to disk on the server. I am not an expert in php, maybe I have missed something:
My upload php script:
$file_path = "uploads/{$_POST['name']}/";
if (!file_exists("uploads/{$_POST['name']}")) {
mkdir("uploads/{$_POST['name']}", 0777, true);
} else {
echo 'folder already exists!';
}
$newfile = $_POST['name'] . "_" . date('m-d_H-i-s') . '.zip';
$filename = $file_path . $newfile;
if(!file_exists($filename)) {
if(move_uploaded_file($_FILES['zipFile']['tmp_name'], $filename)) {
echo "success";
}
} else {
echo 'file already exists';
}

Categories