array_merge error here ?
the result of e->gerMessage() is string which i put in an array then merge it , but i got error that it is not an array !
i tried var_dump and print_r and i did not notice any change
Here is a code
if(isset($_POST['submit'])) {
var_dump($_FILES);
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) {
$errors_array = array("error"=>"oh dear");
$errors["errors"] = $e->getMessage();
$moh = array_merge($errors_array , $errors) ;
echo "--->";
}
like the error says, $e->getMessage(); is not an array, it's a string, just add it...
$errors_array = array("error"=>"oh dear");
$errors_array["error_message"] = $e->getMessage();
$moh = array_merge($errors_array , $errors) ;
echo "--->";
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.');
}
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?
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. :)
I'm having an issue with this snippet where I try to validate a file that I'm trying to upload. The code come from this page, but it keeps throwing Invalid file format. exception when I'm checking the mime types. I need to upload only PDF files. Every PDF file I tried, failed.
What could be the issue here?
private function File($f) { // example from http://php.net/manual/en/features.file-upload.php
try {
if(!isset($f['file']['error']) || is_array($f['file']['error'])) {
throw new RuntimeException('Invalid parameters.');
}
switch ($f['file']['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.');
}
if($f['file']['size'] > 10000000) {
throw new RuntimeException('Exceeded filesize limit.');
}
$finfo = new finfo(FILEINFO_MIME_TYPE);
$extentions = array(
'pdf' => 'application/pdf',
'pdf' => 'x-pdf',
'pdf' => 'application/vnd.cups-pdf',
'pdf' => 'application/vnd.sealedmedia.softseal-pdf'
);
$ext = array_search($finfo->file($f['file']['tmp_name']), $extentions);
if(false === $ext) {
throw new RuntimeException('Invalid file format.');
}
if(!move_uploaded_file($f['file']['tmp_name'], sprintf('./uploads/%s.%s', sha1_file($f['file']['tmp_name']), $ext))) {
throw new RuntimeException('Failed to move uploaded file.');
}
echo 'File is uploaded successfully.';
}
catch (RuntimeException $e) {
echo $e->getMessage();
}
}
You are overwriting your array keys in $extentions with new values instead of adding new key/value pairs.
The following code isn't doing what you think:
$extentions = array(
'pdf' => 'application/pdf',
'pdf' => 'x-pdf',
'pdf' => 'application/vnd.cups-pdf',
'pdf' => 'application/vnd.sealedmedia.softseal-pdf'
);
A var_dump($extentions); will produce:
array(1) {
["pdf"]=>
string(40) "application/vnd.sealedmedia.softseal-pdf"
}
You need to add the additional MIME types instead of writing over them.
One problem is this: I believe your keys and values are swapped. In the following, there will be an array called $extensions with one key pdf associated with one value application/vnd.sealedmedia.softseal-pdf
$extentions = array(
'pdf' => 'application/pdf',
'pdf' => 'x-pdf',
'pdf' => 'application/vnd.cups-pdf',
'pdf' => 'application/vnd.sealedmedia.softseal-pdf'
);
My suspicion is that you are actually trying to do this:
$extentions = array(
'application/pdf' => 'pdf',
'x-pdf' => 'pdf',
'application/vnd.cups-pdf' => 'pdf',
'application/vnd.sealedmedia.softseal-pdf' => 'pdf'
);
$ext = #$extensions[$finfo->file($f['file']['tmp_name'])];
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.');
}