Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I got an upload script and must to change file name first of uploading.
Here is my code:
<?php
$ds = DIRECTORY_SEPARATOR;
$fileName = $_POST['articleSlug'];
$storeFolder = '../uploads';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
}
?>
I must to use the $fileName variable to change filename, but when I change the $targetFile variable it doesn't upload the file anymore, so I've reverted my code to the moment was working, can you please help me to find how to replace the original file name using the variable content?
Thanks a lot
The most likely error is that changing $targetFile with $fileName, you're trying to write the file to a place where you do not have sufficient permissions.
You probably need to do something like this:
<?php
$ds = DIRECTORY_SEPARATOR;
$fileName = $_POST['articleSlug'];
$storeFolder = '../uploads';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$targetFile = $targetPath . $fileName;
move_uploaded_file($tempFile,$targetFile);
}
?>
Also "move_uploaded_file" throws warnings when somethings goes wrong. You can visualize this warnings with the following lines at begining of the script:
error_reporting(E_ALL);
ini_set('display_errors', 1);
Finally you can do a vardump of the two possible destination and compare them to detect whats going on.
var_dump($targetPath . $fileName, $targetPath. $_FILES['file']['name']);
Replace
$targetFile = $targetPath. $_FILES['file']['name'];
to
$ext = end(explode(".", $_FILES['file']['name']));
$targetFile = $targetPath. fileName . '.' . $ext;
Related
I'm just starting out with Laravel and trying to get file uploads working using Dropzone JS. I can upload files successfully, but they're landing in app/Http/Controllers, where they're not then publicly accessible.
It seems to be treating this directory as the root, so if I specify /uploads as the folder then they'll go in app/Http/Controllers/uploads (which is obviously no good either). Using ..s doesn't seem to have any effect.
This is my store method for the file uploads:
$ds = DIRECTORY_SEPARATOR;
$storeFolder = '';
if ( ! empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
}
I've also tried a number of other methods I found (below) but I get 500 errors in Chrome's element inspector with those.
From official docs
$path = $request->file('file')->store('uploads');
From a tutorial I found
$file = $request->file('file');
$destinationPath = '/';
$file->move($destinationPath,$file->getClientOriginalName());
From another tutorial
$uploadedFile = $request->file('file');
$filename = time().$uploadedFile->getClientOriginalName();
Storage::disk('local')->putFileAs(
'/'.$filename,
$uploadedFile,
$filename
);
The current method seems fine but just needs to store files in public/uploads.
Use this path instead:
$targetPath = public_path().'/uploads/';
I also suggest making a perfect route for our storage path so when someone adds hostname/storage it will not show your directory to someone only files can be accessible
Route::get('storage/{filename}', function ($filename)
{
$path = storage_path('public/' . $filename);
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
});
I am using Uploadify and when a person uploads the file I want the file name to be a random generated file name. Numbers would be fine.
Here is the current PHP I am using:
<?php
$targetFolder = '/uploads';
$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png','doc','docx','pdf','xlsx','pptx','tiff','tif','odt','flv','mpg','mp4','avi','mp3','wav','html','htm','psd','bmp','ai','pns','eps'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo '1';
} else {
echo 'Invalid file type.';
}
}
?>
I tried replacing this:
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
with this (per this answer):
$fileParts = pathinfo($_FILES['Filedata']['name']);
$targetFile = rtrim($targetPath,'/') . '/' .rand_string(20).'.'.$fileParts['extension'];
but that did not work, in fact, it stopped the file from uploading at all.
How do I modify the script to create random file names? Note: I know almost no PHP, please make any answer clear for a beginner.
I'd use uniqid() as I have no idea what rand_string is or where it comes from, eg
$fileParts = pathinfo($_FILES['Filedata']['name']);
$targetFile = sprintf('%s/%s.%s', $targetPath, uniqid(), $fileParts['extension']);
Another thing I never do is rely on DOCUMENT_ROOT. Instead, use a path relative from the current script. For example, say your script is in the document root
$targetPath = __DIR__ . '/uploads';
i have this code here which outputs me an image.. I need to change it because for the moment it gives me something like : test.jpg, what i need is for it to give me test_s.jpg
Using the rename function i guess!
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetPath = str_replace('//','/',$targetPath);
$targetFile = $targetPath . $_FILES['Filedata']['name'];
tamano_nuevo_foto($stempFile, 420, $stargetFile);
You could do:
$extension = array_pop( explode(".", $_FILES['Filedata']['name']) ); //get extension
$targetFile = $targetPath . "some_new_name".$extension;
tamano_nuevo_foto($tempFile, 420, $targetFile);
First: You seem to have a path that can be manipulated by the the user. Your usage of $_REQUEST['folder'] directly in your path is bad. The user could put ANYTHING in there, even stuff like ../../../ to move around your filesystem!
To change the name, simply:
$targetFile = $targetPath . "myfilename.png";
Or you can use this function:
function add_s($file){
$fName = substr($file, 0,strpos($file, "."));
$fExtension = substr($file, strpos($file, "."));
$newFName = $fName."_s".$fExtension;
return $newFName;
}
You should use pathinfo and move_uploaded_file
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/'; // should make this more secure, like a fixed path or in a whitelist
$targetPath = str_replace('//','/',$targetPath);
$ext = pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION);
$basename = pathinfo($_FILES['Filedata']['name'], PATHINFO_BASENAME);
$targetFile = $targetPath . $basename . "_s" . $ext;
move_uploaded_file ( $tempFile , string $targetFile)
//tamano_nuevo_foto($stempFile, 420, $stargetFile); // move and resize ??
I have this snippet from my uploadify.php:
if (!empty($_FILES)) {
$name = $_FILES['Filedata']['name'];
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
$path = pathinfo($targetFile);
// this portion here will be true if and only if the file name of the uploaded file does not contain '.', except of course the dot(.) before the file extension
$count = 1;
list( $filename, $ext) = explode( '.', $name, );
$newTargetFile = $targetFolder . $filename . '.' . $ext;
while( file_exists( $newTargetFile)) {
$newTargetFile = $targetFolder . $filename . '(' . ++$count . ')' . '.' . $ext;
}
// Validate the file type
$fileTypes = array('pdf'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$newTargetFile);
echo $newTargetFile;
} else {
echo 'Invalid file type.';
}
return $newTargetFile;
}
Basically this is quite working. Uploading the file and getting the path of the file which will then be inserted on the database and so on. But, I tried uploading a file which file name looks like this,
filename.1.5.3.pdf
and when succesfully uploaded, the file name then became filename alone, without having the file extension and not to mention the file name is not complete. From what I understood, the problem lies on my explode(). It exploded the string having the delimiter '.' and then assigns it to the variables. What will I do to make the explode() cut the string into two where the first half is the filename and the second is the file extension? PLease help.
Don't use explode, use a function designed for the job: pathinfo()
$ext = pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION);
Ok so I have been trying to get this to work and I dont see any errors but my syntax checker swears there is one on line 14. Can anyone help me out with this?
<?php
// Define a destination
$targetFolder = '***********'; // Relative to the root
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$tempFileExploded = explode($tempFile, ".");
//PROBLEM LINE
$tempFile = $tempFileExploded[0] . date('U') . $tempFileExploded[1];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
//mkdir(str_replace('//','/',$targetPath), 0777, true);
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo '1';
} else {
echo 'Invalid file type.';
}
}
//$targerfile is the file name
?>
The error im getting:
Parse error: syntax error, unexpected T_STRING in CODE on line 14
Errors parsing CODE
When you explode with dot. you need to extension with dot. so dot is missing in your code
$tempFile = $tempFileExploded[0] . date('U') .".". $tempFileExploded[1];