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;
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 am having trouble detecting the file type of files when I try to upload them using jQuery ajax ,
Here is how I upload a file using jQuery:
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]); //my file input
//Header require for the framework I am using
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: window.location.origin+'/'+'dataset/create/'+project.pid,
data:formData,
processData:false,//needs to be false for else jQuery gives illegal invocation
contentType:false,
mimeType:"multipart/form-data",
success: function (data) {
uploadDataCallback(data);
},
error: function (data) {
console.error('Error:', data);
}
});
Here is how I handle I try to figure out the file type in php ,
// Check MIME Type .
$finfo = new finfo(FILEINFO_MIME_TYPE);
//var_dump($finfo->file($_FILES['file']['tmp_name'])); //THIS IS ALWAYS 'text/plain'
if (false === $ext = array_search(
$finfo->file($_FILES['file']['tmp_name']),
array(
'csv' => 'text/csv',
'json' => 'application/json',
'csv' =>'text/plain',
),
true
)) {
throw new Exception('Invalid file format.');
}
$finfo always gives 'text/plain' for any type of file i.e. csv ,json etc. I want to detect when user uploads a json file or a csv file so I can parse them appropriately
Here is the entire function for reference:
function create($pid){
$tmpName = $_FILES['file']['tmp_name'];
$file = file($tmpName);
//uploading a file
try {
// Undefined | Multiple Files | $_FILES Corruption Attack
// If this request falls under any of them, treat it invalid.
if(!isset($_FILES['file']) || !is_uploaded_file($_FILES['csv']['tmp_name'][0])){
throw new Exception('File missing');
}
if (
!isset($_FILES['file']['error']) ||
is_array($_FILES['file']['error'])
) {
throw new Exception('Invalid parameters.');
}
// Check $_FILES['file']['error'] value.
switch ($_FILES['file']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new Exception('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new Exception('Exceeded filesize limit.');
default:
throw new Exception('Unknown errors.');
}
//check filesize here.
if ($_FILES['file']['size'] > 1000000) {
throw new Exception('Exceeded filesize limit.');
}
///////////////THIS IS WHERE IS ALWAYS SAYS 'text/plain' EVEN IF IT IS A JSON FILE
// Check MIME Type .
$finfo = new finfo(FILEINFO_MIME_TYPE);
//var_dump($finfo->file($_FILES['file']['tmp_name'])); //this is always text/plain
if (false === $ext = array_search(
$finfo->file($_FILES['file']['tmp_name']),
array(
'csv' => 'text/csv',
'json' => 'application/json',
'csv' =>'text/plain',
),
true
)) {
throw new Exception('Invalid file format.');
}
// name it uniquely.
// obtain safe unique name from its binary data.
$path=sha1_file($_FILES['file']['tmp_name']);
//dev config
if (!move_uploaded_file(
$_FILES['file']['tmp_name'],
sprintf(base_path().'/public/devStorage/%s.%s',
$path,
$ext
)
)) {
throw new Exception('Failed to move uploaded file.');
}
if($ext=='csv'){
$csvAsArray = array_map('str_getcsv', $file);
//dd($csvAsArray);
$rows=count($csvAsArray);
//everything fine,file is uploaded succesfully
//save dataset
$dataset=new DataSet;
$dataset->name=$_FILES['csv']['name'];
$dataset->iduser=Auth::user()->iduser;
$dataset->pid=$pid;
$dataset->path=$path;
$dataset->type=$ext;
$dataset->rows=$rows;
$dataset->cols=count($csvAsArray[0]);
$dataset->save();
for($i=0;$i<count($csvAsArray[0]);$i++ ){
$datasetCol=new DataSetColumn;
$datasetCol->col_name=$csvAsArray[0][$i]; //first row is assume to be the header row
if(is_numeric($csvAsArray[1][$i])){ //second row is taken as value and its type is assumed for entire column
$datasetCol->col_type='Number';
}
else{
$datasetCol->col_type='String';
}
$datasetCol->iddata_sets=$dataset->iddata_sets;
$datasetCol->save();
}
return json_encode($dataset);
}
else if($ext=='json'){
dd('jsonff');
}
} catch (Exception $e) {
$message='Error:'.$e->getMessage();
return $message;
}
}
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 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
I have the following code for uploading the image in database.
<html>
<head><title>File Insert</title></head>
<body>
<h3>Please Choose a File and click Submit</h3>
<form enctype="multipart/form-data" action=
"<?php echo $_SERVER['server address']; ?>" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<input name="userfile" type="file" />
<input type="submit" value="Submit" />
</form>
<?php
// check if a file was submitted
if(!isset($_FILES['userfile']))
{
echo '<p>Please select a file</p>';
}
else
{
try {
$msg= upload(); //this will upload your image
echo $msg; //Message showing success or failure.
}
catch(Exception $e) {
echo $e->getMessage();
echo 'Sorry, could not upload file';
}
}
// the upload function
function upload() {
$host="your_hostname";
$user="your_databaseuser";
$pass="your_database_password";
$db="database_name_to_use";
$maxsize = 10000000; //set to approx 10 MB
//check associated error code
if($_FILES['userfile']['error']==UPLOAD_ERR_OK) {
//check whether file is uploaded with HTTP POST
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
//checks size of uploaded image on server side
if( $_FILES['userfile']['size'] < $maxsize) {
//checks whether uploaded file is of image type
if(strpos(mime_content_type($_FILES['userfile']['tmp_name']),"image")===0) {
// $finfo = finfo_open(FILEINFO_MIME_TYPE);
// if(strpos(finfo_file($finfo, $_FILES['userfile']['tmp_name']),"image")===0) {
// prepare the image for insertion
$imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));
// put the image in the db...
// database connection
mysql_connect($host, $user, $pass) OR DIE (mysql_error());
// select the db
mysql_select_db ($db) OR DIE ("Unable to select db".mysql_error());
// our sql query
$sql = "INSERT INTO test_image
(image, name)
VALUES
('{$imgData}', '{$_FILES['userfile']['name']}');";
// insert the image
mysql_query($sql) or die("Error in Query: " . mysql_error());
$msg='<p>Image successfully saved in database with id ='. mysql_insert_id().' </p>';
}
else
$msg="<p>Uploaded file is not an image.</p>";
}
else {
// if the file is not less than the maximum allowed, print an error
$msg='<div>File exceeds the Maximum File limit</div>
<div>Maximum File limit is '.$maxsize.' bytes</div>
<div>File '.$_FILES['userfile']['name'].' is '.$_FILES['userfile']['size'].
' bytes</div><hr />';
}
}
else
$msg="File not uploaded successfully.";
}
else {
$msg= file_upload_error_message($_FILES['userfile']['error']);
}
return $msg;
}
// Function to return error message based on error code
function file_upload_error_message($error_code) {
switch ($error_code) {
case UPLOAD_ERR_INI_SIZE:
return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
case UPLOAD_ERR_FORM_SIZE:
return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
case UPLOAD_ERR_PARTIAL:
return 'The uploaded file was only partially uploaded';
case UPLOAD_ERR_NO_FILE:
return 'No file was uploaded';
case UPLOAD_ERR_NO_TMP_DIR:
return 'Missing a temporary folder';
case UPLOAD_ERR_CANT_WRITE:
return 'Failed to write file to disk';
case UPLOAD_ERR_EXTENSION:
return 'File upload stopped by extension';
default:
return 'Unknown upload error';
}
}
?>
</body>
</html>
My problem is that this code is saving the full size of image.I want to resize the image before uploading to the database.How can i do that???
First you have to create bitmap from file by imagecreatefromjpeg($string path to file), than empty bitmap by ImageCreateTrueColor($tmbWs,$tmbHs);, after this use ImageCopyResampled()
In modern browsers you can use the File API, and html5 canvas.
var file = YOUR_FILE,
fileType = file.type,
reader = new FileReader();
reader.onloadend = function() {
var image = new Image();
image.src = reader.result;
image.onload = function() {
imageWidth = image.width,
imageHeight = image.height;
//calculate new width and height however you want
// var newWidth, newHeight;
// ...
var canvas = document.createElement('canvas');
canvas.width = newWidth;
canvas.height = newHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, newWidth, newHeight);
// get the resized file
var finalFile = canvas.toDataURL(fileType);
}
}
reader.readAsDataURL(file);