Generating a random string based on previous string - php

Okay so I'm trying to make a system where I can call:
echo _stringClamp("string");
it pushes "string" & the random string(needs to be a new random string each refresh) to an array, and if I call it twice
echo _stringClamp("string");
echo _stringClamp("string");
it will echo the same value.
This is what I have so far.
<?php
function _stringClamp ($string){
$stringSave = $string;
$stringChars = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890";
$strings = array();
$string = str_shuffle($string);
$string = "__" . $string;
$id = end($strings);
for ($i = 0; $i < 15; $i++) {
$string.= $stringChars[rand(0, strlen($stringChars) - 1)];
}
$strings[$stringSave] = $stringSave;
if (in_array($stringSave, $strings)) {
return $strings[$string];
}else{
$strings[$stringSave] = $string;
print_r($strings);
}
}
echo _stringClamp("IDs");
echo "<br>";
echo _stringClamp("IDs");
?>

In order to get what you are asking for you would probably need to have a random value generated before you call the function then use that random value as a second parameter such as:
<?php
$num = rand(0, 100000);
echo _stringClamp("string", $num);
echo _stringClamp("string", $num);
?>
This would provide a random number to use in your function but if you refresh the page the number will change. However if called twice on the same page it would have the same output value.... Right?
You could even use a randomly generated string instead of a number...

If i understand you correctly, you need to use hash-functions (guarantee same output for same input).

Just hash the current time.
$Seed = time();
$RandomString = md5($Seed);
If you don't want to string to be predictable (eg knowing when the script ran could let someone predict the string) then use a random number generator...
$Seed = rand();
$RandomString = md5($Seed);
As long as the variable is declared somewhere outside the function...
$RandomString = md5(time());
function _stringClamp($String) {
global $RandomString;
return $String . $RandomString;
}
You should get the same string every time

Related

Simple php Calculation function dosent get called?

User submits a number (Temperatur in Fahrenheit)
My Code takes the user number ,converts to celsius and then outputs it.
unfortunately it dosent output :)
i did echo the user input - that works, but my output in celsius is displayed as 0
<?php
$tempInCelsius = 0;
$temp = $_GET['temp'];
function tempcalc($a){
global $tempInCelsius;
($a - 32) * 5/9;
return $placeholder;
};
tempcalc($temp);
echo $placeholder;
print "<br>";
echo $temp;
?>
Any Idea?
Here is the answer. i messed up my brain at the beginning but figured it out myself at the end.
$temp = $_GET['temp'];
function tempcalc($num1)
{
$out = round(($num1 - 32) * (5 / 9));
echo $out;
}

How to make a personal algorithm for hash in PHP

I want to make a personal algorithm for hashing texts in PHP. The letter 'a' crypt in 'xyz', 'b' in '256' and some more. How it's possible this?
It's possible by simple create a function that make characters substitution, like this:
function myEncrypt ($text)
{
$text = str_replace(array('a', 'b'), array('xby', '256'), $text);
// ... others
return $text;
}
version with two arrays "search" and "replaceWith" passed as arguments:
function myEncrypt ($text, $search=array(), $replaceWith=array())
{
return str_replace($search, $replaceWith, $text);
}
WARNING: That way isn't a correct solution to encrypt a text, there are a lot of better ways to do a secure encryption with PHP (see for example this post).
I'm bored at work so I thought i'd give this a crack.
This isn't secure at all. The crypt must be hard coded and the crypted character must have a size of 3.
<?php
//define our character->crypted text
$cryptArray = array( "a"=>"xyz","b"=>"256");
//This is our input
$string = "aab";
//Function to crypt the string
function cryptit($string,$cryptArray){
//create a temp string
$temp = "";
//pull the length of the input
$length = strlen($string);
//loop thru the characters of the input
for($i=0; $i<$length; $i++){
//match our key inside the crypt array and store the contents in the temp array, this builds the crypted output
$temp .= $cryptArray[$string[$i]];
}
//returns the string
return $temp;
}
//function to decrypt
function decryptit($string,$cryptArray){
$temp = "";
$length = strlen($string);
//Swap the keys with data
$cryptArray = array_flip($cryptArray);
//since our character->crypt is count of 3 we must $i+3 to get the next set to decrypt
for($i =0; $i<$length; $i = $i+3){
//read from the key
$temp .= $cryptArray[$string[$i].$string[$i+1].$string[$i+2]];
}
return $temp;
}
$crypted = cryptit($string,$cryptArray);
echo $crypted;
$decrypted = decryptit($crypted,$cryptArray);
echo $decrypted;
The input was : aab
The output is:
xyzxyz256
aab
Here's the 3v4l link:
https://3v4l.org/chR2A

PHP and Array_round spiteful function

