Passing from Javascript canvas image info AND some vars to PHP - php

First of all, sorry for my bad English, I'm Italian. I'm a bit new to programming, but for my office I need to create script that's a bit complex (at least for me). Before explaining the problem i'll explain what i'm doing.
I scripted a canvas that creates an image from data input, then i send the image data to php for the saving process. The problem is that i need to send also an value of 1 of the js vars (in the example value1). I can't figure out how to pass this information together with the raw image data.
The js code for the img drawing and saving. i need to pass the value1 to the save.php
button.addEventListener("click",function(){
//saving the values of the form
var value1 = document.getElementById("value1").value;
//text on the canvas
var value1X = (maxWidth-ctx.measureText(value1).width)/2+500;
//drawing the inputed text on the canvas
ctx.drawImage(img,0,0);
ctx.fillText(value1,value1X,maxHeight);
//getting the image url and sending it to save.php for the saving process
var imageURL = c.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST", 'saving.php', false);
ajax.setRequestHeader('Content-Type','application/upload');
ajax.send(imageURL);
}, false);
Here is the PHP file:
<?php
if (isset($GLOBALS[HTTP_RAW_POST_DATA])) {
$imageData = $GLOBALS[HTTP_RAW_POST_DATA];
$imageData = str_replace('data:image/png;base64,', '', $imageData);
$imageData = str_replace(' ', '+', $imageData);
$data = base64_decode($imageData);
//here i need the value1 value from the javascript
$dirname = "value1";
$filename = "header_top.png";
$newdir = mkdir($dirname);
$path = ("the/path/to".$dirname."/");
$fp = fopen($path.$filename, 'wb');
fwrite($fp, $data);
fclose($fp);
}
I hope I was able to explain myself so you can help me.
Thank you very much.
EDIT:
I think i get it, i mean for the moment it works but i don't know if it the right way doing it.
The fact is that i'm calling a php file so i simple added at the end of the url "?dir="+value1 and it works.
ajax.open("POST", 'saving.php?dir='+value1, false);
ajax.setRequestHeader('Content-Type','application/upload');
ajax.send(imageURL);
and in the php file i simply call $_GET['dir'] to get the value.
#hendrik thank you very much for your answer, unfortunaly i can't get it work with json, maybe becouse i didn't know it.
Anyway if someone knows a better way would be nice.

I think using JSON would be a good way to send the data to your PHP file. That way you can store multiple variables in an Object or Array.
// Store your data in an Object
var imageData = {
url: 'http://adsadsf.com',
name: 'foobar.gif',
width: 500,
height: 400,
directory: 'img/'
}
var ajax = new XMLHttpRequest();
ajax.open("POST", 'saving.php', false);
// Send the imageData object as JSON
ajax.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
ajax.send(JSON.stringify(imageData));
Unfortunately I don't know enough about PHP to explain exactly how to handle the received JSON data, but I guess you can use the json_decode method for that.
More about JSON: http://www.json.org/js.html

Related

How to call an image alt by an onclick event using php?

I want to open a new page and transfer data from an array. Using the name of the image seemed like the easiest way so that's what i want to do.
on the page i want to call it
function meghiv($img)
{
$be=$img.alt;
echo $be;
session_start();
$_SESSION['kod'] = $be;
}
for($j=0;$j<4;$j++)
{
echo ' <img src="'.$nevek[$i].'.png" class="card-img-top " alt="'.$i.'" onclick="meghiv(this)"> ';
$i++;
}
on the new page
<?php
session_start();
echo $_SESSION['kod'];
?>
I don't know if it answers your question but try using javascript to load the image name into your php file
let images = document.querySelectorAll('.card-img-top'); // returns NodeList
let img_list = [...images]; // converts NodeList to Array
img_list.forEach(div => {
div.addEventListener("click", function(e){
e.preventDefault()
let alt = div.getAttribute("alt")
window.open(`https://link.here/?alt=${alt}`, "_blank");
})
});
Then in your php file
$image_name = $_GET['alt'];

