php script to save image with proper extension - php

I made some javascrit code base on image uploader to save an image to the server using php. This is my code :
var reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = function(event) {
var base64 = reader.result;
//console.log(base64);
$.ajax({
url: 'imageapi.php',
method: 'post',
data: {src :base64 },
type:"POST",
contentType:"application/x-www-form-urlencoded",
success: function(response) {
alert('Files uploaded successfully.');
}
});
}
The uploaded file should be : text, png or svg
I want to save the file with proper extension on server. Could anyone help to solve my problem ?
I've tried using this code to get extension but it didn't work
echo $mime_type = finfo_buffer($f, $_POST['src'], FILEINFO_MIME_TYPE);
Please help me, How to save image on server with proper extension

Following code gets filename at first and then extracts it's extension.
$path = $_FILES['src']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);

Related

Summernote upload image not showing in the editor after submitting to update

I have been working on a project, using Summernote. My project is like a blog system and I need to upload contents and images.
I have checked the other posts here and other places and managed to insert images to the file with ajax where I want to save the images. However, when I am editing, an image is there but once I click "update button" (submit button in a form), the images won't be there anymore.
I also check the inspect and resource says
Request URL: http://localhost/cms/admin/includes/images/42a0e188f5033bc65bf8d78622277c4e.JPG
This is the right path but after updating, I get a message like
Request URL: http://localhost/%22includes/images/42a0e188f5033bc65bf8d78622277c4e.JPG/%22
Also status code says
Status Code: 403 Forbidden
Here is my code
$('#summernote').summernote({
callbacks: {
onImageUpload: function(files) {
for(let i=0; i < files.length; i++) {
$.upload(files[i]);
}
}
},
height: 300,
});
$.upload = function (file) {
let out = new FormData();
out.append('file', file, file.name);
$.ajax({
method: 'POST',
url: './includes/editor-upload.php',
contentType: false,
cache: false,
processData: false,
data: out,
success: function(url) {
$('#summernote').summernote("insertImage", url, 'filename');
},
error: function (jqXHR, textStatus, errorThrown) {
console.error(textStatus + " " + errorThrown);
}
});
};
And this is my php code (editor-upload.php)
if ($_FILES['file']['name']) {
if (!$_FILES['file']['error']) {
$name = md5(rand(100, 200));
$ext = explode('.', $_FILES['file']['name']);
$filename = $name . '.' . $ext[1];
$destination = 'images/' . $filename; //change this directory
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo 'includes/images/' . $filename;//change this URL
}
else
{
echo $message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
Insert uploaded image to summernote editor
Summernote image upload
Summernote 0.8.12 Image Upload And Delete
I have tried these but nothing worked for me.
I have of course Summernote js and css file and am using Summernote 0.8.18
I am sure I am doing something wrong but I can't figure this out yet.
I am hoping somebody can help me out.
If the images folder is inside of the includes folder, change the following line:
$destination = 'images/' . $filename;
to
$destination = './includes/images/' . $filename;
Next, enter the full URL name and the full path to the image instead of
echo 'includes/images/' . $filename;
Also, the editor-upload.php file in your Ajax upload script may be causing the 403 errors. if the upload file is not in the same folder as your form and index.php page, it can prove problematic.
Try moving the file to the same folder as your form with the summer note editor, and enter the file in your Ajax script as
'editor-upload.php'

How can I create/save a file from BLOB in php?

What I did so far:
Okay, so i create a blob file (wav content) and it is stored under blob:http://localhost/cf6fefdc-352e-4cec-aef8-03af6d0d0ef6.
When i put this URL into my browser, it plays the file.
What i need to do
I want to convert the blob into an actual file, that i want to store on my webserver.
I'm handing the blob object over to a php file via AJAX
$.ajax ({
type: "POST",
url:"path/to/my/file.php",
data: {thefile : blob} ,
success: function(text) {
console.log(text);
},
error:function(){
console.log("Error")
}
});
That works. If I print_r the variable it returns [object Blob]
My PHP
<?php
$file = $_POST['thefile'];
print_r($file);
Can anyone tell me how I can convert and save the file to my server from there on?
In your file.php add this code
$filePath = 'uploads/' . $_POST['thefile'];
$tempName = $_FILES['thefile']['tmp_name'];
if (!move_uploaded_file($tempName, $filePath)) {
echo 'Problem saving file: '.$tempName;
die();
}
// success report
echo 'success';

Phonegap 3.7.0 e-mail file from input[type=file]

I'm having a problem with sending a file from an app I'm developing with phonegap.
I'm new to phonegap, so I might be trying to solve this in an entirely wrong way, so let me describe the the end goal first.
I'm developing a car rental app, I need to make a contact form, so users can leave an order to rent a car.
The form requires user to put in some basic information, like name and phone number, and also attach a photo or a scan of driver's license.
I was able to figure out the basic info part. I'm using $.ajax dataType: 'jsonp', to send the data to the server and then simply e-mail it to my client's address.
But I can find a way to send the file to the server.
I'm using an input[type=file] field to let the user choose what file to upload.
I've tried uploading file using FileTransfer, but apparently input[type=file] gives you some fake file path, that can't be directly used by FileTransfer.upload()
Problem is, I can't understand how can I get a proper file path for FileTransfer.upload function.
I've tried doing it another way, by reading the file using FileReader.
I tried reading the file and setting an image src to the result, but it doesn't work (it show broken image icon instead of an image, the same code works on PC).
I also tried to output it as text, that does output some data (so why doesn't it work for image src?).
Because I did manage to output the data read from the file as text I thought I will send that to the server and save it.
So here is how the code would look like:
On input change I read the file into a global variable
$(".file1").change(function(e){
var caster = e.target;
var files = caster.files;
if(FileReader && files && files.length) {
var fr = new FileReader();
fr.onloadend = function(e) {
//$(".image").attr("src",e.target.result);
window.file1base64 = e.target.result;
}
fr.readAsDataURL(files[0]);
}
});
Then, when user presses a button, I run FileTransfer.upload and then check every 0.1 seconds, whether the file upload is complete
function uploadSuccess(r) {
$(".output").append(" Success ");
window.fileStatus = true;
}
function uploadError(error) {
$(".output").append(" Error "+error.code+" ");
window.fileStatus = true;
window.fileError = error.code;
}
function uploadFile() {
$(".output").append(" uploadFile ");
file = $('.file1').val().split('\\').pop();
$(".output").append(" File-"+file+" ");
if(file){
$(".output").append(" fileExists ");
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = file;
options.mimeType = "image/jpeg";
options.chunkedMode = false;
options.headers = {
Connection: "close"
};
$(".output").append(" FileUploadOptions ");
window.fileStatus = false;
window.fileError = '';
//fileuri = $(".image").attr("src");
fileuri = window.file1base64;
$(".output").append(" fileuri ");
var ft = new FileTransfer();
ft.upload(fileuri, encodeURI("http://***.***/savefile.php"), uploadSuccess, uploadError, options);
$(".output").append(" upload ");
checkFile();
}
}
function checkFile() {
if(!window.fileStatus) {
$(".output").append(" check ");
setTimeout(checkFile, 100);
return;
}
}
After some checks, it prints out Error 3 and I can't figure out what that means or how to fix it.
Server side code is simply this:
Get the file and save it
$dir_name = dirname(__FILE__)."/uploadedimages/";
move_uploaded_file($_FILES["file"]["tmp_name"], $dir_name."test.txt");
But no file is created on the server.
use the FormData object to get the form data (including input file) and submit it this way:
var data = new FormData($('#yourFormID')[0]);
$.ajax({
url: serverURL,
data: data,
cache:false,
contentType: false,
processData: false,
type: 'POST',
error: function(jqXHR,textStatus,errorThrown){
},
success: function(data){
}
});
You should set the FILEURL in some variable and image in some html image element and then use it to transfer the image.
like this:
function onPgCameraSuccess(imageData) {
fileEntry.file(
function(fileObj) {
var previewImage= document.getElementById('SomeImageElement');
fileName=imageData.substr(imageData.lastIndexOf('/')+1);
fileURL=imageData;
previewImage.src =imageData;
$('#SomeTextBox').val(fileName);
});
}
function SubmitPhoto(){
var uOptions = new FileUploadOptions();
var ft = new FileTransfer();
uOptions .fileKey = "keyofyourfileonserver";
uOptions .fileName = fileName;
uOptions .mimeType = "image/jpeg";
uOptions .httpMethod = "POST";
uOptions .params = params;
ft.upload(fileURL,
urlofsvc,
photoSuccess,
photoFail,
uOptions,
true
);}

Upload Image using ajax (json)

I need to upload image using ajax. Elaborating my point:
I need to pass my image data to a PHP page and check the type, size, name and all other attributes of the file. If all attributes matches, then only I need to transfer the file. Problem here is passing of data should be done in JSON(AJAX) format only. One more important thing is that I don't have to convert it to base64.
If you can help me in this, You are most welcome.
Thanks in advance.
The idea in SO is to work on the OP current code. I mean, we are not here to make all the job, because it should have a price. Anyway, here is a workaround for your issue:
Convert your image to base64 using javascript. This useful method works like a charm:
// Code taken from MatthewCrumley (http://stackoverflow.com/a/934925/298479)
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to guess the
// original format, but be aware the using "image/jpg" will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
Then just pass the returned string as base64 through ajax:
$.ajax({
url: 'path/to/your/script.php',
type: 'post',
data: { paramName: imagedata } // the returned data from above js method,
/*...*/
});
And, in PHP side, just return the string to an image file:
// Code taken from Austin Brunkhorst (http://stackoverflow.com/a/15153931/3648578)
function base64_to_jpeg($base64_string, $output_file) {
$ifp = fopen($output_file, "wb");
$data = explode(',', $base64_string);
fwrite($ifp, base64_decode($data[1]));
fclose($ifp);
return $output_file;
}

Issue on Posting Image to a PHP File

I am trying to capture a highcharts chart and POST it to a PHP file
(result.php). I am able to capture image right now but I do not know how to POST captured image to another file. so far I have this code which is returning a PNG image
function postChart(chart) {
var obj = {},chart;
obj.svg = chart.getSVG();
obj.type = 'image/png';
obj.async = true;
exportUrl = 'http://export.highcharts.com/';
$.ajax({
type: "POST",
url: exportUrl,
data: obj,
cache:false,
async:true,
crossDomain:true,
success: function (data) {
// How to Send Image to result.php
},
error: function(data) {
}
});
}
and this result.php file as:
<?php
$content = $_POST['Not Sure What!'];
echo $content;
Now can you please let me know what can I put in
success: function (data) {
// How to Send Result to another Page
},
to post the image to result.php and how should I modify the result.php. Thanks
You can just use the highchart's exportChart API Like
function postChart(chart) {
chart.exportChart({
url : 'path/to/result.php',
type: 'image/png',
filename: 'my-chart'
});
}
Then from result.php you will be able to access the $_POST variable. which will contain following array, where $_POST['svg'] is the image in svg format.
array (
'filename' => 'my-chart',
'type' => 'image/png',
'width' => '0',
'scale' => '2',
'svg' => '',
)
You can then use the highchart's server side script to convert the image from svg to your desired format.
If you do not like to use java library for the conversion, you can also try this
Happy Coding!!
This works only if your php-script is somewhere on http://export.highcharts.com/
(Because you set the crossDomain property to true)
In your ajax method:
Change:
data: obj,
TO:
data: {
objName: obj,
}
Then in the result.php:
<?php
var_dump($_FILES['objName']);
// If you're interested, what else is inside $_FILES
var_dump($_FILES);
Not entirely sure what you're asking. This may be of some help though.
When working with files on upload use $_FILES. Its exactly like $_POST but for files.
Theres a selection of variables you can gather from the file using $_FILES.
<?
$tempname = $_FILES['file']['tmp_name'];
$filetype = $_FILES["file"]["type"];
$filesize = $_FILES['file']['size'];
?>
In the case above this references the file with a name of "file".

Categories