I'm trying to create a function to pick up words from a text file randomly, and no one here poblema. The problem arises when I try to verify if the user correctly inserts the words. Unfortunately, I always get a negative answer. From what I understood when called, the function can not save the contents into the variable that naturally remains empty.
<?php
function random_word() {
$dictionary = "dictionary.txt";
$word = file($dictionary);
$n = 0;
while ($n < 2) {
$n++;
$randomword = array_rand($word);
echo $word[$randomword];
}
}
$a = random_word();
echo "-----------------";
echo $a;
?>
If I try to check the $a variable it tells me that it is NULL. I'm sure the problem is the function but I know PHP shortly and I'm struggling to find the error.
You need to return something. Not sure if you want to return a string or an array but your code seems to be made for string.
<?php
function random_word() {
$dictionary = "dictionary.txt";
$word = file($dictionary);
$n = 0;
while ($n < 2) {
$n++;
$randomword = array_rand($word);
$returner .= $word[$randomword] . " ";
}
return trim($returner);
}
$a = random_word();
echo "-----------------";
echo $a;
?>

Implementing strlen() in a loop

I've got a string here with names of students (leerlingen) and im trying to follow the exercise here.
The code shows the length of the full string.
Next up would be use a loop to check who has the longest name, but how to implement strlen() in a loop?
// change the string into an array using the explode() function
$sleerlingen = "Kevin,Maarten,Thomas,Mahamad,Dennis,Kim,Joey,Teun,Sven,Tony";
$namen = explode(" ", $sleerlingen);
echo $namen[0];
echo "<br><br>";
//determin the longest name by using a loop
// ask length
$arraylength = strlen($sleerlingen);
sleerlingen = $i;
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
echo $arraylength;
?>
You used bad separator in your explode function, in string there is no space.
This should work (I didn't try it). In foreach loop you check current length with the longest one and if the current is longer, just save it as longest.
<?php
$sleerlingen = "Kevin,Maarten,Thomas,Mahamad,Dennis,Kim,Joey,Teun,Sven,Tony";
$names = explode(',', $sleerlingen);
$longest;
$longest_length = 0;
foreach ($names as $item) {
if (strlen($item) > $longest_length) {
$longest_length = strlen($item);
$longest = $item;
}
}
echo 'Longest name: ' . $longest . ', ' . $longest_length .' chars.';
?>
You can create a custom sort function to sort the array based on the strings length. Then you can easily take the first key in the array.
<?php
$sleerlingen = "Kevin,Maarten,Thomas,Mahamad,Dennis,Kim,Joey,Teun,Sven,Tony";
$namen = explode(",", $sleerlingen); // changed the space to comma, otherwise it won't create an array of the string.
function sortByLength($a,$b){
return strlen($b)-strlen($a);
}
usort($namen,'sortByLength');
echo $namen[0];
?>

continued : unable to post fields to the next page in php and HTML

So I have fields that are generated dynamically in a different page and then their results should posted to story.php page. fields is going to be : *noun1 *noun2 *noun3 and story is going to be : somebody is doing *noun1 etc. What I want to do is to replace *noun1 in the story with the *noun, I have posted from the previous page ( I have *noun1 posted from the previous page ) but the code below is not working :
$fields = $_POST['fields'];
$story = $_POST['story'];
$fieldsArray = split(' ', $fields);
for ($i = 0; $i < count($fieldsArray); $i++) {
${$fieldsArray[$i]} = $_POST[$fieldsArray[$i]];
}
// replace words in story with input
for ($i = 0; $i < count($story); $i++) {
$thisWord = $story[$i];
if ($thisWord[0] == '*')
$story[$i] = ${$thisWord.substring(1)};
}
$tokensArray = split(' ',$tokens);
echo $story;
Your problem is likely that you are trying to echo $story, which I gather is an array. You might have better luck with the following:
$storyString = '';
for ($i = 0; $i < count($story); $i++)
{
$storyString .= $story[i] . ' ';
}
echo $storyString;
echo can't print an array, but you can echo strings to your heart's content.
You almost certainly don't want variable variables (e.g. ${$fieldsArray[$i]}). Also, $thisWord.substring(1) looks like you're trying to invoke a method, but that's not what it does; . is for string concatenation. In PHP, strings aren't objects. Use the substr function to get a substring.
preg_replace_callback can replace all your code, but its use of higher order functions might be too much to get into right now. For example,
function sequence($arr) {
return function() {
static $i=0
$val = $arr[$i++];
$i %= count($arr);
return $val;
}
}
echo preg_replace_callback('/\*\w+/', sequence(array('Dog', 'man')), "*Man bites *dog.");
will produce "Dog bites man." Code sample requires PHP 5.3 for anonymous functions.

Categories