Flash sending 2 variables to php script, 1 of them being xml

So this is probably a simple question, but for some reason, I'm having problems with it. I have no ideia why, but I suspect the fact that sending a xml with full "< something >" tags may cause the php to behave wrongly.
So all I need is to send (from a swf as3 client) a filename and a xml. The php will write a xml file with the required filename.
Everything should be okay with the php side, because I tried it using " $_GET " variables, but whenever I try using the flash client, It just doesent work, and the php log says that "the filename variable can't be empty". Whenever I try some static filename (not using GET or POST), it works.
Sooo... Can someone help me out with this one?
Thanks.
EDIT: Code added.
var xmlURLReq:URLRequest = new URLRequest("www.url.com");
var test:URLVariables = new URLVariables;
test.filename = "01.xml";
test.xmldata = xmltosave;
xmlURLReq.data = teste;
xmlURLReq.contentType = "text/xml";
xmlURLReq.method = URLRequestMethod.POST;
var xmlSendLoad:URLLoader = new URLLoader();
xmlSendLoad.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
xmlSendLoad.addEventListener(IOErrorEvent.IO_ERROR, onIOError, false, 0, true);
xmlSendLoad.load(xmlURLReq);
var alertBox:alertBoxClass = new alertBoxClass();
alertBox.x = 0;
alertBox.y = 200;
function onComplete(evt:Event):void
{
try
{
var xmlResponse = new XML(evt.target.data);
alertBox.alertText.text = "Inserção de dados bem sucedida!";
addChild(alertBox);
removeEventListener(Event.COMPLETE, onComplete);
removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
writeXML()
}
}
I also tried Object and LoadVars classes instead of URLVariables, no luck so far.
EDIT: Might as well add the php code as well.
<?php
$filename = "http://url.com/".$_POST["filename"];
$xml = $_POST["xmldata"];
$file = fopen($filename , "wb");
fwrite($file, $xml);
fclose($file);
?>
I see one possible problem in your code;
You are setting the data to a URLVariables instance, but the contentType to "text/xml". It should be "application/x-www-form-urlencoded" when using URLVariables.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLRequest.html#contentType
Hope that solves it!

Script to draw image

I am looking for a PHP script that will allow me to draw an image with my mouse and save it as an image. If you know of any please help.
In case you do feel like reinventing a few wheels :-)
Make a Javascript snippet that lets you draw. This can of course be as advanced or simple as you wish, for example:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
pos = false;
ctx.strokeStyle = "red";
$(canvas).bind("mousedown", function(evt) {
pos = {x: evt.layerX, y: evt.layerY};
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
});
$(canvas).bind("mousemove", function(evt) {
if(!pos) return; // You may not want to do this on every mousemove.
pos = {x: evt.layerX, y: evt.layerY};
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
});
$(canvas).bind("mouseup", function(evt) {
if(!pos) return;
ctx.closePath();
pos = false;
});
Also add a button that sends the image data to your PHP script:
$('#btn').bind("click", function(evt) {
$.post('saveImage.php', {image : canvas.toDataURL('image/jpeg')});
});
In your saveImage.php script on the server, decode the data and write it to a file.
$imgData = $_POST["image"]; // Probably a good idea to sanitize the input!
$imgData = str_replace(" ", "+", $imgData);
$imgData = substr($imgData, strpos($imgData, ","));
$file = fopen('myImage.jpg', 'wb');
fwrite($file, base64_decode($imgData));
fclose($file);
Should do the trick :-) I'm using jQuery for the JS bits here, that's of course not necessary.
PHP is executed server-side, whereas interaction with the mouse is carried out client-side. You would need to use an in-browser technology like JavaScript or Flash to capture the mouse movements and generate bitmap data first.

PHP Detecting if source image url link leads to a "broken" image?

