How to create an Image object with a base-64 source? - javascript

I have a remote web page, on which I use CURL and DOMDocument to retrive the src attribute of an image.
I use the following code, mixing JS in a PHP echo
<?php
$toEcho = "";
$toEcho .= // some stuff here...
$toEcho.="
<script>
//I create the object
var img = new Image();
//I set the source with the PHP variable : I get an error because of unexpected token ":"
img.src = $imgsrc;
</script>"
echo $toEcho;
?>
I checked the source, it is valid, and displays properly in my browser(s).
Where could this come from ?

Set the source like this:
img.src = '$imgsrc';

Related

PHP writing file with wrong line endings

I have some javascript code that generates a file, which then needs to be saved server side for further processing by a Python script.
My javascript creates a string, and in that string I'm using '\n' to break the lines, then I feed that string into a PHP file for saving as a text file.
my issue is when I open the file in vi, it shows ^M at the end of each line, which confuses python. I've tried getting python to generate a substring of the line without the ^M at the end, but Python won't do that.
so my javascript string looks like this when I debug:
line1
line2
line3
but the saved file looks like this:
line1^M
line2^M
line3^M
this is my javascript:
for(var i = 0;i < existingList.length;i++){
console.log(existingList.options[i].value);
saveString += existingList.options[i].value + '\n';
}
saveToFile(saveString);
function saveToFile(saveString){
var data = new FormData();
data.append("data" , saveString);
var xhr = new XMLHttpRequest();
xhr.open( 'post', 'savefile.php', true );
xhr.send(data);
}
This is my PHP:
<?php
if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = "Cards.txt";
$file = fopen($fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}
?>
I've tried converting to UTF8, I've tried String.fromCharCode(13) instead of '\n' and I've tried removing the ^M in Python... any ideas?
SOLUTION:
In python I was using
lines = text_file.read().split('\r')
or:
lines = text_file.read().split('\n')
I found if you use splitlines, it automatically handles the line ending:
lines = text_file.read().splitlines()
use double quotes for new line "\n" instead of '\n'
Try to replace your line(s) of code:
saveString += existingList.options[i].value + '\n';
With:
saveString += existingList.options[i].value + "\n";
OR with:
saveString += existingList.options[i].value + "\r\n";
You can use "\n", "\r\n" only as using single quotes wont work..
You can do it by editing the file or the content with php before you use the file, replace the content you don't want with nothing and save the file using file_get_contents() and file_put_contents(), str_replace() this is not pyton but you might want to try to fix it with php as you can do it before you use the file..
There are multiple ways to do this, this is..
str_replace() example:
<?php
/** More information regarding file_get_contents() - http://php.net/manual/en/function.file-get-contents.php **/
$End_Of_Line = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/path/to/Cards.txt');
/** More information regarding str-replace() - http://php.net/manual/en/function.str-replace.php **/
$End_Of_Line = str_replace('^M', '', $End_Of_Line);
/** Or use $End_Of_Line = str_replace('^M', "\r\n", $End_Of_Line); if you need new lines.. **/
/** More information regarding file_put_contents() - http://php.net/manual/en/function.file-put-contents.php **/
file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/path/to/Cards.txt', $End_Of_Line);
?>
I hope this will bring you into the right direction
I tested jagb's solution, and neither of them seemed to work but it got me thinking about how python reads the file. I finally found the answer:
In python I was using
lines = text_file.read().split('\r')
or:
lines = text_file.read().split('\n')
I found if you use splitlines, it automatically handles the line ending:
lines = text_file.read().splitlines()

How to save div content (img) on server

