I found a good function on github for uploading images using php, but I do not know one of its arguments.
upload_image($_FILES,'file',250,'city',500,'../../uploaded/',1048576);
Function on Github
What is 'file' in this function?
Is this a trusted function to use in my website?
Considering the lines:
$file[$fileIndex]['tmp_name']
$file[$fileIndex]['error']
$file[$fileIndex]['name']
$file[$fileIndex]['type']
$file[$fileIndex]['size']
$file is a three-dimensional array, composed of arrays of name, tmp_name, type, size, error.
It is the kind of array you see when uploading files in PHP.
It calls move-uploaded-file, which moves an uploaded file to a new location.
This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism).
If the file is valid, it will be moved to the filename given by destination.
Related
I built a parsial uploading in PHP and Client-Side Javascript.
The Flow
Convert the file to base64 so I get the base64 string
Slice the base64 string into some pieces
Post every piece and the position to upload handler
The upload handler make the post data as a single file in one same folder
If the iteration stop, the JS tell the upload handler to build the code
Then the upload handler make all files as a single file then decode the base64 to a new file
The problem
When the build finished, I can't read the result file as same as the $_FILES in file uploading. So I can't get:
Original size
Original extension
I wonder can PHP read the information about the file?
I expect some function like this (not the actual function)
$file = read_the_file('/path/to/file');
$metas = read_meta_file($file);
and then you can get what type of file and some others data.
Note
Currently, the file that I work with is a video file.
You can get the information about the file with the help of php function named pathinfo
How to use pathinfo:
print_r(pathinfo("/path_of_file/123.txt"));
It will return .....
Array ( [dirname] => /path_of_file [basename] => 123.txt [extension] => txt )
2. You can get the size of the file with the help of php function named filesize
How to use filesize:
echo filesize("123.txt");
It will return the size of file in bytes.
I hope, This will help you.
Good Luck.
You can use pathinfo php function
For file size you can use filesize function
To get extension from base_64 then you can use finfo_buffer function
echo finfo_buffer(finfo_open(), $base64, FILEINFO_MIME_TYPE);
But you would need to store somewhere that extension - in video files for example in ID3 tags (and use the lib https://github.com/JamesHeinrich/getID3/ to extract it). That is most likely NOT what you want to do as you would need to edit the file on the frontend.
Another option is to use mime_content_type(after you file has finished uploading) - for a "mp4" file, even without extension, it will give you "video/mp4", for mkv "video/x-matroska". Etc. based on the mime-type you can build the extension again - for example:
$exts = [
"video/x-matroska" => "mkv",
"video/mp4" => "mp4"
];
and then:
$extension = $exts[mime_content_type("..path..to..file")];
(of course first with checking if the entry exists there).
Extension itself is NOT stored in any metadata so you cannot simply extract it.
While having the mime-type you can also use any popular libs - like:
https://github.com/ralouphie/mimey
to convert mime-type to extension.
To get the file size it is best to simply use the filesize function.
Another option would be to simply send the original file name with the last post (the one which tells the backend that the file has finished): probably the most reliable one.
why should I use this code to get the name of the file?
$filename = pathinfo($_FILES['file']['name'], PATHINFO_FILENAME)
If I could also get the name through this code:
$filename = $_File['file']['name']
Thank you very much! I'm a beginner in PHP, so sorry if the question is too dumb :D
Because $_File['file']['name'] comes from the user end, and although ordinarily it is just the file name, an ill-intentioned user can actually set it to whatever he wants (example: full path name to overwrite files in the server) and you have to filter it just like every other user input to prevent an attack vector in your system.
Same is true for everything in $_FILE, don't trust the informed MIME type, don't save files without checking if the extension is safe (saving a .php file will be a disaster) etc.
For example, I've seen a system that would trust files of type equal to image/jpeg and other image types, and then saves it without checking the actual file extension. A forged request can inject a .php shell script to this website's upload folder and be used to take control.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to make an upload script with html forms and PHP, I've seen a lot of people using move_uploaded_file and I can't figure out what it does, I looked around and all other websites are too complex for me. Can someone "dumb" it down a bit for me?
An example of what i saw:
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))
Also can someone explain $_FILES to me aswell?
move_uploaded_file — Moves an uploaded file to a new location
This function checks to ensure that the file designated by filename is
a valid upload file (meaning that it was uploaded via PHP's HTTP POST
upload mechanism). If the file is valid, it will be moved to the
filename given by destination.
This sort of check is especially important if there is any chance that
anything done with uploaded files could reveal their contents to the
user, or even to other users on the same system.
Which part of that Manual you need help with?
$_FILES from the PHP Manual:
An associative array of items uploaded to the current script via the HTTP POST method.
move_uploaded_file() from the PHP Manual:
bool move_uploaded_file ( string $filename , string $destination )
This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.
You can use it like this:
if(move_uploaded_file($_FILES['picture']['tmp_name'], './uploads/'.$_FILES['picture']['name']))
echo 'File successfully uploaded';
else
echo 'File could not be uploaded';
$_FILES['picture']['tmp_name']:
The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['picture']['name']:
The original name of the file on the client machine.
For more information check out POST Method Uploads
$_FILES is a superglobal, much like $_GET or $_POST, that stores the information about the uploaded file.
If the name of your upload input form element is 'myfile' then, after uploading you will have an assiciative array $_FILES['myfile'] storing all the data about the uploaded file. To learn about it, just var_dump() it:
var_dump($_FILES['myfile']);
All the uploaded files are usually first uploaded to the /tmp directory (or whatever directory is set for this purpose in the php.ini file). After doing some sanity checks about the file (like testing for the right mime type), you will want to move the file to it's final destination. That's what the move_uploaded_file() function is intendedn for.
In this case $_FILES['userfile']['tmp_name'] is the temporary file path of the uploaded file and $uploadfile should store the final path of the file.
I've got a script, largely based on an example uploading PHP file from jQuery Uploader. It gets file type with the following code (it gets this $_FILES component)...
$fileType = (isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type']);
Note; $upload['type'] comes from the $_FILES['files']['type'].
Now, this is fine - except for the fact that some files seem to have no fileType information from this. I can get more accurate responses from using file info and mimetype functions in PHP - but they don't work on $_FILES objects and I'm trying to do this check before I transfer the file to s3 so I don't really want to load it locally.
Can anyone advise if there's something I can to get more accurately report type from $_FILES or is it going to have to load locally in order to run these alternative PHP functions?
finfo is the only way to do this. You cannot rely on information the client sends you, it is far too easy to fake from the client side.
There is no reason that it won't work with $_FILES, you would simply pass $_FILES['files']['tmp_name'] as the file path - this is still a valid file path, and you don't need to call move_uploaded_file() to access the data. Leaving the file in the temp location also has the advantage that it will be destroyed when the script is finished if you haven't done anything with it.
I am using plupload to do an upload of multiple files to my server. Using this, there is a parameter 'url : 'upload.php'. upload.php catches the files as they are received, and might recombine them if they get chunked. Once the full file is received, it sends a response back to the original page, displaying a green checkbox icon.
I have added some code to this page, after all the main code to manipulate the photos I have uploaded. My plan is to create three copies of my full size image, lg, med, and small. I got this part working, but then decided to first rename the original file to match my naming scheme.
I now get a corrupted renamed file, and thus my three smaller images also get corrupted.
//get the original file info
$filepath = $_SERVER['DOCUMENT_ROOT'].'/uploads/';
$filepathinfo = pathinfo($filepath.$fileName);//fileName is used previously in the file
//rename original file to a unique name
$finding_id = 'xyz';
$file_name_new = uniqid($client_id . '-' . $finding_id . '-', true); //doesn't include extension
//rename($filepath.$fileName, $filepath.$file_name_new.'.'.$ext);
//copy($filepath.$fileName, $filepath.$file_name_new.'.'.$ext);
As is, I get my one file, or how ever many I uploaded, byte size matches original exactly, and name stays the same (except for removal of certain characters).
If I uncomment only the rename function, I actually get two files. The byte sizes total the original photo. The larger file displays with a section of gray at the bottom. The smaller file doesn't display at all.
If I uncomment only the copy function, I get an exact renamed copy of my original file, my original file, and another file, the same size and corruption as the larger file doing a rename.
Any ideas? Seems like it should be pretty straightforward.
if the file was currently uploaded by HTTP POST use move_uploaded_file
if you fopen() somewhere in this request the same file make sure to call fclose()
I forgot I had the chunking feature turned on. Must have turned it on to test something. For whatever reason, when the script was running the last chunk of the file hadn't been fully appended yet. Thanks for all the input anyway!
Are you writing to the file yourself? If so, the problem might be that you're missing a call to fflush or fclose. (The last chunk of the file not getting written and the file no longer being there when PHP gets round to writing it. This shouldn't happen if you're using Linux or some other Unix, but I could envisage it on Windows.)