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.
Related
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');
I would like to have a button that when clicked gets a file (in this case a dynamically generated PDF) from a (predefined) URL on the same domain, and sends it to a (php) backend to be saved.
I am guessing that the best way to do this is to somehow load the file returned by the URL into a javascript variable, base64 encode it and send that to the backend with an ajax POST. Then on the backend I would base64 decode it and save it as a regular file.
Is this the right approach, or is there a better way to do it?
If this is the right approach, the part I am not sure how to do is getting the file from the URL into a variable. Once it's there, I guess I can use btoa() to base64 encode it. The other thing I am not 100% sure about is whether that will be compatible with base64_decode() in PHP for when I decode it?
Update
You say, the URL is predefined, and you don't know how to get in into a javascript variable. I guess, the URL is defined in the backend (PHP). So you could simply set/inject it in the client side code (javascript) with PHP.
Don't post the URL back from the client to the server, as there seems to be no need for that, and the URL could easily be changed by the user (security issue)!!!
So, maybe a better way would be to keep the URL on the server side, and inject it in the client page using php, without posting it back to the server.
Original answer
This answer is only appropriate if the client generates the URL and you have a secure way to verify it, as every client side input has to be treated as potential harmful user input.
In my opinion this is the absolutely right approach. Yes, you should base64 encode your variable. You could put the base64 encoded string in a json object and post this json object via ajax, or post it as plain text in your post body. Make sure to verify this as a client input!
I see no reason why btoa()/base64_decode() should not work. Base64 is platform independent.
I figured it out. It's a mix of vanilla and jQuery because the vanilla is from this article and the project I am working in already has jQuery available for $.ajax to make the POST to the backend easier.
var oReq = new XMLHttpRequest();
var fileUrl = '[URL from PHP]';
oReq.open("GET", fileUrl, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
let arrayBuffer = oReq.response; // Note: not oReq.responseText
if (arrayBuffer) {
let binaryText;
let byteArray = new Uint8Array(arrayBuffer);
for (var i = 0; i < byteArray.byteLength; i++) {
binaryText+=String.fromCharCode( byteArray[ i ] );
}
$.ajax({
type: "POST",
url: "/path/to/backend-upload",
data: {"fileData":btoa(binaryText)},
success: function(resultData){
alert("File Uploaded");
}
});
}
};
oReq.send(null);
and in the PHP backend:
file_put_contents("/path/to/destination", base64_decode($_POST['fileData']));
I'm trying to dynamically collect some free images from Google using the Web Speech API.
Here's the logic:
I capture the search keyword with the Web Speech API in JS.
I send it to the server (PHP) using an ajax call
Then I process the keyword and send back the results to JS.
Everything works fine if the keyword is just a single word like: Barack, but if I use Barack Obama there is a 500 Server Error and the ajax call fails.
JavaScript
$keyword = 'Barack Obama'; //the $Keyword is created from the result of the Web Speech API, but to make this clearer I just created it manually bc the problem still there anyway.
$.ajax({
type:'POST',
url: '../php/myfunctions.php',
data: {$keyword:$keyword},
dataType:"json",
}).done(function(response) {
console.log('yeah');
})
.fail(function(responseText) {
console.warn('error: ',responseText);
});
PHP
include_once($_SERVER['DOCUMENT_ROOT'].'/php/library/simple_html_dom.php');
$keyword = $_POST['$keyword'];
$keyword = 'Barack Obama'; //IF I manually create the $keyword all is fine but It's not the idea so this line is just to debug this issue.
$keyword = strtolower($keyword); //I tried with lowercases (barack obama).
$keyword = rawurlencode($keyword); //Then I tried a encoding workaround (barack%20obama).
$keyword = str_replace(' ','',$keyword); //Then I tried without white spaces(barackobama).
$url = 'https://www.google.com/search?q=' . $keyword . '&tbm=isch&source=lnt&tbs=sur:fc&sa=X&ved=0ahUKEwjQgMn87ajaAhUOtlkKHdgZB_8QpwUIHg&biw=1745&bih=872&dpr=1.1';
$html = file_get_html($url);
//From here I handle this data and I send it back in a json to JS
echo $url //if I echo the $url these are the outputs:
https://www.google.com/search?q=barack obama&tbm=isch&source=lnt&tbs=sur:fc&sa=X&ved=0ahUKEwjQgMn87ajaAhUOtlkKHdgZB_8QpwUIHg&biw=1745&bih=872&dpr=1.1
https://www.google.com/search?q=barack%20obama&tbm=isch&source=lnt&tbs=sur:fc&sa=X&ved=0ahUKEwjQgMn87ajaAhUOtlkKHdgZB_8QpwUIHg&biw=1745&bih=872&dpr=1.1
https://www.google.com/search?q=barackobama&tbm=isch&source=lnt&tbs=sur:fc&sa=X&ved=0ahUKEwjQgMn87ajaAhUOtlkKHdgZB_8QpwUIHg&biw=1745&bih=872&dpr=1.1
If I copy&paste these 3 URLs in the browser manually there is no problem and all the images appear, but if the $keyword created in JS has 2 words like New York there is a 500 error.
What could be the problem? Greetings.
Instead of
data: {$keyword: $keyword}
use
data: {keyword: encodeURIComponent($keyword)}
And drop the dataType: 'json' since you are definitely not echoing json there.
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?^-^
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