I tried making a script that could save all files from a webpage with a pattern in name to a server.
<?php
$base_url = "http://www.someurl.com/";
$sufix = ".jpg";
$id_start= "Name Numberstart"; //Picture 1
$id_end = "Name Numberend"; // Picture 235
$path_to_save = "filer/";
foreach(range($id_start, $id_end) as $id) {
file_put_contents($path_to_save.$id.$sufix, file_get_contents($base_url.$id.$sufix));
}
?>
If I only use id with numbers etc. 1-20 or 50 - 60 and so on, the script works perfectly. But when I have a name in front and white space, it doesn't seem to work. It just saves 1 file and stops.
According to php.net's description of range:
Character sequence values are limited to a length of one. If a length greater than one is entered, only the first character is used.
I take that to mean that
range("Name Numberstart", "Name Numbersend") == array("N");
And if we run php interactively, this is confirmed:
php > $var = range("Name Numberstart", "Name Numbersend");
php > var_dump($var);
array(1) {
[0]=>
string(1) "N"
}
So basically, you're actually getting the range of the first character of the first word to the first character of the second word. If we change the second word to "Pretty", we get:
php > var_dump(range("Name Numberstart", "Pretty Numbersend"));
array(3) {
[0]=>
string(1) "N"
[1]=>
string(1) "O"
[2]=>
string(1) "P"
}
Related
I want to pick digits between other groups of digits.
I think it is best that I show this pattern in order to explain what I mean:
xxxxx...xxxxyyyyyyy....yyyyzzzzzzz....zzzz
{ 1000 } { 1500 }
So from the above string structure, I want to pick the digits that occur between the first 1000 digits (xx) and the final 1500 digits (zz).
I tried substr but as I have to specify the length it didn't work for me. Because I don't know what the length is between those two indexes.
Here is my code:
$id = base64_encode($core->security(1070).$list["user_id"]);
$core->security creates number as many as what is input.
In this it example it creates a length of 1070 random digits.
$decoded = base64_decode($id);
$homework_id = mysqli_real_escape_string($connection,substr($decoded, 1070));
I can pick numbers after some length of digits. But I want to take them between series of digits.
I tried substr but as I have to specify the length it didnt work for me. Because I don't the length between 1000 number and 1500 number.
There is a feature of substr that you might have missed. From the documentation:
If length is given and is negative, then that many characters will be omitted from the end of string
So this would work:
$left = 1000; // Number of characters to be chopped off from the left side
$right = 1500; // Number of characters to be chopped off from the right side
$id = substr($id, $left, -$right) ?: "";
The ?: "" part is there to convert false to "". substr will return false when there are not enough characters present in the string to chop off that many characters. If in that case you just want to get an empty string, then ?: "" will do just that.
You can do it with regex to capture numbers that is between 1000 and 1500
<?php
$number = '10001212121212121500'; #make it string first
if (preg_match('/1000(.*?)1500/', $number, $match) == 1) {
echo (int)$match[1];
}
?>
DEMO1: https://3v4l.org/pebul
DEMO2: https://3v4l.org/8TiWH
$text = <<<HEREDOC
xxxxx...xxxxyyyyyyy....yyyyzzzzzzz....zzzz
{ 1000 } { 1500 }
HEREDOC;
preg_match_all('/\{\s+(\d+)\s+\}/', $text, $matches);
var_dump($matches);
Result:
array(2) {
[0]=>
array(2) {
[0]=>
string(12) "{ 1000 }"
[1]=>
string(15) "{ 1500 }"
}
[1]=>
array(2) {
[0]=>
string(4) "1000"
[1]=>
string(4) "1500"
}
}
I was just goofing around with PHP and I decided to generate some random numbers with PHP_INT_MIN (-9223372036854775808) and PHP_INT_MAX (9223372036854775807). I simply echoed the following:
echo rand(-9223372036854775808, 9223372036854775807);
I kept refreshing to see the numbers generated and to view the randomness of the numbers, as a result I started to notice a pattern emerging. Every 2-4 refreshes 0 appeared and this happened without fail, at one stage I even got 0 to appear 4x in a row.
I wanted to experiment further so I created the following snippet:
<?php
$countedZero = 0;
$totalGen = 250;
for ($i = 1; $i <= $totalGen; $i++) {
$rand = rand(-9223372036854775808, 9223372036854775807);
if ($rand == 0) {
echo $i . ": <font color='red'>" . $rand . "</font><br/>";
$countedZero++;
} else {
echo $i . ": " . $rand . "<br/>";
}
}
echo "0 was generated " . $countedZero . "/" . $totalGen . " times which is " . (($countedZero / $totalGen) * 100) . "%."
?>
this would give me a clear idea of what the generation rate is. I ran 8 tests:
The first 3 tests were using a $totalGen of 250. (3 tests total).
The second 3 tests were using a $totalGen of 1000. (6 tests total).
The third test was just to see what the results would be on a larger number, I chose 10,000. (7 tests total).
The fourth test was the final test, I was intrigued at this point because the last (large number) test got such a high result surprisingly so I raised the stakes and set $totalGen to 500,000. (8th test total).
Results
I took a screenshot of the results. I took the first output, I didn't keep testing it to try and get it to fit a certain pattern:
Test 1 (250)
(1).
(2).
(3).
Test 2 (1000)
(1).
(2).
(3).
Test 3 (10,000)
(1).
Test 4 (500,000)
(1).
From the above results, it is safe to assume that 0 has a very high probability of showing up even when the range of possible numbers is at its maximum. So my question is:
Is there a logical reason to why this is happening?
Considering how many numbers it can choose from why is 0 a recurring number?
Note Test 8 was originally going to be 1,000,000 but it lagged out quite badly so I reduced it to 500,000 if someone could test 1,000,000 and show the results by editing the OP it would be much appreciated.
Edit 1
As requested by #maiorano84 I used mt_rand instead of rand and these were the results.
Test 1 (250)
(1).
(2).
(3).
Test 2 (1000)
(1).
(2).
(3).
Test 3 (10,000)
(1).
Test 4 (500,000)
(1).
The results as you can see show that 0 still has a high probability of showing up. Also using the function rand provided the lowest result.
Update
It seems that in PHP7 when using the new function random_int it fixes the issue.
Example PHP7 random_int
https://3v4l.org/76aEH
This is basically an example of how someone wrote a bad rand() function. When you specify the min/max range in rand(), you hit a part of PHP's source that just results in imperfect distribution in the PRNG.
Specifically lines 44-45 of php_rand.h in php-src, which is the following macro:
#define RAND_RANGE(__n, __min, __max, __tmax) \
(__n) = (__min) + (zend_long) ((double) ( (double) (__max) - (__min) + 1.0) * ((__n) / ((__tmax) + 1.0)))
From higher up the call stack (lines 300-302 in rand.c of php-src):
if (argc == 2) {
RAND_RANGE(number, min, max, PHP_RAND_MAX);
}
RAND_RANGE being the macro defined above. By removing the range parameters by just calling rand() instead of rand(-9223372036854775808, 9223372036854775807) you will get even distribution again.
Here's a script to demonstrate the effects...
function unevenRandDist() {
$r = [];
for ($i = 0; $i < 10000; $i++) {
$n = rand(-9223372036854775808,9223372036854775807);
if (isset($r[$n])) {
$r[$n]++;
} else {
$r[$n] = 1;
}
}
arsort($r);
// you should see 0 well above average in the top 10 here
var_dump(array_slice($r, 0, 10));
}
function evenRandDist() {
$r = [];
for ($i = 0; $i < 10000; $i++) {
$n = rand();
if (isset($r[$n])) {
$r[$n]++;
} else {
$r[$n] = 1;
}
}
arsort($r);
// you should see the top 10 are about identical
var_dump(array_slice($r, 0, 10)); //
}
unevenRandDist();
evenRandDist();
Sample Output I Got
array(10) {
[0]=>
int(5005)
[1]=>
int(1)
[2]=>
int(1)
[3]=>
int(1)
[4]=>
int(1)
[5]=>
int(1)
[6]=>
int(1)
[7]=>
int(1)
[8]=>
int(1)
[9]=>
int(1)
}
array(10) {
[0]=>
int(1)
[1]=>
int(1)
[2]=>
int(1)
[3]=>
int(1)
[4]=>
int(1)
[5]=>
int(1)
[6]=>
int(1)
[7]=>
int(1)
[8]=>
int(1)
[9]=>
int(1)
}
Notice the inordinate difference in the number of times 0 shows up in the first array vs. the second array. Even though technically they are both generating random numbers within the same exact range of PHP_INT_MIN to PHP_INT_MAX.
I guess you could blame PHP for this, but it's important to note here that glibc rand is not known for generating good random numbers (regardless of crypto). This problem is known in glibc's implementation of rand as pointed out by this SO answer
I took a quick look at your script and ran it through the command line. The first thing I had noticed is that because I was running a 32-bit version of PHP, my Integer Minimum and Maximum were different from yours.
Because I was using your original values, I was actually getting 0 100% of the time. I resolved this by modifying the script like so:
$countedZero = 0;
$totalGen = 1000000;
for ($i = 1; $i <= $totalGen; $i++) {
$rand = rand(~PHP_INT_MAX, PHP_INT_MAX);
if ($rand === 0) {
//echo $i . ": <font color='red'>" . $rand . "</font><br/>";
$countedZero++;
} else {
//echo $i . ": " . $rand . "<br/>";
}
}
echo "0 was generated " . $countedZero . "/" . $totalGen . " times which is " . (($countedZero / $totalGen) * 100) . "%.";
I was able to confirm that each test would yield just shy of a 50% hit rate for 0.
Here's the interesting part, though:
$rand = rand(~PHP_INT_MAX+1, PHP_INT_MAX-1);
Altering the range to these values causes the likelihood of zero coming up to plummet to an average of 0.003% (after 8 tests). The weird part was that after checking the value of $rand that was not zero, I was seeing many values of 1, and many random negative numbers. No positive numbers greater than 1 were showing up.
After changing the range to the following, I was able to see consistent behavior and more randomization:
$rand = rand(~PHP_INT_MAX/2, PHP_INT_MAX/2);
Here's what I'm pretty sure is happening:
Because you're dealing with a range here, you have to take into account the difference between the minimum and the maximum, and whether or not PHP can support that value.
In my case, the minimum that PHP is able to support is -2147483648, the maximum 2147483647, but the difference between them actually ends up being 4294967295 - a much larger number than PHP can store, so it truncates the maximum in order to try to manage that value.
Ultimately, if the difference of your minimum and maximum exceeds the PHP_INT_MAX constant, you're going to see unexpected behavior.
what I'm trying to do looks impossible with my actual PHP skills. Below you can find an exemple of a race result file, in txt. This file is composed of :
dir= the-track-file-name
longname= the-track-long-name-with-spaces
firstlap= the number of gate (checkpoint) the first lap is composed of
normallap= the number of gate (checkpoint) other laps are composed of
holeshotindex= thefirst gate after the start, which determine which player started first
time= the race duration, in minutes
laps= the number of laps (if minutes + laps, laps are counted when time's up)
starttime=1793
date= timestamp of the start
players:(under this line are all the player, just 1 in this exemple)
slot=0 (this is the multiplayer server slot taken by the player)
uid=5488 (this is the unique ID of the player)
number=755 (player's race number)
bike=rm125 (player's motorbike model)
name=Nico #755(player's name)
times: (under this line are things like timestamps of every gate, like SLOT|GATE|TIME)
0 0 1917 (it's like divide the timstamp /128 sounds good)
0 1 2184
(and etc, see full exemple below...)
The game server is on a dedicated ubuntu.
At each race end I send these results on an FTP web server, and what I need is to get vars to output something readable like a table with results after selecting a race (in a dropdown list i.e.).
Doing the table isn't the problem.
My problem is, even searching a lot here, that I don't know how to read the txt to obtain this kind of page (only RESULTS table) : http://mxsimulator.com/servers/q2.MXSConcept.com/races/6015.html
Here is a full sample result file : http://www.mediafire.com/view/3b34a4kd5nfsj4r/sample_result_file.txt
Thank you
Ok, tonight it's file parsing time.
I've written a very basic parser, which walks through the data line by line.
First it looks for "=". When a "=" is found the line is split/exploded at "=".
You get two parts: before and after the "=".
I've used them as key and value in an $results array.
This process continues till we reach the line "times:".
That's the line indicating that on the next line (line "times:" + 1) the results start.
The results are "slot gate time" separated by spaces. So the results are exploded with " " (space) this time and you get the three parts.
I've inserted an array key 'times' which contains an array with named keys (slot,gate,time).
You might just look at the structure of the $results array.
It should be very easy to iterate over it to render a table or output data.
#$datafile = 'http://www.mediafire.com/view/3b34a4kd5nfsj4r/sample_result_file.txt';
#$lines = file_get_contents($datafile);
$lines = '
dir=Dardon-Gueugnon
longname=Dardon Gueugnon
firstlap=72
normallap=71
holeshotindex=1
time=0
laps=6
starttime=1846
date=1407162774
players:
slot=0
uid=8240
number=172
bike=rm125
name=Maximilien Jannot | RH-Factory
slot=1
uid=7910
number=666
bike=rm125
name=Patrick Corvisier|Team RH-Factory
slot=2
uid=10380
number=114
bike=rm125
name=Benoit Krawiec | MXS-Concept.com
slot=6
uid=6037
number=59
bike=rm125
name=Yohan Levrage | SPEED
slot=8
uid=6932
number=447
bike=rm125
name=Morgan Marlet | Mxs-Concept.com
times:
6 0 1974
1 0 1989
0 0 2020
2 0 2056
6 1 2242
1 1 2260
0 1 2313
2 1 2338
6 2 2434
1 2 2452';
$results = array();
$parseResults = false;
#foreach($lines as $line){ // use this line when working with file_get_contents
foreach(preg_split("/((\r?\n)|(\r\n?))/", $lines) as $line){
if($parseResults === true) {
$parts = explode(' ', $line); // SLOT|GATE|TIME = parts 0|1|2
$times = array(
'slot' => $parts[0],
'gate' => $parts[1],
'time' => $parts[2]
);
$results['times'][] = $times;
}
if(false !== strpos($line, '=')) { // if line has a = in it, explode it
$parts = explode('=', $line);
$results[$parts[0]] = $parts[1]; // assign parts to array as key=value
}
if(false !== strpos($line, 'times:')) {
// we reached "times:", let's set a flag to start reading results in the next iteration
$parseResults = true;
}
}
var_dump($results);
Output:
array(15) {
["dir"]=> string(15) "Dardon-Gueugnon"
["longname"]=> string(15) "Dardon Gueugnon"
....
["name"]=> string(31) "Morgan Marlet | Mxs-Concept.com"
["times"]=> array(10) {
[0]=> array(3) { ["slot"]=> string(1) "6" ["gate"]=> string(1) "0" ["time"]=> string(4) "1974" }
[1]=> array(3) { ["slot"]=> string(1) "1" ["gate"]=> string(1) "0" ["time"]=> string(4) "1989" }
[2]=> array(3) { ["slot"]=> string(1) "0" ["gate"]=> string(1) "0" ["time"]=> string(4) "2020" }
...
} } }
I have some database figures that I am doing some simple math with. For some reason, I can't keep the total from rounding to the nearest dollar. I need to include the cents information, as well, though. I am positive that each itemPrice entry contains two decimal places in the database.
if (strpos($row2["itemDiscount"],'%') !== false) {
$itemDiscount = $row2["itemDiscount"];
$itemDetailTotalUnformatted = $row2["itemQuantity"]*($itemPrice*(1-($itemDiscount/100)));
}
else {
$itemDetailTotalUnformatted = $row2["itemQuantity"]*($row2["itemPrice"]-$row2["itemDiscount"]);
}
$itemDetailTotal = number_format($itemDetailTotalUnformatted, 2, '.', '');
echo $itemDetailTotal;
var_dump($row2):
50.00array(6) {
[0]=>
string(1) "2"
"itemQuantity"]=>
string(1) "2"
[1]=>
string(5) "30.00"
[itemPrice]=>
string(1) "30.00"
[2]=>
string(4) "5.00"
[itemPrice]=>
string(4) "5.00"
When dealing with currency, ALWAYS work in integers. Save the prices in cents, handle prices in cents, and only at the very end do you divide by 100 to present the result.
The reason for this is that ints have perfect precision (up to obscenely high values, where they are handled as floats instead), whereas floats do not. There is no fixed-point type in PHP.
Once you do that, your rounding problems will probably disappear.
This question already has answers here:
Getting N random numbers whose sum is M
(9 answers)
Closed 1 year ago.
do you know a way to split an integer into say... 5 groups.
Each group total must be at random but the total of them must equal a fixed number.
for example I have "100" I wanna split this number into
1- 20
2- 3
3- 34
4- 15
5- 18
EDIT: i forgot to say that yes a balance would be a good thing.I suppose this could be done by making a if statement blocking any number above 30 instance.
I have a slightly different approach to some of the answers here. I create a loose percentage based on the number of items you want to sum, and then plus or minus 10% on a random basis.
I then do this n-1 times (n is total of iterations), so you have a remainder. The remainder is then the last number, which isn't itself truley random, but it's based off other random numbers.
Works pretty well.
/**
* Calculate n random numbers that sum y.
* Function calculates a percentage based on the number
* required, gives a random number around that number, then
* deducts the rest from the total for the final number.
* Final number cannot be truely random, as it's a fixed total,
* but it will appear random, as it's based on other random
* values.
*
* #author Mike Griffiths
* #return Array
*/
private function _random_numbers_sum($num_numbers=3, $total=500)
{
$numbers = [];
$loose_pcc = $total / $num_numbers;
for($i = 1; $i < $num_numbers; $i++) {
// Random number +/- 10%
$ten_pcc = $loose_pcc * 0.1;
$rand_num = mt_rand( ($loose_pcc - $ten_pcc), ($loose_pcc + $ten_pcc) );
$numbers[] = $rand_num;
}
// $numbers now contains 1 less number than it should do, sum
// all the numbers and use the difference as final number.
$numbers_total = array_sum($numbers);
$numbers[] = $total - $numbers_total;
return $numbers;
}
This:
$random = $this->_random_numbers_sum();
echo 'Total: '. array_sum($random) ."\n";
print_r($random);
Outputs:
Total: 500
Array
(
[0] => 167
[1] => 164
[2] => 169
)
Pick 4 random numbers, each around an average of 20 (with distribution of e.g. around 40% of 20, i.e. 8). Add a fifth number such that the total is 100.
In response to several other answers here, in fact the last number cannot be random, because the sum is fixed. As an explanation, in below image, there are only 4 points (smaller ticks) that can be randomly choosen, represented accumulatively with each adding a random number around the mean of all (total/n, 20) to have a sum of 100. The result is 5 spacings, representing the 5 random numbers you are looking for.
Depending on how random you need it to be and how resource rich is the environment you plan to run the script, you might try the following approach.
<?php
set_time_limit(10);
$number_of_groups = 5;
$sum_to = 100;
$groups = array();
$group = 0;
while(array_sum($groups) != $sum_to)
{
$groups[$group] = mt_rand(0, $sum_to/mt_rand(1,5));
if(++$group == $number_of_groups)
{
$group = 0;
}
}
The example of generated result, will look something like this. Pretty random.
[root#server ~]# php /var/www/dev/test.php
array(5) {
[0]=>
int(11)
[1]=>
int(2)
[2]=>
int(13)
[3]=>
int(9)
[4]=>
int(65)
}
[root#server ~]# php /var/www/dev/test.php
array(5) {
[0]=>
int(9)
[1]=>
int(29)
[2]=>
int(21)
[3]=>
int(27)
[4]=>
int(14)
}
[root#server ~]# php /var/www/dev/test.php
array(5) {
[0]=>
int(18)
[1]=>
int(26)
[2]=>
int(2)
[3]=>
int(5)
[4]=>
int(49)
}
[root#server ~]# php /var/www/dev/test.php
array(5) {
[0]=>
int(20)
[1]=>
int(25)
[2]=>
int(27)
[3]=>
int(26)
[4]=>
int(2)
}
[root#server ~]# php /var/www/dev/test.php
array(5) {
[0]=>
int(9)
[1]=>
int(18)
[2]=>
int(56)
[3]=>
int(12)
[4]=>
int(5)
}
[root#server ~]# php /var/www/dev/test.php
array(5) {
[0]=>
int(0)
[1]=>
int(50)
[2]=>
int(25)
[3]=>
int(17)
[4]=>
int(8)
}
[root#server ~]# php /var/www/dev/test.php
array(5) {
[0]=>
int(17)
[1]=>
int(43)
[2]=>
int(20)
[3]=>
int(3)
[4]=>
int(17)
}
$number = 100;
$numbers = array();
$iteration = 0;
while($number > 0 && $iteration < 5) {
$sub_number = rand(1,$number);
if (in_array($sub_number, $numbers)) {
continue;
}
$iteration++;
$number -= $sub_number;
$numbers[] = $sub_number;
}
if ($number != 0) {
$numbers[] = $number;
}
print_r($numbers);
This should do what you need:
<?php
$tot = 100;
$groups = 5;
$numbers = array();
for($i = 1; $i < $groups; $i++) {
$num = rand(1, $tot-($groups-$i));
$tot -= $num;
$numbers[] = $num;
}
$numbers[] = $tot;
It won't give you a truly balanced distribution, though, since the first numbers will on average be larger.
I think the trick to this is to keep setting the ceiling for your random # generator to 100 - currentTotal
The solution depends on how random you want your values to be, in other words, what random situation you're going to simulate.
To get totally random distribution, you'll have to do 100 polls in which each element will be binded to a group, in symbolic language
foreach i from 1 to n
group[ random(1,n) ] ++;
For bigger numbers, you could increase the selected group by random(1, n/100) or something like that until the total sum would match the n.
However, you want to get the balance, so I think the best for you would be the normal distribution. Draw 5 gaussian values, which will divide the number (their sum) into 5 parts. Now you need to scale this parts so that their sum would be n and round them, so you got your 5 groups.
The solution I found to this problem is a little different but makes makes more sense to me, so in this example I generate an array of numbers that add up to 960. Hope this is helpful.
// the range of the array
$arry = range(1, 999, 1);
// howmany numbers do you want
$nrresult = 3;
do {
//select three numbers from the array
$arry_rand = array_rand ( $arry, $nrresult );
$arry_fin = array_sum($arry_rand);
// dont stop till they sum 960
} while ( $arry_fin != 960 );
//to see the results
foreach ($arry_rand as $aryid) {
echo $arryid . '+ ';
}