Trying to convert PHP assignment to Javascript - javascript

I am trying to convert a PHP function to javascript, but i cant read the following line of codes:
$sha_string .= "$key=$value$ipn_passphrase";
and
$sha_sign = strtoupper(hash("sha512", $sha_string));
Complete function:
function digistore_signature( $ipn_passphrase, $array)
{
unset($array[ 'sha_sign' ]);
$keys = array_keys($array);
sort($keys);
$sha_string = "";
foreach ($keys as $key)
{
$value = html_entity_decode( $array[ $key ] );
$is_empty = !isset($value) || $value === "" || $value === false;
if ($is_empty)
{
continue;
}
$sha_string .= "$key=$value$ipn_passphrase";
}
$sha_sign = strtoupper(hash("sha512", $sha_string));
return $sha_sign;
}
the $array is the body of a POST request.
the $passphrase is a string

.= in PHP is a simple concatenation. it is similar to the programming concept of +=. It's easy to understand with an example
<?php
$a = "hello";
$a .= " "; //now $a = "hello "
$a .= "world"; // now $a = "hello world"
"$key=$value$ipn_passphrase"; is called an in-place variable substitution in PHP. You can check the PHP Doc for more. You can simply consider it as the value $key, $values and $ipn_passphrase is replaced by the values of those variables accordingly and it forms a new string variable $sha_sign.
$sha_sign = strtoupper(hash("sha512", $sha_string)); is a simple statement where you pass the algorithm sha512 and $sha_string to the function hash() and store the result back in $sha_string variable.

Related

Iterate through JSON String in PHP?

it seems to be a really easy question, but I am a little bit struggling: I am receiving a JSON String via JavaScript. Now I would like to iterate through the element. The resulting string has this form: {"title":value,"title2":value}
How can I iterate through this JSON string without knowing the key and value? I would like to get this output:
title -> value
title2 -> value2
I tried it this way:
$json = file_get_contents('php://input');
$array = json_decode($json,true);
$response = "Test";
foreach($array as $key=>$val) {
$response = $response. "$key : $val";
}
echo json_encode($response);
It only returns "Test". If I change it to echo json_encode($array), it returns the mentioned JSON String.
You mention javascript and php in your question, so I'm going to answer for both. Here is JS, two different ways. I believe that foreach is being deemphasized in favor of the (of) construct now, but I don't work primarily in JS:
var json = '{"title": 12, "title2": "text"}';
var data = JSON.parse(json);
Object.keys(data).forEach(function(key) {
console.log(key + ' -> ' + data[key])
})
for(key of Object.keys(data)) {
console.log(key + ' -> ' + data[key]);
}
And for PHP:
You can parse the json string into an array using json_decode:
$json = '{"title": 12, "title2": "text"}';
$arr = json_decode($json, true);
foreach($arr as $key=>$val) {
echo "$key : $val";
}
true parses it into an array instead of a std object.
https://www.php.net/manual/en/function.json-decode.php
Because of response's format you must decode the decoded format in order to take the object as you want
$json = '{"title": 12, "title2": "text"}';
$encoded=json_encode($json);
$decoded=json_decode($encoded);
$ddecode=json_decode($decoded);
foreach($ddecode as $key=>$val) {
echo "$key -> $val";
}
Output :
title -> 12 title2 -> text

Is there a way to trim a string formula taken from JSON object and apply it using PHP variables? [duplicate]

