PHP base64_decode() .toDataURL() - javascript

I have an encoded string created from the Javascript function .toDataUrl(). Every time I try to convert this to binary with PHP base64_decode() it truncates the binary. I have already tried various items such as the following:
//First Attempt
$encoded = str_replace('data:image/png;base64,', '', $sig);
$decodedstring = base64_decode(str_replace(array(' ', '_'), array('+', '/'), $encoded));
$decodedstring = base64_decode(chunk_split($encoded));
//2nd attempt
$encoded = str_replace([' ','data:image/png;base64,'], ['+',''], $sig);
$decodedstring = "";
for ($i=0; $i < ceil(strlen($encoded)/256); $i++)
$decodedstring = $decodedstring . base64_decode(substr($encoded,$i*256,256));
//Other attempt
$decodedstring = base64_decode( str_replace(['data:image/png;base64,', ' '], ['','+'], $sig) );
None of these produce the correct file. Also to note, that when I use the standard png base64 online decoders the image looks 100% correct so the issue seems to be happening in the conversion.
Would anyone have additional thoughts. I have spent a few days trying to research this with no luck.

This is a function I made to convert data sent via ajax to php. It has always worked flawlessly for me.
function prepare_image($string, $file_name) {
list($type, $string) = explode(';', $string);
list(, $string) = explode(',', $string);
$string = base64_decode($string);
return $string;
}

Related

parse into another array contain xml child node using php

currently, im having problem to parse xml node in array using condition where parse with <mo> as separator
this is my array(0)
Array([0] => <mi>x</mi><mo>+</mo><mn>2</mn><mo>=</mo><mn>3</mn>);
i want to parse like this
Array[0] => <mi>x</mi>
Array[1] =><mo>+</mo><mn>2</mn>
Array[2]=><mo>=</mo><mn>3</mn>
this is my coding
<?
$result(0)="<mi>x</mi><mo>+</mo><mn>2</mn><mo>=</mo><mn>3</mn>";
$result1= new simplexml_load_string($result);
$arr_result=[];
foreach($result1 as $key => $value){
$exp_key = explode('<', $key);
if($key[0] == 'mo'){
$arr_result[] = $value;
}
print_r($arr_result);
}
if(isset($arr_result)){
print_r($arr_result);
}
?>
thanks in advance !
The approach with XML seems excessive since what you really want is to pull out substrings of a string based on a delimiter.
Here is a working example. It works by finding the position of <mo> and cutting off that section, then searching for the next <mo> in the remain string.
<?php
$result(0)="<mi>x</mi><mo>+</mo><mn>2</mn><mo>=</mo><mn>3</mn>";
$res = $result(0);
$arr_result=[];
while($pos = strpos($res, "<mo>", 1)) {
$arr_result[] = substr($res, 0, $pos); // grab first match
$res = substr($res, $pos); // grab the remaining string
}
$arr_result[] = $res; // add last chunk of string
print_r($arr_result);
?>
Your code above has several issues.
First:
$result1= new simplexml_load_string($result); // simplexml_load_string() is a function not a class
Second:
$key and $value do not contain the '<' and '>' so, this part:
$exp_key = explode('<', $key); will never do anything and isn't needed.
Third:
If your code did work it would only return array('+', '=') because you are appending the data inside the mo element to the result array.

PHP & JS mcrypt decryption not working

I have the following code in Javascript to encrypt a string using a key:
des.js is this: http://www.tero.co.uk/des/code.php
<script src="/js/des.js"></script>
<script>
var key = '12345678';
var message = 'hello world';
var ciph = des(key, message, 1, 0);
ciph = stringToHex(ciph);
console.log("Encrypted Result: " + ciph);
</script>
Then I send it server side and attempt to decrypt with this PHP code:
$key = '12345678';
$hexa = '0x28dba02eb5f6dd476042daebfa59687a'; /This is the output from Javascript
$string = '';
for ($i=0; $i < strlen($hexa)-1; $i+=2) {
$string .= chr(hexdec($hexa[$i].$hexa[$i+1])); }
echo mcrypt_decrypt(MCRYPT_DES, $key, $string, MCRYPT_MODE_ECB);
Ive tried converting it to utf8, changing encoding, changing the hex decoding, etc, but it always comes out gibberish, sometimes as nonreadable characters, other times as readable but nonsense.
The way to decrypt the string is not working properly, try this:
$key = '12345678';
$hexa = '0x28dba02eb5f6dd476042daebfa59687a';
function hexToString ($h) {
$r = "";
for ($i= (substr($h, 0, 2)=="0x")?2:0; $i<strlen($h); $i+=2) {$r .= chr (base_convert (substr ($h, $i, 2), 16, 10));}
return $r;
}
echo mcrypt_decrypt(MCRYPT_DES, $key,hexToString('0x28dba02eb5f6dd476042daebfa59687a'), MCRYPT_MODE_ECB);
The output will be: hello world
This way work properly, however, you should search another method to encrypt your data, in your script the key (12345678) and your encrypt method is visible to everyone.
Data to be encrypted with a block cipher such as DES or AES must be an exact multiple of the block size in length. The solution is to add padding to the data to be encrypted, PKCS#5 padding is the usual padding for DES and probably the default for Javascript. Unfortunately mcrypt does not support PKCS#5 padding, only a non-standard zero padding.
Potential solutions:
Use a better encryption function than mcrypt, see the comment to the question.
Specify no padding in Javascript and manually add zero padding.
Specify no padding in mcrypt and remove the padding manually.
It is better tospecify all options and no to rely on defaults.

