PHP check if contents are available - php

I am using random.org in my php script to generate random numbers like that:
function getToken($length){
$r = explode('
',file_get_contents('http://www.random.org/integers/?num='.$length.'&min=0&max=9&col=1&base=10&format=plain'));
$string = '';
foreach ( $r as $char ) $string.=$char;
return $string;
}
but my university net denies such queries, so whenewer i test my project using university wifi, i dont get random numbers to be generated, and that means trouble.
So, i before using this function, it needs to be chect if i can query random.org or not like that:
if( site is accessible ) return getToken();
else return false;
what would be the best way to check accesability?
Myself i tried:
file_get_contents();
but it sends warnings,whenewer it fails,
dns_get_record();
but i dont know if i can trust that, if it checks only dns name.
Please help!
P.S. a pinging technique might proove usefull...

You could just run file_get_contents with # to supress errors and simply return when it doesn't give you a random number, resulting in something like:
function getToken($length){
$number = #file_get_contents('http://www.random.org/integers/?num='.$length.'&min=0&max=9&col=1&base=10&format=plain');
if($number === false) return null;
$r = explode('',$number);
$string = '';
foreach ( $r as $char ) $string.=$char;
return $string;
}
That being said, I seriously doubt if you really need to use random.org to generate random numbers. PHP's own pseudo-random generator functions include openssl_random_pseudo_bytes that is said to generate "cryptographically strong" pseudorandom numbers:
http://www.php.net/manual/en/function.openssl-random-pseudo-bytes.php

Related

Is there any manual method other than "str_repeat" to repeat the string?

I mean if we give 3, b as parameters passed into function, it should return "bbb" by using loops.
I've tried some code, but I do not want to post it because it might look crazy for a well-versed developer. I can provide you links, this question has been asked in an interview, mainly they want it to be computed in C or C++. Since I am a PHP practitioner, I am curious to know it is possible in PHP. Below is the link (ROUND 2: SIMPLE CODING(3 hours))
https://www.geeksforgeeks.org/zoho-interview-set-3-campus/
A PHP function to do that would probably look like this:
function string_repeat($num, $string)
{
$result = "";
for ($x = 0; $x < $num; $x++) {
$result .= $string;
}
return $result;
}
So calling echo string_repeat(3, 'b'); would output:
bbb
One way would be to keep around a "dummy" string, of sufficient length to be longer than any string you want to generate. Then, we can use preg_replace to replace each character with whatever the input is. Finally, we can substring that replace string to the desired length.
$dummy = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$length = 3;
$dummy = preg_replace('/./', 'b', $dummy);
$output = substr($dummy, 0, $length);
echo $output;
This prints:
bbb
You could wrap this into a helper function, if you really wanted to do that. Note that internally the regex engine is most likely doing some looping of its own, so we are not really freeing ourselves from looping, just hiding it from the current context.

PHP Encryption, encrypts with empty line in mind

I'm working with some encryption in PHP that's being accessed by some c# code,
When I sha1 Encrypt the following: test1:test1:apple,
every online generator will return: 8ee27a0e9368d2835b3fdeb4b50caf1d8f790314
However, when I run my PHP script it returns 296b39344a6eb9d88c3bb1122f5941f0bcf3b0c2 instead. Because essentially it's adding an empty line along with the string (test1:test1:apple) that I'm encrypting.
Does anyone have any idea how to fix this? It's not neccesarily the worst thing in the world, it's just extremely annoying.
The code I'm using is pretty simple:
function GetRandomWord()
{
$file = "../Core/nouns0.txt";
$file_arr = file($file);
$num_lines = count($file_arr);
$last_index = $num_lines -1;
$rand_index = rand(0, $last_index);
$rand_text = $file_arr[$rand_index];
return $rand_text;
}
$enc = GetRandomWord();
$encrypted = sha1("$username:$password:$enc");
echo $encrypted;
which gets caught in c# by a script.
Thanks in advance!
#IƂyaBursov their answer helped! I changed the GetRandomWord() function's return statement to
return trim($rand_text);
Thanks!
file() will read each line of a file into an array. It reads the entire line, including the linefeed at the end. If you don't want this behaviour, use the second argument to say so:
$file_arr = file($file, FILE_IGNORE_NEW_LINES);

How to get the highest version number / tag in PHP

Because the Bitbucket API doesn't provide a method to get the latest tag for a repository I find myself having to get it from an array of all tags.
How do you do it?
I have tried max but it doesn't work for certain numbers e.g.
max(['1.0.8', '1.0.9', '1.0.10']);
returns '1.0.9'.
I know the tags will only ever be three numbers a.b.c they won't have other semver accepted strings like alpha etc. because of the way we do tags for our repos.
So how do you do it?
$versions = ['1.0.8', '1.0.9', '1.0.10'];
usort($versions, 'version_compare');
echo end($versions);
See http://php.net/version_compare
If you don't feel like modifying the array:
echo array_reduce($versions, function ($highest, $current) {
return version_compare($highest, $current, '>') ? $highest : $current;
});
By using the version_compare function:
function maxVersion($array)
{
$max = null;
foreach ($array as $version) {
if (version_compare($max, $version) === -1) {
$max = $version;
}
}
return $max;
}
print(maxVersion(['1.0.8', '1.0.9', '1.0.10']));
// returns "1.0.10"
Because you are dealing with Strings here rather than numbers, you will not get the result you require. You could try the following:
$version_numbers = str_replace(".","",['1.0.8', '1.0.9', '1.0.10']);
$max = max($version_numbers);
If you are always dealing with a fixed a.b.c structure then by replacing the decimal point you will get a series of integers that will let you determine the maximum relatively easily

Need every permutation of capitalized letters in php

I want to build an array in php that contains every possible capitalization permutation of a word. so it would be (pseudocode)
function permutate($word){
for ($i=0; $i<count($word); $i++){
...confused here...
array_push($myArray, $newWord)
}
return $myArray;
}
So say I put in "School" I should get an array back of
{school, School, sChool, SCHool, schOOl, ... SCHOOL}
I know of functions that capitalize the string or the first character, but I am really struggling with how to accomplish this.
This should do it for you:
function permute($word){
if(!$word)
return array($word);
$permutations = array();
foreach(permute(substr($word, 1)) as $permutation){
$lower = strtolower($word[0]);
$permutations[] = $lower . $permutation;
$upper = strtoupper($word[0]);
if($upper !== $lower)
$permutations[] = $upper . $permutation;
}
return $permutations;
}
Codepad Demo
However, for your particular use case there may be a better solution. As there are 2^n permutations for a string of length n. It will be infeasible to run this (or even to generate all those strings using any method at all) on a much longer string.
In reality you should probably be converting strings to one particular case before hashing them, before storing them in the database, if you want to do case-insensitive matching.

PHP - Most Efficient Dictionary Code

I'm using the following code to pull the definition of a word from a tab-delimited file with only two columns (word, definition). Is this the most efficient code for what I'm trying to do?
<?php
$haystack = file("dictionary.txt");
$needle = 'apple';
$flipped_haystack = array_flip($haystack);
foreach($haystack as $value)
{
$haystack = explode("\t", $value);
if ($haystack[0] == $needle)
{
echo "Definition of $needle: $haystack[1]";
$defined = "1";
break;
}
}
if($defined != "1")
{
echo "$needle not found!";
}
?>
Right now you're doing a lot of pointless work
1) load the file into a per-line array
2) flip the array
3) iterate over and explode every value of the array
4) test that exploded value
You can't really avoid step 1, but why do you have to do all that useless "busy work" for 2&3?
e.g. if your dictionary text was set up something like this:
word:definition
then a simple:
$matches = preg_grep('/^$word:(.*)$/', $haystack);
would do the trick for you, with far less code.
No. Most likely a trie is more efficient and you didn't sort your dictionary and it doesn't use a binary tree or ternary tree. I guess if you need to search in a huge dictionary your method is simply too slow.
Is this the most efficient code for what I'm trying to do?
Surely not.
To find only one needle you are processing all the entries.
I will be building up to have 100,000+ entries.
use a database then.

Categories