My problem: I want to INSERT a image into a MySQL table with BLOB. In the same project I has upload a file but just the link in a VARCHAR column, and it works. Now I tried with file_get_contents and fread and both of them returns empty string. What's wrong with my code? Or is something wrong with the configuration of php.ini? The code is:
$imgdata = NULL;
$imgext = NULL;
$file = $_FILES['foto'];
if (!in_array($file['type'], $con->ext)) {
exit('Archivo no permitido');
} else {
if ($file['error'] === FALSE) {
exit('Error ' . $file['error']);
} else {
$attachtmp = $file['tmp_name'];
$imgext = $file['type'];
if (file_exists($attachtmp)) {
if (is_uploaded_file($attachtmp)) {
$fp = fopen($attachtmp, 'r+b');
$imgdata = fread($fp, filesize($attachtmp));
fclose($fp);
//if (empty(file_get_contents($attachtmp))) {
//$imgdata = $con->real_escape_string(file_get_contents($attachtmp));
//}
} else {
exit('<h3>Error interno del servidor<h3>');
}
} else {
exit('<h3>Error error interno del servidor<h3>');
}
}
}
Check your results first:
// Check $_FILES['foto']['error'] value.
switch ($_FILES['foto']['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.');
}
taken from php manual
Related
I have a Multi Step form with 6 pages. Each page has 2-3 inputs. There are next and previous buttons on each page. Whenever user fills data in one of the page and submits, a php file is called through ajax call. Validation for all the steps are done in that same file. If all the inputs have correct data then next page is shown. All the steps are defined by their step no.
On the second last step there is a file input that takes an image. Sends it through ajax and stores in files. I have to store it in files somewhere to be able to show to the user.
Now on last step all the data has to be shown for last verification. Everything the user has entered is shown to him. Where he chooses to dismiss all the data or store it in the profile.
What if he does nothing and closes the tab. The Session variables will get destroyed but the image file he uploaded will be stuck in the files forever.
So, my question is how can i store that image in such a way so that whatever activity user does except (to dismiss or to accept), the image gets removed from the files.
A wild guess : can i store it in the sessions? Or cookies?
** Here Is The Code For Upload Verification **
/* Page 5 */
if($page == $page5)
{
if(isset($_FILES['uploadedVisitingCard']))
{
$image = new image;
$outImage;
try{
if(!list($width, $height, $type) = getimagesize($_FILES['uploadedVisitingCard']['tmp_name']))
{
throw new Exception("Either Uploaded File Is Not An Image or It An Image Type That Is Not Supported");
}
$image->type = $type;
$image->width = $width;
$image->height = $height;
}
catch(Exception $e)
{
$result['error'] = true;
$result['msg'] = $e->getMessage();
echo json_encode($result);
die();
}
if(!in_array($image->type, $allowedImageType))
{
$result['error'] = true;
$result['msg'] = "File Type Not Supported For Uploading! The File Must Be a PNG File or a JPG File";
echo json_encode($result);
die();
}
try{
if(!$image->size = filesize($_FILES['uploadedVisitingCard']['tmp_name']))
{
throw new Exception("Unable To Get The Size OF The Uploaded Image.");
}
}
catch(Exception $e){
$result['error'] = true;
$result['msg'] = $e->getMessage();
echo json_encode($result);
die();
}
if($image->size > 5242880)
{
$result['error'] = true;
$result['msg'] = "The Image Must Be Below 5MB";
echo json_encode($result);
die();
}
try{
switch ($image->type)
{
case IMAGETYPE_JPEG:
if(!$outImage = imagecreatefromjpeg($_FILES['uploadedVisitingCard']['tmp_name']))
{
throw new Exception("Cannot Reproduce The JPEG Image! Error Code: IMGDUPJPEG");
}
if(!$outImage = resize_image($outImage, $image, 640, 480))
{
throw new Exception("Cannot Reproduce The JPEG Image! Error Code: IMGDUPJPEGFUNC");
}
if(!imagejpeg($outImage, "main.jpg", 70))
{
throw new Exception("Cannot Save The File Into The Servers! Error Code: IMGSAVJPEG");
}
$result['error'] = true;
$result['msg'] = "Image Is JPEG";
echo json_encode($result);
die();
break;
case IMAGETYPE_PNG:
if(!$outImage = imagecreatefrompng($_FILES['uploadedVisitingCard']['tmp_name']))
{
throw new Exception("Cannot Reproduce The JPEG Image! Error Code: IMGDUPPNG");
}
if(!$outImage = resize_image($outImage, $image, 800, 600))
{
throw new Exception("Cannot Reproduce The JPEG Image! Error Code: IMGDUPPNGFUNC");
}
if(!imagepng($outImage, "main.png", 9))
{
throw new Exception("Cannot Save The File Into The Servers! Error Code: IMGSAVPNG");
}
$result['error'] = true;
$result['msg'] = "Image Is PNG";
echo json_encode($result);
die();
break;
}
}
catch(Exception $e)
{
$result['error'] = true;
$result['msg'] = $e->getMessage();
echo json_encode($result);
die();
}
$result['error'] = true;
$result['msg'] = "Width = ".$image->width." \nHeight = ".$image->height." \nImage Type = ".$image->type;
echo json_encode($result);
die();
}
else
{
$result['error'] = true;
$result['msg'] = "The Image Was NOt Uploaded";
echo json_encode($result);
die();
}
}
** Here Is The Function That Fetches Image Details, Resize Them And Renders Out Image In The File **
function resize_image($file, image $image, $dstWidth, $dstHeight)
{
$dst; $newwidth; $newheight;
$r = $image->width / $image->height;
if ($dstWidth/$dstHeight > $r) { $newwidth = $dstHeight*$r; $newheight = $dstHeight; }
else { $newheight = $dstWidth/$r; $newwidth = $dstWidth; }
switch($image->type)
{
case IMAGETYPE_JPEG:
try{
if(!$dst = imagecreatetruecolor($newwidth, $newheight)){
throw new Exception("Problem In Duplication Of The File! Error Code: IMGDUPJPEGFUNC1");
}
if(!imagecopyresampled($dst, $file, 0, 0, 0, 0, $newwidth, $newheight, $image->width, $image->height)){
throw new Exception("Problem In Duplication Of The File! Error Code: IMGDUPJPEGFUNC2");
}
}
catch(Execption $e)
{
$result['error'] = true;
$result['msg'] = $e->getMessage();
echo json_encode($result);
die();
}
break;
case IMAGETYPE_PNG:
try{
if(!$dst = imagecreatetruecolor($newwidth, $newheight)){
throw new Exception("Problem In Duplication Of The File! Error Code: IMGDUPPNGFUNC1");
}
if(!imagecopyresampled($dst, $file, 0, 0, 0, 0, $newwidth, $newheight, $image->width, $image->height)){
throw new Exception("Problem In Duplication Of The File! Error Code: IMGDUPPNGFUNC2");
}
}
catch(Execption $e)
{
$result['error'] = true;
$result['msg'] = $e->getMessage();
echo json_encode($result);
die();
}
break;
}
return $dst;
}
function process_image($file)
{
global $allowedImageType;
$image = new Image;
try{
if(!list($width, $height, $type) = getimagesize($file))
{
throw new Exception("Either Uploaded File Is Not An Image or It An Image Type That Is Not Supported");
}
$image->type = $type;
$image->width = $width;
$image->height = $height;
}
catch(Exception $e)
{
$result['error'] = true;
$result['msg'] = $e->getMessage();
echo json_encode($result);
die();
}
if(!in_array($image->type, $allowedImageType))
{
$result['error'] = true;
$result['msg'] = "File Type Not Supported For Uploading! The File Must Be a PNG File or a JPG File";
echo json_encode($result);
die();
}
try{
if(!$image->size = filesize($file))
{
throw new Exception("Unable To Get The Size OF The Uploaded Image.");
}
}
catch(Exception $e){
$result['error'] = true;
$result['msg'] = $e->getMessage();
echo json_encode($result);
die();
}
if($image->size > 5242880)
{
$result['error'] = true;
$result['msg'] = "The Images Must Be Below 5MB";
echo json_encode($result);
die();
}
return $image;
}
function render_image($image, $path)
{
try{
switch ($image->type)
{
case IMAGETYPE_JPEG:
if(!$outImage = imagecreatefromjpeg($_FILES['uploadedVisitingCard']['tmp_name']))
{
throw new Exception("Cannot Reproduce The JPEG Image! Error Code: IMGDUPJPEG");
}
if(!$outImage = resize_image($outImage, $image, 640, 480))
{
throw new Exception("Cannot Reproduce The JPEG Image! Error Code: IMGDUPJPEGFUNC");
}
if(!imagejpeg($outImage, "main.jpg", 70))
{
throw new Exception("Cannot Save The File Into The Servers! Error Code: IMGSAVJPEG");
}
$result['error'] = true;
$result['msg'] = "Image Is JPEG";
echo json_encode($result);
die();
break;
case IMAGETYPE_PNG:
if(!$outImage = imagecreatefrompng($_FILES['uploadedVisitingCard']['tmp_name']))
{
throw new Exception("Cannot Reproduce The JPEG Image! Error Code: IMGDUPPNG");
}
if(!$outImage = resize_image($outImage, $image, 800, 600))
{
throw new Exception("Cannot Reproduce The JPEG Image! Error Code: IMGDUPPNGFUNC");
}
if(!imagepng($outImage, "main.png", 9))
{
throw new Exception("Cannot Save The File Into The Servers! Error Code: IMGSAVPNG");
}
$result['error'] = true;
$result['msg'] = "Image Is PNG";
echo json_encode($result);
die();
break;
}
}
catch(Exception $e)
{
$result['error'] = true;
$result['msg'] = $e->getMessage();
echo json_encode($result);
die();
}
}
The easiest way is to create an actual file management system. Meaning, you have a database table somewhere in which you store information about the files. The actual files should be stored in a folder structure somewhere on disk, with randomly generated names. UUIDs are very useful for this purpose. In the database then you store that UUID/file path, and any additional information about the file you want; e.g. its original user-supplied name, when it was uploaded, by whom it was uploaded etc.
Having this information allows you to act on it. E.g., you can query for all files which have been uploaded more than 24 hours ago, but have not been used anywhere else after that, so which can be deleted. Or perhaps you set a temporary = true flag when you upload them, and at the end of your wizard you remove the temporary flag, and you delete all temporary files after 24 hours. This can all be done with a simple, regular cron job.
In other words: you don't treat the files any differently from any other uploaded files, you merely retain enough information about them somewhere that allows you to remove them later as necessary.
When I tried uploading to /non_public_html/ the support team from my hosting team said that:
. Unfortunately, I have some bad news. It seems that you will not be able to move that file through a script, because of shared hosting restrictions. In order to have "www-data" permissions you would need to have a VPS package, so you could get root permissions.
So I can't upload to outside of /public_html/ it seems.
However when I try to upload to public_html it still fails, this is my code:
$PICTURE_UPLOAD_DIR = '/public_html/my_uploaded/';
$PICTURE_MIMES = [
'jpg' => 'image/jpeg',
'png' => 'image/png'
];
$image = $_FILES['image'];
$imagepath = $image['tmp_name'];
// Undefined | Multiple Files | $_FILES Corruption Attack
// If this request falls under any of them, treat it invalid.
if (!isset($image['error']) || is_array($image['error'])) {
$ojson['error'] = 'Invalid parameters'; $finish();
}
// Check $image['error'] value.
switch ($image['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
$ojson['error'] = 'No file sent'; $finish();
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
$ojson['error'] = 'Exceeded filesize limit.'; $finish();
default:
$ojson['error'] = 'Unknown errors.'; $finish();
}
// You should also check filesize here.
$size = filesize($imagepath);
// $size = $image['size']; // dont trust $_FILES
if ($size > 1000000) {
$ojson['error'] = 'Exceeded filesize limit.'; $finish();
}
// DO NOT TRUST $_FILES['image']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($imagepath);
// if ($ext = array_search($mime, $PICTURE_MIMES) === false) { // this doesnt set $ext
if (false === $ext = array_search($mime, $PICTURE_MIMES)) {
$ojson['error'] = 'Invalid file format.'; $finish();
}
$ojson['$ext'] = $ext;
$ojson['$mime'] = $mime;
// generate random file name
while (true) {
$filename = generateRandomString().'.'.$ext;
$pathtarget = $PICTURE_UPLOAD_DIR.$filename;
if (!file_exists($pathtarget)) break;
}
$ojson['$pathtarget'] = $pathtarget;
$ojson['$imagepath'] = $imagepath;
// $getimg = getimagesize($imagepath);
if(is_uploaded_file($imagepath)){
$ojson['isuploaded'] = true;
} else {
$ojson['NOTUPLOADED'] = true;
}
if(move_uploaded_file($imagepath, $pathtarget)) {
$ojson['ok move'] = 'ok';
} else {
$ojson['failed move'] = error_get_last();
}
move_uploaded_file continually fails, and error_get_last() is always printing:
move_uploaded_file(): Unable to move '/tmp/php7G5KMy' to '/public_html/my_uploaded/Q9BEsUkDre.jpg'
isuploaded is always true. I am so confused, may you please help.
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?
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 "--->";
This is phonogap code for uploading captured audio...
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name; //audio comes here...path and name of file
var img64 = imgdata; // here comes image in base64 and will decode at php in server side
ft.upload(path,
"http://my.domain.com/upload.php",
function(result) {
console.log('Upload success: ' + result.responseCode);
console.log(result.bytesSent + ' bytes sent');
},
function(error) {
console.log('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}
I want to upload both image data in base 64 and audio file by using that Fileuploader and store in PHP to a url
In PHP
$img = $_POST['image'];
$img = str_replace(' ', '+', $img);
$data = base64_decode($img); // FOR AUDIO how do i GET ?
Why don't you use $_FILES instead of base64-encoded $_POST?
PHP Manual
Post Method Uploads : http://www.php.net/manual/en/features.file-upload.post-method.php
PhoneGap Reference
FileTransfer : http://docs.phonegap.com/en/2.7.0/cordova_file_file.md.html#FileTransfer
FileTransferOptions : http://docs.phonegap.com/en/2.7.0/cordova_file_file.md.html#FileUploadOptions
These statements seem to be very important:
fileKey
The name of the form element. If not set defaults tofile. (DOMString)
fileName
The file name you want the file to be saved as on the server. If not set defaults toimage.jpg. (DOMString)
Example:
<?php
$upload_key = 'file';
if (isset($_FILES[$upload_key])) {
try {
$error = $_FILES[$upload_key]['error'];
if (is_array($error))
throw new Exception('This script can\'t accept multiple files');
switch ($error) {
case UPLOAD_ERR_INI_SIZE:
throw new Exception('Exceeded upload_max_filesize');
case UPLOAD_ERR_FORM_SIZE:
throw new Exception('Exceeded MAX_FILE_SIZE');
case UPLOAD_ERR_PARTIAL:
throw new Exception('Incomplete file uploaded');
case UPLOAD_ERR_NO_FILE:
throw new Exception('No file uploaded');
case UPLOAD_ERR_NO_TMP_DIR:
throw new Exception('No tmp directory');
case UPLOAD_ERR_CANT_WRITE:
throw new Exception('Can\'t write data');
case UPLOAD_ERR_EXTENSION:
throw new Exception('Extension error');
}
$finfo = new finfo(FILEINFO_MIME);
$name = $_FILES[$upload_key]['name'];
$tmp_name = $_FILES[$upload_key]['tmp_name'];
$size = $_FILES[$upload_key]['size'];
if ($size > 1000000)
throw new Exception('Exceeded 1MB limit');
if (!is_uploaded_file($tmp_name))
throw new Exception('Not an uploaded file');
$type = $finfo->file($tmp_name);
if ($type === false)
throw new Exception('Failed to get MimeType');
if (substr($type, 'image/') !== 0);
throw new Exception('Only images available');
$new_name = dirname(__FILE__).'/upload/'.$name;
if (is_file($new_name))
throw new Exception("The file {$new_name} already exists");
if (!move_uploaded_file($tmp_name, $new_name))
throw new Exception('Failed to move uploaded file');
$msg = "File successfully uploaded as {$new_name}";
} catch (Exception $e) {
$msg = 'Error: '.$e->getMessage();
}
} else {
$msg = 'No file sent';
}
echo $msg;