I want to calculate math expression from a string. I have read that the solution to this is to use eval(). But when I try to run the following code:
<?php
$ma ="2+10";
$p = eval($ma);
print $p;
?>
It gives me the following error:
Parse error: syntax error, unexpected $end in
C:\xampp\htdocs\eclipseWorkspaceWebDev\MandatoryHandinSite\tester.php(4)
: eval()'d code on line 1
Does someone know the solution to this problem.
While I don't suggest using eval for this (it is not the solution), the problem is that eval expects complete lines of code, not just fragments.
$ma ="2+10";
$p = eval('return '.$ma.';');
print $p;
Should do what you want.
A better solution would be to write a tokenizer/parser for your math expression. Here's a very simple regex-based one to give you an example:
$ma = "2+10";
if(preg_match('/(\d+)(?:\s*)([\+\-\*\/])(?:\s*)(\d+)/', $ma, $matches) !== FALSE){
$operator = $matches[2];
switch($operator){
case '+':
$p = $matches[1] + $matches[3];
break;
case '-':
$p = $matches[1] - $matches[3];
break;
case '*':
$p = $matches[1] * $matches[3];
break;
case '/':
$p = $matches[1] / $matches[3];
break;
}
echo $p;
}
Take a look at this..
I use this in an accounting system where you can write math expressions in amount input fields..
Examples
$Cal = new Field_calculate();
$result = $Cal->calculate('5+7'); // 12
$result = $Cal->calculate('(5+9)*5'); // 70
$result = $Cal->calculate('(10.2+0.5*(2-0.4))*2+(2.1*4)'); // 30.4
Code
class Field_calculate {
const PATTERN = '/(?:\-?\d+(?:\.?\d+)?[\+\-\*\/])+\-?\d+(?:\.?\d+)?/';
const PARENTHESIS_DEPTH = 10;
public function calculate($input){
if(strpos($input, '+') != null || strpos($input, '-') != null || strpos($input, '/') != null || strpos($input, '*') != null){
// Remove white spaces and invalid math chars
$input = str_replace(',', '.', $input);
$input = preg_replace('[^0-9\.\+\-\*\/\(\)]', '', $input);
// Calculate each of the parenthesis from the top
$i = 0;
while(strpos($input, '(') || strpos($input, ')')){
$input = preg_replace_callback('/\(([^\(\)]+)\)/', 'self::callback', $input);
$i++;
if($i > self::PARENTHESIS_DEPTH){
break;
}
}
// Calculate the result
if(preg_match(self::PATTERN, $input, $match)){
return $this->compute($match[0]);
}
// To handle the special case of expressions surrounded by global parenthesis like "(1+1)"
if(is_numeric($input)){
return $input;
}
return 0;
}
return $input;
}
private function compute($input){
$compute = create_function('', 'return '.$input.';');
return 0 + $compute();
}
private function callback($input){
if(is_numeric($input[1])){
return $input[1];
}
elseif(preg_match(self::PATTERN, $input[1], $match)){
return $this->compute($match[0]);
}
return 0;
}
}
I recently created a PHP package that provides a math_eval helper function. It does exactly what you need, without the need to use the potentially unsafe eval function.
You just pass in the string version of the mathematical expression and it returns the result.
$two = math_eval('1 + 1');
$three = math_eval('5 - 2');
$ten = math_eval('2 * 5');
$four = math_eval('8 / 2');
You can also pass in variables, which will be substituted if needed.
$ten = math_eval('a + b', ['a' => 7, 'b' => 3]);
$fifteen = math_eval('x * y', ['x' => 3, 'y' => 5]);
Link: https://github.com/langleyfoxall/math_eval
Using eval function is very dangerous when you can't control the string argument.
Try Matex for safe Mathematical formulas calculation.
Solved!
<?php
function evalmath($equation)
{
$result = 0;
// sanitize imput
$equation = preg_replace("/[^a-z0-9+\-.*\/()%]/","",$equation);
// convert alphabet to $variabel
$equation = preg_replace("/([a-z])+/i", "\$$0", $equation);
// convert percentages to decimal
$equation = preg_replace("/([+-])([0-9]{1})(%)/","*(1\$1.0\$2)",$equation);
$equation = preg_replace("/([+-])([0-9]+)(%)/","*(1\$1.\$2)",$equation);
$equation = preg_replace("/([0-9]{1})(%)/",".0\$1",$equation);
$equation = preg_replace("/([0-9]+)(%)/",".\$1",$equation);
if ( $equation != "" ){
$result = #eval("return " . $equation . ";" );
}
if ($result == null) {
throw new Exception("Unable to calculate equation");
}
echo $result;
// return $equation;
}
$a = 2;
$b = 3;
$c = 5;
$f1 = "a*b+c";
$f1 = str_replace("a", $a, $f1);
$f1 = str_replace("b", $b, $f1);
$f1 = str_replace("c", $c, $f1);
evalmath($f1);
/*if ( $equation != "" ){
$result = #eval("return " . $equation . ";" );
}
if ($result == null) {
throw new Exception("Unable to calculate equation");
}
echo $result;*/
?>
This method has two major drawbacks:
Security, php script is being evaluated by the eval function. This is bad,
especially when the user wants to inject malicious code.
Complexity
I created this, check it out: Formula Interpreter
How does it work ?
First, create an instance of FormulaInterpreter with the formula and its parameters
$formulaInterpreter = new FormulaInterpreter("x + y", ["x" => 10, "y" => 20]);
Use the execute() method to interpret the formula. It will return the result:
echo $formulaInterpreter->execute();
in a single line
echo (new FormulaInterpreter("x + y", ["x" => 10, "y" => 20]))->execute();
Examples
# Formula: speed = distance / time
$speed = (new FormulaInterpreter("distance/time", ["distance" => 338, "time" => 5]))->execute() ;
echo $speed;
#Venezuela night overtime (ordinary_work_day in hours): (normal_salary * days_in_a_work_month)/ordinary_work_day
$parameters = ["normal_salary" => 21000, "days_in_a_work_month" => 30, "ordinary_work_day" => 8];
$venezuelaLOTTTArt118NightOvertime = (new FormulaInterpreter("(normal_salary/days_in_a_work_month)/ordinary_work_day", $parameters))->execute();
echo $venezuelaLOTTTArt118NightOvertime;
#cicle area
$cicleArea = (new FormulaInterpreter("3.1416*(radio*radio)", ["radio" => 10]))->execute();
echo $cicleArea;
About the formulas
It must contain at least two operands and an operator.
Operands' name could be in upper or lower case.
By now, math functions as sin, cos, pow… are not included. I'm working to include them.
If your formula is not valid, you will get an error message like: Error, your formula (single_variable) is not valid.
Parameters' values must be numeric.
You can improve it if you want to!
eval Evaluates the given code as PHP. Meaning that it will execute the given paremeter as a PHP piece of code.
To correct your code, use this :
$ma ="print (2+10);";
eval($ma);
Using eval function
protected function getStringArthmeticOperation($value, $deduct)
{
if($value > 0){
$operator = '-';
}else{
$operator = '+';
}
$mathStr = '$value $operator $deduct';
eval("\$mathStr = \"$mathStr\";");
$userAvailableUl = eval('return '.$mathStr.';');
return $userAvailableUl;
}
$this->getStringArthmeticOperation(3, 1); //2
Finding a sweetspot between the dangers of eval and the limitless calculation possibilities I suggest checking the input for only numbers, operators and brackets:
if (preg_match('/^[0-9\+\-\*\/\(\)\.]+$/', $mathString)) {
$value = eval('return
' . $mathString . ';');
} else {
throw new \Exception('Invalid calc() value: ' . $mathString);
}
It's still easy to use yet relatively save. And it can handle any basic math calulation like (10*(1+0,2)) which isn't possible with most of the mentioned solutions here.
An eval'd expression should end with ";"
Try this :
$ma ="2+10;";
$p = eval($ma);
print $p;
By the way, this is out of scope but the 'eval' function won't return the value of the expression. eval('2+10') won't return 12.
If you want it to return 12, you should eval('return 2+10;');

PHP Array to JavaScript Length

I wrote this code:
$userAddresses = $database->getUsers("SELECT * FROM Users");
$address = array();
foreach($userAddresses as $user){
array_push($address, array("address"=> $user['address'],
"zipcode" => $user['zipcode']));
}
$locations = array(
"locations" => $address
);
$jsonLocations = json_encode($locations);
This code returns this json object:
{"locations":[
{"address":"Sneekermeer 25","zipcode":"2993 RL"},
{"address":"Boeier 13","zipcode":"2992 AK"}]}
I want to get the length of this array inside JavaScript. So I did this:
var address = '<?php echo $jsonLocations ?>';
After that I called console.log(address.length); to check the length but some how it counts all the chars (108 I think) in the address variable and returns that as length. address.locations.length also doesn't work.
Could someone help me out?
You can use JSON.parse()
var address = JSON.parse('<?php echo $jsonLocations ?>');
console.log(address.length); // will give you length;
Thats because the string needs to be decoded to an object. You can do this one of two ways.
Non recommended:
var address = <?= $jsonLocations ?>;
Or more correctly and safer:
var address = JSON.parse('<?= addslashes(json_encode($jsonLocations)) ?>');
Do not forget the call to addslashes to prevent any single quotes in your array from breaking the javascript string.
You can either remove the quotes around var address = '<?php echo $jsonLocations ?>'; (i.e var address = <?php echo $jsonLocations ?>;) or use JSON.parse to parse it as a string to an object.
I have tried the below and its working
var address = '{"locations":[{"address":"Sneekermeer 25","zipcode":"2993 RL"},{"address":"Boeier 13","zipcode":"2992 AK"}]}';
address = JSON.parse(address);
console.log(address.locations.length);

Saving image as jpg in php issue [duplicate]

I want to create exact 5 random characters string with least possibility of getting duplicated. What would be the best way to do it? Thanks.
$rand = substr(md5(microtime()),rand(0,26),5);
Would be my best guess--Unless you're looking for special characters, too:
$seed = str_split('abcdefghijklmnopqrstuvwxyz'
.'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
.'0123456789!##$%^&*()'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 5) as $k) $rand .= $seed[$k];
Example
And, for one based on the clock (fewer collisions since it's incremental):
function incrementalHash($len = 5){
$charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
$base = strlen($charset);
$result = '';
$now = explode(' ', microtime())[1];
while ($now >= $base){
$i = $now % $base;
$result = $charset[$i] . $result;
$now /= $base;
}
return substr($result, -5);
}
Note: incremental means easier to guess; If you're using this as a salt or a verification token, don't. A salt (now) of "WCWyb" means 5 seconds from now it's "WCWyg")
If for loops are on short supply, here's what I like to use:
$s = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
You can try it simply like this:
$length = 5;
$randomletter = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
more details: http://forum.arnlweb.com/viewtopic.php?f=7&t=25
A speedy way is to use the most volatile characters of the uniqid function.
For example:
$rand = substr(uniqid('', true), -5);
The following should provide the least chance of duplication (you might want to replace mt_rand() with a better random number source e.g. from /dev/*random or from GUIDs):
<?php
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$result = '';
for ($i = 0; $i < 5; $i++)
$result .= $characters[mt_rand(0, 61)];
?>
EDIT:
If you are concerned about security, really, do not use rand() or mt_rand(), and verify that your random data device is actually a device generating random data, not a regular file or something predictable like /dev/zero. mt_rand() considered harmful:
https://spideroak.com/blog/20121205114003-exploit-information-leaks-in-random-numbers-from-python-ruby-and-php
EDIT:
If you have OpenSSL support in PHP, you could use openssl_random_pseudo_bytes():
<?php
$length = 5;
$randomBytes = openssl_random_pseudo_bytes($length);
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters);
$result = '';
for ($i = 0; $i < $length; $i++)
$result .= $characters[ord($randomBytes[$i]) % $charactersLength];
?>
I always use the same function for this, usually to generate passwords. It's easy to use and useful.
function randPass($length, $strength=8) {
$vowels = 'aeuy';
$consonants = 'bdghjmnpqrstvz';
if ($strength >= 1) {
$consonants .= 'BDGHJLMNPQRSTVWXZ';
}
if ($strength >= 2) {
$vowels .= "AEUY";
}
if ($strength >= 4) {
$consonants .= '23456789';
}
if ($strength >= 8) {
$consonants .= '##$%';
}
$password = '';
$alt = time() % 2;
for ($i = 0; $i < $length; $i++) {
if ($alt == 1) {
$password .= $consonants[(rand() % strlen($consonants))];
$alt = 0;
} else {
$password .= $vowels[(rand() % strlen($vowels))];
$alt = 1;
}
}
return $password;
}
It seems like str_shuffle would be a good use for this.
Seed the shuffle with whichever characters you want.
$my_rand_strng = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), -5);
I also did not know how to do this until I thought of using PHP array's. And I am pretty sure this is the simplest way of generating a random string or number with array's. The code:
function randstr ($len=10, $abc="aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789") {
$letters = str_split($abc);
$str = "";
for ($i=0; $i<=$len; $i++) {
$str .= $letters[rand(0, count($letters)-1)];
};
return $str;
};
You can use this function like this
randstr(20) // returns a random 20 letter string
// Or like this
randstr(5, abc) // returns a random 5 letter string using the letters "abc"
$str = '';
$str_len = 8;
for($i = 0, $i < $str_len; $i++){
//97 is ascii code for 'a' and 122 is ascii code for z
$str .= chr(rand(97, 122));
}
return $str
Similar to Brad Christie's answer, but using sha1 alrorithm for characters 0-9a-zA-Z and prefixed with a random value :
$str = substr(sha1(mt_rand() . microtime()), mt_rand(0,35), 5);
But if you have set a defined (allowed) characters :
$validChars = array('0','1','2' /*...*/,'?','-','_','a','b','c' /*...*/);
$validCharsCount = count($validChars);
$str = '';
for ($i=0; $i<5; $i++) {
$str .= $validChars[rand(0,$validCharsCount - 1)];
}
** UPDATE **
As Archimedix pointed out, this will not guarantee to return a "least possibility of getting duplicated" as the number of combination is low for the given character range. You will either need to increase the number of characters, or allow extra (special) characters in the string. The first solution would be preferable, I think, in your case.
If it's fine that you'll get only letters A-F, then here's my solution:
str_pad(dechex(mt_rand(0, 0xFFFFF)), 5, '0', STR_PAD_LEFT);
I believe that using hash functions is an overkill for such a simple task as generating a sequence of random hexadecimal digits. dechex + mt_rand will do the same job, but without unnecessary cryptographic work. str_pad guarantees 5-character length of the output string (if the random number is less than 0x10000).
Duplicate probability depends on mt_rand's reliability. Mersenne Twister is known for high-quality randomness, so it should fit the task well.
works fine in PHP (php 5.4.4)
$seed = str_split('abcdefghijklmnopqrstuvwxyz');
$rand = array_rand($seed, 5);
$convert = array_map(function($n){
global $seed;
return $seed[$n];
},$rand);
$var = implode('',$convert);
echo $var;
Live Demo
Source: PHP Function that Generates Random Characters
This simple PHP function worked for me:
function cvf_ps_generate_random_code($length=10) {
$string = '';
// You can define your own characters here.
$characters = "23456789ABCDEFHJKLMNPRTVWXYZabcdefghijklmnopqrstuvwxyz";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters)-1)];
}
return $string;
}
Usage:
echo cvf_ps_generate_random_code(5);
Here are my random 5 cents ...
$random=function($a, $b) {
return(
substr(str_shuffle(('\\`)/|#'.
password_hash(mt_rand(0,999999),
PASSWORD_DEFAULT).'!*^&~(')),
$a, $b)
);
};
echo($random(0,5));
PHP's new password_hash() (* >= PHP 5.5) function is doing the job for generation of decently long set of uppercase and lowercase characters and numbers.
Two concat. strings before and after password_hash within $random function are suitable for change.
Paramteres for $random() *($a,$b) are actually substr() parameters. :)
NOTE: this doesn't need to be a function, it can be normal variable as well .. as one nasty singleliner, like this:
$random=(substr(str_shuffle(('\\`)/|#'.password_hash(mt_rand(0,999999), PASSWORD_DEFAULT).'!*^&~(')), 0, 5));
echo($random);
function CaracteresAleatorios( $Tamanno, $Opciones) {
$Opciones = empty($Opciones) ? array(0, 1, 2) : $Opciones;
$Tamanno = empty($Tamanno) ? 16 : $Tamanno;
$Caracteres=array("0123456789","abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ");
$Caracteres= implode("",array_intersect_key($Caracteres, array_flip($Opciones)));
$CantidadCaracteres=strlen($Caracteres)-1;
$CaracteresAleatorios='';
for ($k = 0; $k < $Tamanno; $k++) {
$CaracteresAleatorios.=$Caracteres[rand(0, $CantidadCaracteres)];
}
return $CaracteresAleatorios;
}
I`ve aways use this:
<?php function fRand($len) {
$str = '';
$a = "abcdefghijklmnopqrstuvwxyz0123456789";
$b = str_split($a);
for ($i=1; $i <= $len ; $i++) {
$str .= $b[rand(0,strlen($a)-1)];
}
return $str;
} ?>
When you call it, sets the lenght of string.
<?php echo fRand([LENGHT]); ?>
You can also change the possible characters in the string $a.
Simple one liner which includes special characters:
echo implode("", array_map(function() {return chr(mt_rand(33,126));}, array_fill(0,5,null)));
Basically, it fills an array with length 5 with null values and replaces each value with a random symbol from the ascii-range and as the last, it joins them together t a string.
Use the 2nd array_fill parameter to control the length.
It uses the ASCII Table range of 33 to 126 which includes the following characters:
!"#$%&'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

saving script variables from php variables in while loop

been trying to save my data from my while loop to script variables but no success. Did an example if how I want to save my php data to script variables. This doesn't work for me. Anyone have any idea? Don't want to save all data manually. Very greatful for answers! Ask if you don't understand :)
$id = 0;
while($rows = mysql_fetch_array($data)){
$id = $id + 1;
$data = $rows['data'];
echo "<script>";
echo "var data" . $id . " = " . $data . ";"; //???
echo "</script>";
}
The best thing to do here would almost certainly be to create an array (on the PHP side), and then output the entire array at once.
Assuming you've built an array in $array, here's how you would output it:
echo "<script>var data = " . json_encode($array) . ";</script>"
More on json_encode in the docs, but basically it encodes the PHP data as valid JSON. Since JSON is a subset of JavaScript object and array initializer syntax, you can safely output JSON text as the right-hand side of an assignment, as above.
In the client-side script, you'd access each item via data[0], data[1], etc. up through data[data.length - 1].
Separately, note what Nathan Loding pointed out in a comment on the question:
...[you're] calling mysql_fetch_array($data) and then [have] $data = $rows['data'] two lines further down, thus overwriting $data...
...which will tend to mess up your fetch loop.
You are duplicating the script tag on every iteration.
you also need to surround the data in double or single quotes.
But it is not so safe..
$id = 0;
$data = "";
$vars = "";
while($rows = mysql_fetch_array($data)){
$id = $id + 1;
$data = $rows['data'];
$vars .= "var data" . $id . " = \"" . addslashes( $data ). "\";"; //???
}
echo "<script>";
echo $vars;
echo "</script>";
}

Categories

Resources