Get variable value by name from a String

This is for server side, regardless of client.
$data= file_get_contents('textfile.txt');
The textfile.txt contains
var obTemperature = "55";
var obIconCode = "01";
What can I enter so I can get echo obTemperature value of 55?
is there not a simple php interface to read var values by name?
please no over complicated /half answers /trolling,
You would be better off explaining what you want to do in general, but if you are tied to this file format and the format is consistent:
$data = str_replace('var ', '$', $data);
eval($data);
echo $obTemperature;
echo $obIconCode;
However, any other types of JavaScript code will cause a parse error.
Also, you can treat it as an ini file:
$data = str_replace('var ', '', parse_ini_string($data));
echo $data['obTemperature'];
Or just:
$data = parse_ini_string($data);
echo $data['var obTemperature'];
You can use a regular expression:
preg_match('/var obTemperature = "(\d+)";/', $data, $match);
$temperature = $match[1];
DEMO

Japanese/korean into MySQL table

i am trying to store some info in my db. One of the fields are Japanese names. I am getting a error:
Warning: #1366 Incorrect string value: '\xE3\x83\xA9\xE3\x83\x87...' for column 'japan-name' at row 1
So i cannot chnage the charset of my db. Can i use PHP or Javascript to convert Japanese/Korean to something else, and them when i go read it, reconvert to Japanese/Korean?
PHP offers the base64_encode() and base64_decode() functions. They are fast, and impose a storage penalty of about 33%. You can use the first to convert your utf-8 east Asian text to what looks like gibberish in ASCII before you store it in your table. The second will convert it back after you retrieve it.
Here's an example:
$jp = " 私はガラスを食べられます。それは私を傷つけません。";
$jpe = base64_encode ($jp);
$jpd = base64_decode ($jpe);
After you run these lines, the $jpe variable has the value
IOengeOBr+OCrOODqeOCueOCkumjn+OBueOCieOCjOOBvuOBmeOAguOBneOCjOOBr+engeOCkuWCt+OBpOOBkeOBvuOBm+OCk+OAgg==
That stores just fine in an ASCII or Latin-1 column.
utf-8 saves the unicode data in table... but other way is to encode and save and then decode and display
update:
searched on web and found answer at How do you Encrypt and Decrypt a PHP String?
define("ENCRYPTION_KEY", "!##$%^&*");
$string = "This is the original data string!";
echo $encrypted = encrypt($string, ENCRYPTION_KEY);
echo "<br />";
echo $decrypted = decrypt($encrypted, ENCRYPTION_KEY);
/**
* Returns an encrypted & utf8-encoded
*/
function encrypt($pure_string, $encryption_key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, $encryption_key, utf8_encode($pure_string), MCRYPT_MODE_ECB, $iv);
return $encrypted_string;
}
/**
* Returns decrypted original string
*/
function decrypt($encrypted_string, $encryption_key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypted_string = mcrypt_decrypt(MCRYPT_BLOWFISH, $encryption_key, $encrypted_string, MCRYPT_MODE_ECB, $iv);
return $decrypted_string;
}

PHP Get last five words from .txt-file using file_get_contents

I'm looking for a functioning way of reading the last, say, 5 words from a .txt file using file_get_contents while long-polling. I've tried to work on a solution using the commented code below, but it breaks the long-polling – which works fine when displaying the full contents of a .txt-file.
I looked at the offset parameter for file_get_contents as well, but I don't know how to do a good (or functioning) adaption of that in my code. I guess that'd involve first counting all the words in said .txt file (which in itself is dynamic) then taking that number of words minus 5 somehow? There's probably an easier solution than that, and if not how do I go about to work it out with an alternative solution?
get_data.php
$id = $_COOKIE["currentID"];
$filepath = 'stories/'.$id.'.txt';
if (file_exists($filepath)) {
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filepath);
while($currentmodif <= $lastmodif){
sleep(1);
clearstatcache();
$currentmodif = filemtime($filepath);
}
// I've tried:
// Attempt to getting the last five words of .txt file, does NOT work
$str = file_get_contents($filepath);
$words = explode(' ', $str);
$last = join(" ", array_slice($words, -5, 5));
$response = array();
/* $response['data'] = file_get_contents($filepath); */ //use if not attempting to get last 5 words
$response['data'] = $last; //part of "what I've tried"
$response['timestamp'] = $currentmodif;
echo json_encode($response);
}
else{
// if file doesn't exist
echo('nada data, son.');
}
?>
application.js (for context)
$(function(){
$.longpolling({
pollURL: './get_data.php',
successFunction: pollSuccess,
errorFunction: pollError
});
});
function pollSuccess(data, textStatus, jqXHR){
var json = eval('(' + data + ')');
$('#response').html(json['data']);
document.getElementById('notificationsound').play();
console.log('file updated');
}
function pollError(jqXHR, textStatus, errorThrown){
console.log('Long Polling Error: ' + textStatus);
}
Why not do:
$lastfive = explode(" ", trim(preg_replace("/^([\s\S]+)(( ([^ ]+)){5})$/m", "$2", $code)));
Also, you should never use eval when parsing code retrieved from a server. Try using JSON.parse(data) instead.

Categories