Suppose you have a thumbnail generator script that accepts source images in the form of a URL. Is there a way to detect if the source URL is "broken" - whether nonexistent or leads to an non-image file?
Just brute force using getimagesize() or another PHP GD function is not a solution, since spoofed stray URL's that might not be images at all (http://example.com/malicious.exe or the same file, but renamed as http://example.com/malicious.jpg) could be input - such cases could easily be detected by PHP before having to invoke GD. I'm looking for GD pre-sanitizing before having GD try its battalion at parsing the file.
as a first step, the following regular expression checks if the URL is an image extension:
preg_match('#(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)([^\s]+(\.(?i)(jpg|png|gif|bmp))$)#', $txt,$url);
use file_exists function in php, you can check urls with it.
See documentation below, shows how to check img... exactly what you need
FILE EXISTS - http://www.php.net/manual/en/function.file-exists.php#93572
URL EXISTS - http://www.php.net/manual/en/function.file-exists.php#85246
Here is alternative code for checking the url. If you will test in browser replace \n with <br/>
<?php
$urls = array('http://www.google.com/images/logos/ps_logo2.png', 'http://www.google.com/images/logos/ps_logo2_not_exists.png');
foreach($urls as $url){
echo "$url - ";
echo url_exists($url) ? "Exists" : 'Not Exists';
echo "\n\n";
}
function url_exists($url) {
$hdrs = #get_headers($url);
echo #$hdrs[1]."\n";
return is_array($hdrs) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',$hdrs[0]) : false;
}
?>
Output is as follows
http://www.google.com/images/logos/ps_logo2.png - Content-Type: image/png
Exists
http://www.google.com/images/logos/ps_logo2_not_exists.png - Content-Type: text/html; charset=UTF-8
Not Exists
I have used the following to detect attributes for remote images
$src='http://example.com/image.jpg';
list($width, $height, $type, $attr) = #getimagesize($src);
example (checking stackoverflows "Careers 2.0" image)
$src='http://sstatic.net/ads/img/careers2-ad-header-so.png';
list($width, $height, $type, $attr) = #getimagesize($src);
echo '<pre>';
echo $width.'<br>';
echo $height.'<br>';
echo $type.'<br>';
echo $attr.'<br>';
echo '</pre>';
If $height, $width etc is null the image is obvious not an image or the file does not exists. Using cURL is overkill and slower (even with CURLOPT_HEADER)
The only really reliable way is to request the image using file_get_contents(), and finding out its image type using getimagesize().
Only if getimagesize() returns a valid file type, can you rely that it is in fact a valid image.
This is quite resource heavy, though.
You could consider not doing any server-side checks at all, and adding an onerror JavaScript event to the finished image resource:
<img src="..." onerror="this.style.display = 'none'">
try for local files
<?php
if(file_exists($filename))
{
//do what you want
}
else
{
//give error that file does not exists
}
?>
for external domains
$headers = #get_headers($url);
if (preg_match("|200|", $headers[0])) {
// file exists
} else {
// file doesn't exist
}
Also you can use curl request for the same.
Fast Solution for broken or not found images link
i suggest you that don't use getimagesize() because it will 1st download image then it will check images size+if this will not image then it will throw exception so use below code
if(checkRemoteFile($imgurl))
{
//found url, its mean
echo "this is image";
}
function checkRemoteFile($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
// don't download content
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_exec($ch)!==FALSE)
{
return true;
}
else
{
return false;
}
}
Note:
this current code help you to identify broken or not found url image this will not help you to identify image type or headers
You could check the HTTP status code (it should be 200) and the Content-type header (image/png etc.) of the HTTP response before you put the actual image through the generator.
If these two preconditions are ok, after retrieving the image you can call getimagesize() on it and see if it breaks, what MIME type it returns etc.
did you try file_get_contents() method?
http://php.net/manual/en/function.file-get-contents.php
onerror Event
Execute a JavaScript if an error occurs when loading an image:
The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image).
Example:
<!DOCTYPE html>
<html>
<body>
<img src="image.gif" onerror="myFunction()">
<p>A function is triggered if an error occurs when loading the image. The function shows an alert box with a text.
In this example we refer to an image that does not exist, therefore the onerror event occurs.</p>
<script>
function myFunction() {
alert('The image could not be loaded.');
}
</script>
</body>
</html>
Although not detecting broken links, might be useful for someone else...
onerror=""
<img src="PATH" onerror="this.src='NEW PATH'" />

