Give the result of canvas.toDataURL (JS) to $mail->addAttachment(); (PHP) - javascript

I'm developing a webapp where the user will be able to configure a pool by dragging the various icon on a blueprint (stairs, skimmer, light...).
Once the configuration is done, the user can click on a button to receive the blueprint by email.
I did the function that take the screenshot and it works well, i did also the PHP function that send the mail (made with PHPmailer) and it work too.
My problem is that I can't find a way to attach the result of my screenshot which is stored in the JS variable "url" and gave to the html in the id "linkImg" :
function getPNG(){
html2canvas(document.querySelector("#plan")).then(canvas => {
document.getElementById("box1").appendChild(canvas)
var url = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
const linkImg = document.getElementById("linkImg");
linkImg.href=url;
linkImg.download="plan.png";
});
}
Here the code of php part that i need to fill :
<?php
$mail->addAttachment();
?>
I tried to give as argument : '$(#linkImg)' but without surprise it does not work.
I thank you by advance for any help. Have a good dayy

The image is in the browser, but your PHP code is on your server, so you have to pass the image data from the browser to the server. The best way to do that is with fetch. Here's an example showing how to send canvas data using fetch. On the server side, you will need to decode the data URL:
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
and then you will be able to add it to your email message directly, without going via a file, using addStringAttachment():
$mail->addStringAttachment($data, 'image.png');

Related

Save Multiple Canvas Created Images to Server via AJAX with JavaScript

I am working on a form set for a client. In a nutshell:
The forms are filled out by my client’s customers by selecting different options on each form.
Each form can have multiple instances, depending on the customer.
At the end of the process, the customer can opt to either sign one or all the forms digitally or decline to sign them digitally and at the end of the process the forms are printed out and signed manually.
To accomplish this, I’ve created a signature plugin written in jQuery. Once the customer fills out the forms, they are presented each form separately. To sign the form digitally they simply tap (click) the signature block, a dialog with a canvas element appears, they sign the form and save it, the signature appears in the form, and they move on to the next form.
Here is the portion of the code that stores the completed signature and adds the image to the form:
$.sig = {
signatures: {},
}
function signatureSave() {
var canvas = document.getElementById("sigcanvas"),
dataURL = canvas.toDataURL("image/png");
document.getElementById($.sig.target).src = dataURL;
$.sig.signatures[$.sig.target].url = dataURL;
$.sig.signatures[$.sig.target].hasSignature = true;
};
The function is only called if the signature is saved, if there is no signature, the $.sig.signatures[$.sig.target].hasSignature remains false and the system skips the object.
This all works as intended, almost.
My problem lies in the process used to save the form information. If the customer does not sign any forms digitally the form information is simply saved and the forms are printed out, no need to save any signatures.
If the customer signs at least one form, though, the signatures must be sent to the server using the FormData() object.
I’ve used the FormData object in other projects for the client successfully, but only when the customer uploads one or more images to the browser using the input file element. It’s a pretty simple process because the resulting images have a img.file property that I send to the server.
Not so with a canvas object. All I get is the .src property, an any attempt to use anything from the resulting .png image that is created in the function above results in either a “cannot use a blob” or some other error.
Now I know if I have a single image, I can send it using AJAX with the following:
$.ajax({
type: "POST",
url: "script.php",
data: {
imgBase64: dataURL
}
})
Problem is that I am sending from one to x number of signatures.
Edit: I forgot to add this in. This is the function that is supposed to create the FormData object used to send the signatures to the server (and where my problem lies):
function getUploadData() {
var upl = new FormData();
$.each($.sig.signatures, function (e, u) {
if (u.hasSignature == true && u.url != null) {
var im = new Image();
im.src = u.url;
upl.append(u.target, im, u.target + '.png');
}
})
return upl;
}
I've tried all the tricks and nothing is working. The var im = new Image(); as well as the following line are just my latest ill fated attempt.
Picture perfect would be the ability to save the image information in the $.sig.signatures object so I can simply loop through any signatures that are signed, add them as elements of the FormData object, and then send the FormData object as the data for the AJAX call. As stated before, I use this method in other projects and works fine.
Does anyone know a way to do this?
Please note:
The server-side AJAX processor functions correctly.
The signature process works correctly (customer signs canvas, signature is displayed, signature information is stored).
All I need is how to send multiple images created using the canvas element in a FormData object to the server.
I know the answer is staring me right in the face, but I am just not getting it. Any hints or suggestions would be greatly appreciated!
Edit: Just a note. I've searched the entire afternoon for this and have found entries that either deal with sending multiple files using FormData and AJAX - but the files are uploaded to the browser (not created using Canvas), or single files sent to the server that are created using Canvas, but nothing about sending multiple files sent using FormData and AJAX that are created using Canvas. Oje!
As stated, the answer was staring me in the face, but I didn't see it because was looking behind the wrong door. FormData has nothing to do with it (Homer Dope Slap!).
Since I already have the data stored in $.sig.signature for each signature, I just need to send the information to the server as the data in the AJAX function. I updated my function above as shown:
function getUploadData() {
var upl = {};
$.each($.sig.signatures, function (e, u) {
if (u.hasSignature == true && u.url != null) {
upl[e] = u.url;
}
})
return upl;
}
Since the form information is sent as JSON I just add the signature info to the object that contains the form information, JSON.stringify it and send it on its way. This should work because the information retrieved above are strings.
Server side will look something like this:
$info = json_decode( $_POST['info'] );
// Various validation routines and checks
foreach( $info->signatures as $sig=>$data ):
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$img = base64_decode($data);
// Do some processing, file naming, database saving and other general dodads
$success = file_put_contents( $file, $img );
endforeach;
The above function is still concept, I am reworking some of the code but this should work.
Credit is given to this post for opening my eyes:
post sending base64 image with ajaxpost sending base64 image with ajax
So question answered and yeah, I deserve a dope slap, but all comes out right in the end.
CAVEAT: Works like a charm.

