Get uploaded file name? - php

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/php‌​yCWSRd.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.');
}

Related

Image Upload and Management system PHP

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?

How to upload only .psd in php file upload

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();
}
?>

Validation process when uploading an image in PHP vs creating an image from uploaded image

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. :)

array merge error from object string

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 "--->";

PHP upload csv file - invalid format issue after upload

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.');
}

Categories