I am receiving a serialized string into a PHP function (sent via Ajax to PHP). Let's say it looks like this:
year=1923&season=Winter&person_1_name=barry&person_1_age=20&person_2_name=Tom&person_3_name=Jane&person_3_age=30
I need to know how in PHP to split those numbered fields out so I can do something with them, like:
foreach ( person_x as person ) {
// do something here with person_x's details
}
Also I can't generalise the information I will receive as some may not have all the info (note person_2 does not have an age in the above example) and there will be an unknown number of these fields (they are repeatable in the form)
Using parse_str() Recommended method
$string = 'year=1923&season=Winter&person_1_name=barry&person_1_age=20&person_2_name=Tom&person_3_name=Jane&person_3_age=30';
parse_str($string, $output);
foreach ($output as $key => $person){
echo $key . " = " . $person . "<br />";
}
Using explode()
$string = 'year=1923&season=Winter&person_1_name=barry&person_1_age=20&person_2_name=Tom&person_3_name=Jane&person_3_age=30';
$persons = explode("&", $string);
foreach ($persons as $person){
$details = explode("=", $person);
echo $details[0] . " = " . $details[1] . "<br />";
}
Output:
year = 1923
season = Winter
person_1_name = barry
person_1_age = 20
person_2_name = Tom
person_3_name = Jane
person_3_age = 30
----------
year = 1923
season = Winter
person_1_name = barry
person_1_age = 20
person_2_name = Tom
person_3_name = Jane
person_3_age = 30
Exclude all other fields that don't start with person_
parse_str($string, $output);
foreach ($output as $key => $person){
if(preg_match('/person_/', $key)){
echo $key . " = " . $person . "<br />";
}
}
Output:
person_1_name = barry
person_1_age = 20
person_2_name = Tom
person_3_name = Jane
person_3_age = 30
Related
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.
I have problem when I want to separate my string in JavaScript, this is my code :
var str= 'hello.json';
str.slice(0,4); //output hello
str.slice(6,9); //output json
the problem is when i want to slice second string ('json') I should create another slice too.
I want to make this code more simple , is there any function in JavaScript like explode function in php ?
You can use split()
var str = 'hello.json';
var res = str.split('.');
document.write(res[0] + ' ' + res[1])
or use substring() and indexOf()
var str = 'hello.json';
document.write(
str.substring(0, str.indexOf('.')) + ' ' +
str.substring(str.indexOf('.') + 1)
)
The php example for explode:
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *
The Javascript equivalent (ES2015 style):
//Example 1
let pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
let pieces = pizza.split(" ");
console.log(pieces[0]);
console.log(pieces[1]);
//Example 2
let data = "foo:*:1023:1000::/home/foo:/bin/sh";
let user, pass, uid, gid, gecos, home, shell;
[user, pass, uid, gid, gecos, home, ...shell] = data.split(":");
console.log(user);
console.log(pass);
I seem to be having an issue with array_fill().
I have a MYSQL table that has
------------------------
id - username - tickets
01 BOB 14
02 JIM 22
03 KYLE 9
-----------------------
I'm trying to save the values to an array, and
for each ticket the user has, the username is added to the array...
$select=$conn->query("SELECT * FROM table") or die (MySQL_error());
while($r = $select->fetch()){
$tickets_array = array_fill(0, $r['tickets'], $r['username']);
}
After this I am trying to push the values in $tickets_array to a javascript
array.
var tickets = new Array();
<?php foreach($tickets_array as $key => $val){ ?>
tickets.push('<?php echo $val; ?>');
<?php } ?>
The code is working. However, I am only getting the first result from the database. tickets = 'BOB','BOB','BOB','BOB','BOB','BOB','BOB','BOB','BOB','BOB','BOB','BOB','BOB','BOB'
the other results are not being pushed to the javascript array for some reason.
Any ideas of what I am doing wrong, and how I can fix it?
Thanks in advance.
Not sure why you are using array_fill, I would use fetch_all()
http://php.net/manual/en/mysqli-result.fetch-all.php
$select=$conn->query("SELECT * FROM table") or die (MySQL_error());
$tickets_array = $select->fetch_all());
I would try this approach. Much simpler and it populates your array the way you want.
$tickets = array();
while($r = $select->fetch_object()) {
for($i = 1; $i <= $r->tickets; $i++) {
$tickets[] = $r->username;
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to replicate the following CryptoJS 3.1.2 code with PHP 5.4.4 :
var plaintext = 'test';
var key = CryptoJS.enc.Utf8.parse('9rIY8vV8DdOKx3m6JocjEaObhhYc2NfY');
var iv = CryptoJS.enc.Utf8.parse('r0dkbnVQhklNeUGA');
var encrypted = CryptoJS.AES.encrypt(plaintext, 'euhe68vjdr1aX4F091c7aCggSMBf0A7M', key,{iv: iv,mode: CryptoJS.mode.CBC,padding: CryptoJS.pad.Pkcs7});
I have found several questions dealing with that problem, but none of them had that extra parameter in encrypt() between plaintext and key.
The CryptoJS wiki does not mention this parameter at all.
And yet, it works. I can decrypt with this :
var decrypted = CryptoJS.AES.decrypt(encrypted, 'euhe68vjdr1aX4F091c7aCggSMBf0A7M', key, {iv: iv});
If I omit 'euhe68vjdr1aX4F091c7aCggSMBf0A7M' in the decrypt() call, it won't work.
So that parameter really does something. But what? Is is a hash, a salt?
Does anybody know how I can replicate this specific encryption process with PHP?
I can not modify this JS code in any way.
The code is on a login page and is used to encrypt credentials before they are sent to the server.
I am trying to use PHP-cURL to submit credentials to that server from the command line, which is why I need to reproduce this encryption process.
Update: thanks to Jim's answer, I now have the proper JavaScript, now I need help with replicating the code in PHP
Here is the JS :
var plaintext = 'test';
var key = 'euhe68vjdr1aX4F091c7aCggSMBf0A7M';
var iv = CryptoJS.enc.Utf8.parse('r0dkbnVQhklNeUGA');
var encrypted = CryptoJS.AES.encrypt(plaintext, key, key,{iv: iv,mode: CryptoJS.mode.CBC,padding: CryptoJS.pad.Pkcs7})
encrypted equals U2FsdGVkX1+ZujoXKqDHcO+4N1QO+Nv1KHUMFjZos1s=
Here is the decryption:
var decrypted = CryptoJS.AES.decrypt(encrypted, key);
decrypted equals test
I have tried many different ways to replicate the encryption with PHP, but none of them gives a a string I can decode with the above JS.
For instance, using this AES_Encryption class, I tried the following code :
$key = 'euhe68vjdr1aX4F091c7aCggSMBf0A7M';
$iv = 'r0dkbnVQhklNeUGA';
$message = 'test';
$AES = new AES_Encryption($key, $iv, PKCS7);
$encrypted = $AES->encrypt($message);
$decrypted = $AES->decrypt($encrypted);
$base64_encrypted = base64_encode('Salted__'.$encrypted);
I end up with U2FsdGVkX18eEv+TnigBEKGJL8t/V1Hm instead of U2FsdGVkX1+ZujoXKqDHcO+4N1QO+Nv1KHUMFjZos1s=
Note that both strings start the same way, thanks to the 'Salted__' prefix I added (since CryptoJS seems to do the same thing).
I tried similar code with phpseclib, openssl_encrypt and mcrypt. No luck.
Any hint would be appreciated.
**Update: FIXED **
This PHP code is a perfect match for the CryptoJS code above.
function ssl_encrypt($pass, $data)
{
// Set a random salt
$salt = substr(md5(mt_rand(), true), 8);
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$pad = $block - (strlen($data) % $block);
$data = $data . str_repeat(chr($pad), $pad);
// Setup encryption parameters
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, "", MCRYPT_MODE_CBC, "");
$key_len = mcrypt_enc_get_key_size($td);
$iv_len = mcrypt_enc_get_iv_size($td);
$total_len = $key_len + $iv_len;
$salted = '';
$dx = '';
// Salt the key and iv
while (strlen($salted) < $total_len) {
$dx = md5($dx.$pass.$salt, true);
$salted .= $dx;
}
$key = substr($salted,0,$key_len);
$iv = substr($salted,$key_len,$iv_len);
mcrypt_generic_init($td, $key, $iv);
$encrypted_data = mcrypt_generic($td, $data);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
//return chunk_split(base64_encode('Salted__' . $salt . $encrypted_data),32,"\r\n");
return base64_encode('Salted__' . $salt . $encrypted_data);
}
function ssl_decrypt($password, $edata)
{
$data = base64_decode($edata);
print "Data: " . $data . "\n";
$salt = substr($data, 8, 8);
print "Salt (Base64): " . base64_encode($salt) . "\n";
$ct = substr($data, 16);
print "Content (Base64): " . base64_encode($ct) . "\n";
$rounds = 3;
$data00 = $password.$salt;
print "Data00 (Base64): " . base64_encode($data00) . "\n";
$md5_hash = array();
$md5_hash[0] = md5($data00, true);
$result = $md5_hash[0];
print "MD5-Hash[0] (Base64): " . base64_encode($result) . "\n";
for ($i = 1; $i < $rounds; $i++) {
$md5_hash[$i] = md5($md5_hash[$i - 1].$data00, true);
$result .= $md5_hash[$i];
print "Result (Base64): " . base64_encode($result) . "\n";
}
$key = substr($result, 0, 32);
print "Key (Base64): " . base64_encode($key) . "\n";
$iv = substr($result, 32, 16);
print "IV (Base64): " . base64_encode($iv) . "\n";
print "Decrypted: " . openssl_decrypt($ct, 'aes-256-cbc', $key, true, $iv) . "\n";
}
$encryptedString = ssl_encrypt('euhe68vjdr1aX4F091c7aCggSMBf0A7M', 'test');
$decryptedString = ssl_decrypt('euhe68vjdr1aX4F091c7aCggSMBf0A7M', $encryptedString);
I can't remember where I found it. Sorry.
This is a JavaScript thing, not a CryptoJS thing. Try this:
var decrypted = CryptoJS.AES.decrypt(encrypted, 'euhe68vjdr1aX4F091c7aCggSMBf0A7M', {iv: iv});
or this:
key = 'euhe68vjdr1aX4F091c7aCggSMBf0A7M';
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {iv: iv});
You'll see that what you think is the key, isn't the key at all. It's being grouped with the optional parameters at the end, and lost.
'euhe68vjdr1aX4F091c7aCggSMBf0A7M' is your key, or is what your key is derived from.
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>";
}