Send base64 image from meteor application

I have a meteor application and in this one I use cropper plugin to upload an image from the local computer of the user in the website and after send it to my DigitalOcean server. So the upload from the local computer works but when I try to send the image in my server, it doesn't work.
From cropper plugin, I retrieve a imgbase64 I want to send.
I search on many forums but I didn't find a good solution so I tried to do this :
In myapp.js I have :
$("#save").click(function() {
window.open($image.cropper("getDataURL"));
var dataURL = $image.cropper("getDataURL");
$.ajax({
type: "POST",
url: "script.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
// If you want the file to be visible in the browser
// - please modify the callback in javascript. All you
// need is to return the url to the file, you just saved
// and than put the image in your browser.
});
});
In myapp.html I have
<button class="btn btn-primary" id="save" type="submit">Save</button>
And I have a php script :
<?php
// requires php5
define('UPLOAD_DIR', '/home/images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
//header('Location: '.$_POST['return_url']);
?>
When I click on save button, I get "saved" in the console but I have nothing in the folder.
Do you have an idea why ?
I'm afraid it looks like you aren't using Meteor correctly.
Meteor is a JavaScript framework, so you can't create PHP files and try to initiate them within Meteor. All of your code has to be JavaScript.
This is a fundamental part of meteor development. I suggest you try the Meteor tutorial which should help you learn how to use Meteor.
The code you have posted will not achieve what you want to achieve, you will need to remove the PHP and rewrite it in JavaScript.

Javascript : Getting the dom image data source and save it to directory

I have an image data here from my console came from DOM displaying it using array
The console data look like this, I perfectly getting this data my problem is how to pass and get that image data into php
["data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAuSgpcjBs5Go81S/7+/x/MmaPEm
0:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAgAEl
1:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAY3U
2:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAgAElE
3:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAgAEl
Its a long string I did not just continue. I'm not sure if its an object, array or what. Is this possible to pass that value into PHP and then save the image into folder?
var image = [];
$('.dz-image img').each(function(){
image.push($(this).attr('src'));
});
console.log(image);
in general, you're looking at a Data URI - see https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs for more info.
in this particular case, you seem to be looking at a base64 encoded PNG file - if you want to upload the PNG to a PHP script on the server, you actually have a TON of options around what happens where (and in what order), but one possible approach is to a) always assume you're dealing w/ base64 encoded PNGs (if you know that not to be true, then you'll have to handle the first two parts of the data URI), b) upload data ($.post() the stuff after the comma) to PHP, c) base64 decode the data on the PHP side
Pass the value into PHP from javascript, consider to use ajax? In my experience, the http-post can transfer Array to PHP directly, like this:
var image = [];
$('.dz-image img').each(function(){
image.push($(this).attr('src'));
});
//console.log(image);
//here, I use jQuery, but you can use any way of ohter javascript framework
$.ajax({
type:'post',
tranditional:true,
url:'saveImage.php',
data:{"iamge":image},
success:function(data){
console.log(image)
}
})
In the php side, if you need to save image address into database, just do it like insert data to database. If you want to save the image into folder, do like this: saveImage.php
<?php
$images = $_POST['image'];
//here, you can code var_dump($image) to console the data you get
foreach($images as $key=>$image){
$image = base64_decode(str_replace('data:image/png:base64,','', $image));
file_put_contents($key.'.jpg', $image);
}
now, have a try?^-^

