I am currently working with uploading files into a file system with the help of php. Specifically, I am working with csv extension files. I am able to get the filed stored in the folder called csv_uploads and assigned it a unique name. The issues is that the file is being saved in the directory with a .1 as file extension and therefore losing the csv extension. What is the reason of such of behavior?
header('Content-Type: text/plain; charset=utf-8');
try {
// Undefined | Multiple Files | $_FILES Corruption Attack
// If this request falls under any of them, treat it invalid.
if (
!isset($_FILES['upfile']['error']) ||
is_array($_FILES['upfile']['error'])
) {
throw new RuntimeException('Invalid parameters.');
}
// Check $_FILES['upfile']['error'] value.
switch ($_FILES['upfile']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('Exceeded filesize limit.');
default:
throw new RuntimeException('Unknown errors.');
}
// You should also check filesize here.
if ($_FILES['upfile']['size'] > 1000000) {
throw new RuntimeException('Exceeded filesize limit.');
}
// DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['upfile']['tmp_name']),
array(
'text/csv',
'text/plain',
'application/csv',
'text/comma-separated-values',
'application/excel',
'application/vnd.ms-excel',
'application/vnd.msexcel',
'text/anytext',
'application/octet-stream',
'application/txt'
),
true
)) {
throw new RuntimeException('Invalid file format.');
}
// You should name it uniquely.
// DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
// On this example, obtain safe unique name from its binary data.
if (!move_uploaded_file(
$_FILES['upfile']['tmp_name'],
sprintf('./csv_uploads/%s.%s',
sha1_file($_FILES['upfile']['tmp_name']),
$ext
)
)) {
throw new RuntimeException('Failed to move uploaded file.');
}
echo 'File is uploaded successfully.';
} catch (RuntimeException $e) {
echo $e->getMessage();
}
I think you have not set the variable $ext. Try setting the proper extension based on mime type.
The $ext currently contains the boolean value 1/0 based upon the search condition you have applied for the mime-type. i.e why your code is picking up extension value as 1. So file name becomes file_name.1
In this case
$ext = 'csv';
if (!move_uploaded_file(
$_FILES['upfile']['tmp_name'],
sprintf('./csv_uploads/%s.%s',
sha1_file($_FILES['upfile']['tmp_name']),
$ext
)
)) {
throw new RuntimeException('Failed to move uploaded file.');
}
Related
I am trying PHP Script in which users can upload files.
I am Using Script from php.net.
It ran successfully on my localhost. But the problem is how can i Get Uploaded file name for save image path it into my database?
Code -
<?php
header('Content-Type: text/plain; charset=utf-8');
try {
// Undefined | Multiple Files | $_FILES Corruption Attack
// If this request falls under any of them, treat it invalid.
if (
!isset($_FILES['upfile']['error']) ||
is_array($_FILES['upfile']['error'])
) {
throw new RuntimeException('Invalid parameters.');
}
// Check $_FILES['upfile']['error'] value.
switch ($_FILES['upfile']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('Exceeded filesize limit.');
default:
throw new RuntimeException('Unknown errors.');
}
// You should also check filesize here.
if ($_FILES['upfile']['size'] > 1000000) {
throw new RuntimeException('Exceeded filesize limit.');
}
// DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['upfile']['tmp_name']),
array(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
),
true
)) {
throw new RuntimeException('Invalid file format.');
}
// You should name it uniquely.
// DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
// On this example, obtain safe unique name from its binary data.
if (!move_uploaded_file(
$_FILES['upfile']['tmp_name'],
sprintf('./uploads/%s.%s',
sha1_file($_FILES['upfile']['tmp_name']),
$ext
)
)) {
throw new RuntimeException('Failed to move uploaded file.');
}
echo 'File is uploaded successfully.';
} catch (RuntimeException $e) {
echo $e->getMessage();
}
?>
I am confused how can i pass uploaded image name into variable and then store it into my database?
I have tried
$path = $_FILES['upfile']['tmp_name'];
echo $path;
but no luck. anyone here can help me out?
To get the information of uploaded file use $_FILES['upfile']['tmp_name'] for temp name and for real name $_FILES['upfile']['name']
$tmp_file = $_FILES['upfile']['tmp_name']; // store temporary file name
$real_file_name = $_FILES['upfile']['name']; // store the name of the file like upload.png
For example the uploaded file is ccd37b2ce541f407cabfc58be4e4af952fce7bde.jpg
$tmp_file = $_FILES['upfile']['tmp_name']; // this is a random generated temp image name like /var/www/html/phpyCWSRd.jpg
$real_file_name = $_FILES['upfile']['name']; // which is ccd37b2ce541f407cabfc58be4e4af952fce7bde.jpg
To move this file to uploads directory
$path = 'uploads/' . $real_file_name; // this will be uploads/ccd37b2ce541f407cabfc58be4e4af952fce7bde.jpg
if (!move_uploaded_file($_FILES['upfile']['tmp_name'], $path)) {
throw new RuntimeException('Failed to move uploaded file.');
}
I'm having a problem with php approving my file upload. I want the user to only upload .xml files. But it doesn't work.
Here is my html form:
<form action="upload2.php" method="post" enctype="multipart/form-data">
Wähle deine Sprachdatei aus:
<input type="file" class="form-control-file" name="upfile">
<br>
<input type="submit" class="btn btn-primary" value="Sprachdatei hochladen" name="submit">
</form>
and here is my php to control the file via MIME type:
<?php
header('Content-Type: text/plain; charset=utf-8');
try {
// Undefined | Multiple Files | $_FILES Corruption Attack
// If this request falls under any of them, treat it invalid.
if (
!isset($_FILES['upfile']['error']) ||
is_array($_FILES['upfile']['error'])
) {
throw new RuntimeException('Invalid parameters.');
}
// Check $_FILES['upfile']['error'] value.
switch ($_FILES['upfile']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('Exceeded filesize limit.');
default:
throw new RuntimeException('Unknown errors.');
}
// You should also check filesize here.
if ($_FILES['upfile']['size'] > 1000000) {
throw new RuntimeException('Exceeded filesize limit.');
}
// DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['upfile']['tmp_name']),
array(
'xml' => 'text/xml',
'txt' => 'text/plain',
),
true
)) {
throw new RuntimeException('Invalid file format.');
}
// You should name it uniquely.
// DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
// On this example, obtain safe unique name from its binary data.
if (!move_uploaded_file(
$_FILES['upfile']['tmp_name'],
sprintf('./uploads/%s.%s',
sha1_file($_FILES['upfile']['tmp_name']),
$ext
)
)) {
throw new RuntimeException('Failed to move uploaded file.');
}
echo 'File is uploaded successfully.';
} catch (RuntimeException $e) {
echo $e->getMessage();
}
?>
with simple jpg and png it works but not with xml.
I checked the MIME Type and it's still not working
I'm using XAMPP on Windows to run php
Thank you for your help.
It seems like $finfo->file() returns application/xml instead of text/xml for xml files.
Change your array with valid mime-types to this:
array(
'xml' => 'application/xml',
'txt' => 'text/plain',
),
Try with the below code. Extension of the file was getting properly on your code.
if (!move_uploaded_file(
$_FILES['upfile']['tmp_name'], 'uploads/'.basename($_FILES["upfile"]["name"]
)
))
Good morning, I have an issue with image uploading on a blog/cms I'm creating. Their is a post article page where user can upload a picture and then write his article. Basically, what I want to do is upload an image into uploads/ foler and then verify if it exists. If file does not exists, it will be uploaded and a reference will be inserted into the database Posts table after post is created and if it exists it wont be uploaded but a reference will still be inserted into the Posts table. The image insert function verifies picture size, but it also generates a new name for file afterwards in sha1 format. So here is the function that inserts the image:
function addImage() {
try {
// Undefined | Multiple Files | $_FILES Corruption Attack
// If this request falls under any of them, treat it invalid.
if (
!isset($_FILES['upfile']['error']) ||
is_array($_FILES['upfile']['error'])
) {
throw new RuntimeException('Invalid parameters.');
}
// Check $_FILES['upfile']['error'] value.
switch ($_FILES['upfile']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('Exceeded filesize limit.');
default:
throw new RuntimeException('Unknown errors.');
}
// You should also check filesize here.
if ($_FILES['upfile']['size'] > 1000000) {
throw new RuntimeException('Exceeded filesize limit.');
}
// DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['upfile']['tmp_name']), array(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
), true
)) {
throw new RuntimeException('Invalid file format.');
}
// You should name it uniquely.
// DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
// On this example, obtain safe unique name from its binary data.
if (!move_uploaded_file(
$_FILES['upfile']['tmp_name'], sprintf('./uploads/%s.%s', $sha2 = sha1_file($_FILES['upfile']['tmp_name']), $ext
)
)) {
throw new RuntimeException('Failed to move uploaded file.');
}
function addImage() {
try {
// Undefined | Multiple Files | $_FILES Corruption Attack
// If this request falls under any of them, treat it invalid.
if (
!isset($_FILES['upfile']['error']) ||
is_array($_FILES['upfile']['error'])
) {
throw new RuntimeException('Invalid parameters.');
}
// Check $_FILES['upfile']['error'] value.
switch ($_FILES['upfile']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('Exceeded filesize limit.');
default:
throw new RuntimeException('Unknown errors.');
}
// You should also check filesize here.
if ($_FILES['upfile']['size'] > 1000000) {
throw new RuntimeException('Exceeded filesize limit.');
}
// DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['upfile']['tmp_name']), array(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
), true
)) {
throw new RuntimeException('Invalid file format.');
}
if (file_exists($_SESSION['filefullname'])) {
echo "The file $filename exists";
$_SESSION['sha'] == "exists";
echo $_SESSION['sha'];
echo $_SESSION['filefullename'];
} else {
echo "The file $filename does not exist";
$_SESSION['sha'] == "notexists";
$_SESSION['filefullname'] = $filename;
echo $_SESSION['sha'];
echo $_SESSION['filefullename'];
}
// You should name it uniquely.
// DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
// On this example, obtain safe unique name from its binary data.
if (!move_uploaded_file(
$_FILES['upfile']['tmp_name'], sprintf('./uploads/%s.%s', $sha2 = sha1_file($_FILES['upfile']['tmp_name']), $ext
)
)) {
throw new RuntimeException('Failed to move uploaded file.');
}
echo 'File is uploaded successfully.';
} catch (RuntimeException $e) {
echo $e->getMessage();
}
$path = 'C:/wamp64/www/blog_management/uploads/' . $sha2 . ".jpg";
}
echo 'File is uploaded successfully.';
} catch (RuntimeException $e) {
echo $e->getMessage();
}
$path = 'C:/wamp64/www/blog_management/uploads/' . $sha2 . ".jpg";
}
So I'm wondering what would be the best way to proceed. Or is there a better easier way to do this? How are image uploads and management system usually created?
I am trying to restrict file upload to images only in the php but does not allow me to upload .psd format of images. how to allow .psd file upload in the php.
Right now I'm doing this way
<input accept="image/*" type="file" name="image" />
Never rely on client side verification's and do not trust $_FILES['upfile']['mime'] value!!
You need to check the following mime types for psd files, with some modification to fit your case:
'psd' => 'image/psd',
'psd' => 'image/x-photoshop',
'psd' => 'application/photoshop',
'psd' => 'zz-application/zz-winassoc-psd',
'psd' => 'application/psd'
From the php manual Handling file uploads :
<?php
header('Content-Type: text/plain; charset=utf-8');
try {
// Undefined | Multiple Files | $_FILES Corruption Attack
// If this request falls under any of them, treat it invalid.
if (
!isset($_FILES['image']['error']) ||
is_array($_FILES['image']['error'])
) {
throw new RuntimeException('Invalid parameters.');
}
// Check $_FILES['image']['error'] value.
switch ($_FILES['image']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('Exceeded filesize limit.');
default:
throw new RuntimeException('Unknown errors.');
}
// DO NOT TRUST $_FILES['image']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['image']['tmp_name']),
array(
'psd' => 'image/psd',
'psd' => 'image/x-photoshop',
'psd' => 'application/photoshop',
'psd' => 'zz-application/zz-winassoc-psd',
'psd' => 'application/psd'
),
true
)) {
throw new RuntimeException('Invalid file format.');
}
// You should name it uniquely.
// DO NOT USE $_FILES['image']['name'] WITHOUT ANY VALIDATION !!
// On this example, obtain safe unique name from its binary data.
if (!move_uploaded_file(
$_FILES['image']['tmp_name'],
sprintf('./uploads/%s.%s',
sha1_file($_FILES['image']['tmp_name']),
$ext
)
)) {
throw new RuntimeException('Failed to move uploaded file.');
}
echo 'File is uploaded successfully.';
} catch (RuntimeException $e) {
echo $e->getMessage();
}
?>
My question is quite simple. Should I be as thorough in validation when I am not going to let users upload an image, but rather create an image from the source?
I was thinking that I will only use $_FILES['file']['tmp_name'] to create a new jpeg or png image with PHP functions.
On php.net I found this suggestion with the most votes, should I do it like this or is it overkill?
try {
// Undefined | Multiple Files | $_FILES Corruption Attack
// If this request falls under any of them, treat it invalid.
if (
!isset($_FILES['upfile']['error']) ||
is_array($_FILES['upfile']['error'])
) {
throw new RuntimeException('Invalid parameters.');
}
// Check $_FILES['upfile']['error'] value.
switch ($_FILES['upfile']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('Exceeded filesize limit.');
default:
throw new RuntimeException('Unknown errors.');
}
// You should also check filesize here.
if ($_FILES['upfile']['size'] > 1000000) {
throw new RuntimeException('Exceeded filesize limit.');
}
// DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['upfile']['tmp_name']),
array(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
),
true
)) {
throw new RuntimeException('Invalid file format.');
}
// You should name it uniquely.
// DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
// On this example, obtain safe unique name from its binary data.
if (!move_uploaded_file(
$_FILES['upfile']['tmp_name'],
sprintf('./uploads/%s.%s',
sha1_file($_FILES['upfile']['tmp_name']),
$ext
)
)) {
throw new RuntimeException('Failed to move uploaded file.');
}
echo 'File is uploaded successfully.';
} catch (RuntimeException $e) {
echo $e->getMessage();
}
I think you should do this(You be as thorough in validation).Reasons
What if someone uploads a harmful php file?
What if someone uploads a file with large size?
Other Security Problems
.
So thorough in validation is needed, else it will be a danger for site.The time needed for validation is less.So security is most important.
The code you got on php.net validates file size, extension etc which is perfect and minimizes the risk.
Also creating image from source needs more resources.So letting users upload image with thorough in validation is best. :)