javascript return function's data as a file

I have a function in javascript called "dumpData" which I call from a button on an html page as **onlick="dumpData(dbControl);"* What it does is return an xml file of the settings (to an alert box right now). I want to return it to the user as a file download. Is there a way to create a button when click will open a file download box and ask the user to save or open it? (sorta of like right-clicking and save target as)...
Or can it be sent to a php file and use export();? Not sure how I would send a long string like that to php and have it simple send it back as a file download.
Dennis
I don't think you can do that with javascipt, at least not with a nice solution.
Here's how to force a download of a file in PHP:
$file = "myfile.xml";
header('Content-Type: application/xml');
header("Content-Disposition: attachment; filename='$file'");
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
Instead of using readfile to output your file, you could also directly display content using echo.
/EDIT: hell, someone was faster :).
EDITED:
just a proof of concept.. but you get the idea!
instead of
<a onlick="dumpData(dbControl); href="#">xml file</a>
you can have like this:
xml file
then like this:
// Assuming your js dumpData(dbControl); is doing the same thing,
// retrieve data from db!
$xml = mysql_query('SELECT * FROM xml WHERE id= $_GET['id'] ');
header("Content-type: text/xml");
echo $xml;
I eneded up going this route:
The HTML code
<script type="text/javascript">
$(document).ready(function() {
$("#save").click(function(e) { openDialog() } );
});
</script>
<button id="save" >Send for processing.</button>
The javascript code:
function openDialog() {
$("#addEditDialog").dialog("destroy");
$("#Name").val('');
$("#addEditDialog").dialog({
modal: true,
width: 600,
zIndex: 3999,
resizable: false,
buttons: {
"Done": function () {
var XMLname = $("#Name").val();
var XML = dumpXMLDocument(XMLname,geomInfo);
var filename = new Date().getTime();
$.get('sendTo.php?' + filename,{'XML':XML}, function() {
addListItem(XMLname, filename + ".XML");
});
$(this).dialog('close');
},
"Cancel": function () {
$("#Name").val('');
$(this).dialog('close');
//var XMLname = null;
}
}
});
}
PHP Code, I just decided to write the file out to a directory. Since I created the filename in the javascript and passed to PHP, I knew where it was and the filename, so I populated a side panel with a link to the file.
<?php
if(count($_GET)>0)
{
$keys = array_keys($_GET);
// first parameter is a timestamp so good enough for filename
$XMLFile = "./data/" . $keys[0] . ".kml";
echo $XMLFile;
$fh = fopen($XMLFile, 'w');
$XML = html_entity_decode($_GET["XML"]);
$XML = str_replace( '\"', '"', $XML );
fwrite($fh, $XML);
fclose($fh);
}
//echo "{'success':true}";
echo "XMLFile: ".$XMLFile;
?>
I don't know why, but when I send the XML to my php file it wrote out the contents withs escape charters on all qoutes and double quotes. So I had to do a str_replace to properly format the xml file. Anyone know why this happens?
POST the XML via a form to a php script that writes it back to the client with a Content-Disposition: attachment; filename=xxx.xml header.
<form name="xml_sender" action="i_return_what_i_was_posted.php" method="POST">
<input type="hidden" name="the_xml" value="" />
</form>
Then with js
function dumpData(arg) {
var parsedXML = ??? //whatever you do to get the xml
//assign it to the the_xml field of the form
document.forms["xml_sender"].the_xml.value = parsedXML;
//send it to the script
document.forms["xml_sender"].submit();
}
Can't remember if this loses the original window, if so, post to an iframe.

Categories