Uploading image from webcam to server

made a websitem, or trying to, where you can take a picture with your webcam and then upload it to the server, but ive found some inspiration in a guy that uses PHP and i wanna avoid it as much as posible. so what i have now in my .html for uploading is the picture is:
// Upload image to sever
document.getElementById("upload").addEventListener("click", function(){
var dataUrl = canvas.toDataURL("images/", 0.85);
$("#uploading").show();
$.ajax({
type: "POST",
url: "html5-webcam-save.php",
data: {
imgBase64: dataUrl,
//user: "Joe"
}
and then the reference(html5-webcam-save.php):
<?php
$rawData = $_POST['imgBase64'];
$filteredData = explode(',', $rawData);
$unencoded = base64_decode($filteredData[1]);
$datime = date("Y-m-d-H.i.s", time() ) ; # - 3600*7
//$userid = $_POST['userid'] ;
// name & save the image file
$fp = fopen('images/'.$datime.'-'.$userid.'.jpg', 'w');
fwrite($fp, $unencoded);
fclose($fp);
so my question, anyone now how to upload it to the server or just the "images" folder in the root of the site, without the need for PHP.
to be honest, the reason i dont want the PHP is because i simply cant get it to work properly on the server side, and iam lost when it comes to php. So can this be done with for instance C#/Javascript?
"..without the need for PHP"
You can't. You need a server side language to receive the data from raw http, convert it back from base64 text to image and then write it to disc. It could be PHP, c#, nodejs javascript, but there will always be a server side controller handling all this. You can't access server file system from client javascript for obvious security reasons.

PHP script to download text from site, convert and store it locally

How can I store text from a site to a local file?
So basically the script needs to do the following:
go to this site (fake site)
http://website/webtv/secure?url=http://streamserver.net/channel/channel.m3u8**&TIMESTAMP**
where TIMESTAMP can be a timestamp to make it unique.
the site will respond with:
{
"url":"http://streamserver.net/channel/channel.m3u8?st=8frnWMzvuN209i-JaQ1iXA\u0026e=1451001462",
"alternateUrl":"",
"Ip":"IPADRESS"
}
Grab the url and convert the text as follows:
http://streamserver.net/channel/channel.m3u8?st=8frnWMzvuN209i-JaQ1iXA\u0026e=1451001462
must be:
http://streamserver.net/channel/channel.m3u8?st=8frnWMzvuN209i-JaQ1iXA&e=1451001462
so \u0026e is replaced by &
and store this text in a local m3u8 file.
I am looking for a script either php or any other code is welcome which can perform this. Any help is appreciated.
I tried a small script just to show the contents but then I get the error:
Failed to open stream: HTTP request Failed!
It seems that php tries to open it as a stream instead of a website. It should see it as a site because only then the response is sent.
<?php
$url = 'http://website/webtv/secure?url=http://streamserver.net/channel/channel.m3u8&1';
$output = file_get_contents($url);
echo $output;
?>
This is not a tutorial website, so I am not going to provide you more details. You can try the following code:
<?php
$json_url = "http://linktoyour.site"; //change the url to your needs
$data = file_get_contents($json_url); //Get the content from url
$json = json_decode($data, true); //Decodes string to JSON Object
$data_to_save=$json["url"]; //Change url to whatever key you want value of
$file = 'm3u8.txt'; //Change File name to your desire
file_put_contents($file, $data_to_save); //Writes to File
?>
I think there is issue with your PHP configuration.
It like as allow_url_fopen is denied.
See more http://php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen

Categories

Resources