I am developing a web application where users can crop images.Users must be able to email the URL so others can view the cropped image. This means every cropped image must be stored on the server so that the URL will never die. The portion of my HTML that contains the cropped image is:
<div class="contain" id="myDiv">
<img src="" id="croppedImage">
</div>
The cropping function works fine and it is written in JavaScript. I am using PHP to parse through the DOM, extract the image and save it on the server but it is not working. Any help will be greatly appreciated.
<?php
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$divContent = $xpath->query('//img[id="croppedImage"]');
$my_server_img = $divContent;
$img = imagecreatefromjpeg($my_server_img);
$path = 'images_saved/';
imagejpeg($img, $path);
?>
After reviewing your code and checking out the functions you are using I looked at this part: $xpath->query('//img[id="croppedImage"]'); and compared to http://php.net/manual/en/domxpath.query.php you can see that the function returns a DOMNodeList element (even if nothing is found it will return the object with no children.. You are then taking this object and passing it to imagecreatefromjpeg($filename) that accepts a string as $filename, not an object. Also your xpath selector is wrong, you need to prefix id with # like so: $xpath->query('//img[#id="croppedImage"]');
So here is some code that will grab an <img /> element off a page by it's id and then download the URL of the src attribute and save it. You will want to make sure that the src of the image you are downloading is a jpg file otherwise imagecreatefromjpeg() will fail. You could use CURL or another method to download images (so you can get png images as well) but that is out of the scope of this answer.
$dom = new DOMDocument();
$dom->loadHTML('
<html>
<img src="http://images.freepicturesweb.com/img1/18/02/13.jpg" id="croppedImage2"/>
<img src="http://images.freepicturesweb.com/img1/18/02/14.jpg" id="croppedImage3"/>
</html>
');
$xpath = new DOMXPath($dom);
$imageElements = $xpath->query('//img[#id="croppedImage2"]');
// make sure $imageElements isn't empty
if($imageElements->length) {
// grab first item in list (should only be one)
/** #var DOMElement $imageElement */
$imageElement = $imageElements->item(0);
// get the src attribute off the <img>
$src = $imageElement->getAttribute('src');
// download and create image resource based off $src
$img = imagecreatefromjpeg($src);
// save image with random name to current directory
$filename = __DIR__.'/'.base_convert(sha1(uniqid(mt_rand(), true)), 16, 36).'.jpg';
imagejpeg($img, $filename);
echo "File saved to: ".$filename;
}
Should also be noted that you were assigning a variable to a variable. Things can get messy quick by doing this. If you want a variable to be called something else just set the name when you initialize it instead of assigning it to another variable with the name you want (I'm guessing this is just something you left over after trying some code out, but still worth mentioning).

setInterval - load PHP with POST - return image

I'm trying to use setInterval() to reload an image from a given path. I have some similar code to reload a log file which is working fine:
var auto_refresh = setInterval(
function auto_refresh_log()
{
$('#log_output').load('refresh_log.php').fadeIn("slow");
}, 1000);
refresh_log.php:
<?php $file = "/var/www/html/mainLOG";
$contents = file($file);
$string = implode( $contents);
echo $string; ?>
Now, I want to do something similar only with 2 changes:
Instead of using a fixed path like in refresh_log.php, I want to pass the path from the JS function to the PHP file. How can I do that?
Instead of returning a string, I want to return an image, which is then used in my html document. How can I do that?
To be exact on what I want to do: I have an index.php on which a user can select a file path. After setting some further parameters, some calculations start in the background. The results are saved as TIFF-files which cannot be read by the browser. So I want to use a PHP script with imagemagick to convert them (which is working fine) and pass them back to the JS. Then, the image should be displayed on my HTML <img id="image_id" ... > and refreshed every couple of seconds just like the log file.
Thanks!
One way would be to change the src attribute of the img element.
The browser will download the resource when you change the the src of the img element. Use the jQuery attr to do this. You should append a timestamp parameter so the browser does not obtain a cached instance from the local browser cache.
function loadImg(src) {
// append a parameter of "_" to the url
$("#myimg").attr("src", src + "?_=" + Date.now());
}
setInterval(loadImg("path/to/img"), 1000);
On your PHP side you would need a script that servers the image up in your converted format from where ever you are storing it. An example of how to do that is here.
I've managed to come up with a solution using $.post instead of $.load. The function is called via:
setInterval(
function auto_refresh_img()
{
var img_path = document.getElementById("image_path").value;
$.post('refresh_img.php',
{path: img_path},
function(data) {
$('#my_div').html(data);}
);
}, 1000);
with refresh_img.php looking like this:
<?php $imagepath = $_REQUEST['path'];
if (file_exists($imagepath)) {
$img = new imagick($imagepath."[0]");
$img->setImageFormat('jpg');
$thumbnails0 = $img->getImageBlob();
echo "<img src='data:image/jpg;base64,".base64_encode($thumbnails0)."' id='reco_background' style='display:none' />";
}
else {
echo "Image does not exist.";
};
?>
The returned <img ... > may then be used for any purpose.

Passing variables in a URL of a php page to JavaScript and to another PHP

Based on the code in this link http://webaudiodemos.appspot.com/AudioRecorder/index.html, I am making changes to send the recorded audio file to server by passing a sessionId via URL. The php page is http://xxxxx/abc.php?sessionId=Sam. PHP versions: PHP 5.4 PHP 5.5.22. I am using the 2nd method from this link:How to pass variables and data from PHP to JavaScript?. The abc.php page has reference to a few JS codes as with the index.html from the link above. abc.php page process the URL values correctly with the following code:
<div id="bottom">
<?php
$faid = $_GET["sessionId"];
echo htmlspecialchars($faid); // tested working
?>
</div>
On the recorder.js JavaScript,I have a function that tries to pass the URL values to another PHP while uploading the audio file to server - The fname is not being passed on ... it seems .. can the xhr.send(blob) will still send the fname?
Recorder.setupDownload = function(blob){
var div = document.getElementById("bottom");
var fname = div.textContent;
var xhr = new XMLHttpRequest();
xhr.open('POST', "./uploads.php?" + fname, true);
xhr.onload = function(e) {};
// Listen to the upload progress.
var progressBar = document.querySelector('progress');
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
progressBar.value = (e.loaded / e.total) * 100;
progressBar.textContent = progressBar.value; // Fallback for unsupported browsers.
}
};
xhr.send(blob);
The uploads.php in the server has the following script to receive the value and to create an audio file - but it is not creating the audio file - however, if I fix the file name (eg: "filename123") it writes the audio file - so the issue is in passing the variable name - I am a newbie and I wonder what am I missing?:
<?php
ini_set("display_errors", true);
error_reporting(E_ALL);
if(isset($_GET['fileId']) && !empty($_GET['fileId'])){
$id = $_GET["fileId"];
}
$fp = fopen( $id, 'wb' ); // writes the audio file
fwrite( $fp, $GLOBALS['HTTP_RAW_POST_DATA'] );
fclose( $fp );
?>
Update: It is working!
You didn't give your value a name, so you're passing a value that will appear as DIFFERENT key in every page.
e.g. each of your users will have something like
http://example.com?foo
http://example.com?bar
leading to $_GET['foo'] and $_GET['bar'] in PHP. But since foo/bar are some randomish value representing your session ID, you have no idea what that value will be. So... give it a name:
http://example.com?key=foo
Now you just do $key = $_GET['key'] and can always access your session value, no matter what value it really as - it'll always be assigned to the key.

Save iframe content as text file

How do you save the content of an iframe as a text file? Currently i only know ways to save the content of the webpage itself, but not any child iframes. I'm thinking some javascript, PHP and/or HTML5.
Using PHP and Javascript you can do this easily
Javascript (JQuery)
var data = document.getelementbyid("idofiframe").html();
var url = 'write.php';
$.ajax({url: url,type:"POST",data: data});
PHP
//Log all Proxy Requests
$file = 'file.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
date_default_timezone_set('GMT');
$current .= date('Y-m-d H:i:s'). ",".file_get_contents('php://input')."\n";
// Write the contents back to the file
file_put_contents($file, $current);

Categories

Resources