Simple random generator script not working - php

I have this script but it's not working, not sure how to fix it, any tips please? all I get out the other end is the letter "t"
Thanks :)
<?php
$cachefile = './current_t_id';
$time = $id = null; // assume we have no cached quote
$change_every = 3600; // seconds
$pages = array(1 => 'text1-1.php', 2 => 'text1-2.php');
foreach($pages as $pagekey => $page){
if($pagekey == $siteId){
include($page);
}
}
// if cached quote exists, load it
if(is_file($cachefile)) {
list($time, $id) = explode(' ', file_get_contents($cachefile));
}
// if no cached quote or duration expired, change it
if(!$time || time() - $time > $change_every) {
srand ((double) microtime() * 100000);
$id = rand(0,count($page)-1);
file_put_contents($cachefile, time().' '.$id); // update cache
}
// echo the quote, be it cached or freshly picked
echo ($page[$id]);
?>

OK am going to give you 3 different examples
Variables
$quotes = array (
"hello",
"baba",
"luke"
);
$pages = array(1 => 'text1-1.php', 2 => 'text1-2.php');
A. Using Random Quotes
// Using Ramdom Quptes
$key = array_rand ( $quotes );
echo $quotes [$key];
//Or
include($pages[$key]) ;
B. Using Robin
// Using Robin
$cacheFile = "robin.cache";
$robin = null;
$quotesID = intval ( file_get_contents ( $cacheFile ) );
$totalQuotes = count ( $quotes );
$key = ($quotesID < ($totalQuotes - 1)) ? $quotesID ++ : 1;
file_put_contents ( $cacheFile, $quotesID );
echo $quotes [$key];
//Or
include($pages[$key]) ;
Using Timer
// Using Timer
$cacheFile = "timer.cache";
$expiration = 3600;
$robin = null;
list($quotesID, $time) = explode(' ', file_get_contents($cacheFile));
$totalQuotes = count ( $quotes );
if($time < (time() - $expiration))
{
$key = mt_rand(0,count($pages)-1);
file_put_contents($cacheFile, time().' '.$id);
}
echo $quotes [$key];
//Or
include($pages[$key]) ;
I hope your issue can be resolved now
Thanks
:)

Related

Find records between two time slots in php

i have time slots like
$timeslot = ['09:00-10:00', .... '23:00-00:00', '00:00-01:00'];
I have records with updated time as 23:15:00, 23:30:00, 00:15:00, 09:15:00 etc.
What i'm trying to find is the sum of records between each of the $timeslot. I'm not considering what day got updated, only time i'm looking for.
i tried with:-
$data = ['23:15:00', '23:30:00', '00:15:00', '09:15:00'];
foreach($data as $val) {
$cnt = 0;
foreach($timeslot as $slots) {
$slot = explode("-", $slots);
if( (strtotime($val) > strtotime($slot[0])) && (strtotime($val) <= strtotime($slot[1])) ) {
$up_time[$slot[0] . '-' . $slot[1]] = $cnt++;
}
}
}
echo '<pre>';print_r($up_time);echo '</pre>';
The expected output is:-
09:00-10:00 = 1
23:00-00:00 = 2
00:00-01:00 = 1
Strtotime is not required since your time can be compared as strings.
This code works as you expected.
$data = ['23:15:00', '23:30:00', '00:15:00', '09:15:00'];
$timeslot = ['09:00-10:00', '23:00-00:00', '00:00-01:00'];
$up_time = array();
foreach ($data as $val) {
$myTime = substr($val, 0, 5);
foreach ($timeslot as $slot) {
$times = explode("-", $slot);
if (substr($times[1], 0, 3) == "00:") {
$times[1] = "24:" . substr($times[1], 3);
}
if ($myTime >= $times[0] && $myTime <= $times[1]) {
if (!isset($up_time[$slot])) {
$up_time[$slot] = 1;
} else {
$up_time[$slot]++;
}
}
}
}
echo '<pre>';
print_r($up_time);
echo '</pre>';
The if with 'substr' is needed because for midnight you have '00' and not '24' so the computer thinks is an empty set (such as hours bigger then 23 and smaller then 0).
Comparison is made between string because bigger time is also a bigger string since you use 2 digits for hours.
You need to count equal slots so you need an array with an element for each slot and increment if duplicate or create an element if not found (the condition '!isset').
Update for modification request
$data = ['23:15:00', '23:30:00', '00:15:00', '09:15:00'];
// added unused slot 8:00-9:00
$timeslot = ['08:00-09:00','09:00-10:00', '23:00-00:00', '00:00-01:00'];
$up_time = array();
// new initialization
foreach ($timeslot as $slot) {
$up_time[$slot] = 0;
}
foreach ($data as $val) {
$myTime = substr($val, 0, 5);
foreach ($timeslot as $slot) {
$times = explode("-", $slot);
if (substr($times[1], 0, 3) == "00:") {
$times[1] = "24:" . substr($times[1], 3);
}
if ($myTime >= $times[0] && $myTime <= $times[1]) {
$up_time[$slot]++; // simplified
}
}
}

Weighted percentage between two links?

I'm working with two rotating links in a php redirector, is there a way to weight them in percentages?
For example: The first link will have a 70% chance or getting redirected and second 30%.
Code:
<?php
$k = $_GET['sub'];
$aff[] = 'http://google.com';
$aff[] = 'http://yahoo.com';
srand ((double) microtime() * 1000000);
$random_number = rand(0,count($aff)-1);
$lol = ($aff[$random_number]);
$lal = $lol.$k;
header("Location: $lal");
?>
There are similar questions but involve more than two variables.
This seems to work.
$array = array(70 => "http://google.com",
30 => "http://yahoo.com");
$random_number = rand(0, 100);
$last_interval = 0;
$link = "";
foreach( $array as $key => $value ) {
// in range?
if($random_number > $last_interval && $random_number < $key + $last_interval) {
$link = $value;
break;
}
$last_interval = $key;
}
echo "You chose: " . $link;
Concept was taken from https://softwareengineering.stackexchange.com/questions/150616/return-random-list-item-by-its-weight and adapted slightly here is a concept that would work. Credit to #Benjamin Kloster who made the original post.
Prepare a list of intervals that cover 0 to sum(weights, 30 and 70 in your case). Each interval represents one link, its length being it's weight, so for your example:
intervals = [70, 100]
Where an index of 0-70 represents link #1, 70-100 link #2.
Generate a random number n in the range of
0 to sum(weights)
Find the interval in which n falls and you got your link.
Maybe you can do it like this:
$array = array(
array( 30, 'http://google.de/' ),
array( 70, 'http://google.com/' )
);
$number = rand( 1, array_sum( array_column( $array, 0 ) ) );
$lastsum = 0;
foreach( $array as $arr ){
if( $number > $lastsum && $number <= ( $lastsum + $arr[0] ) ){
$url = $arr[1];
break;
}
$lastsum += $arr[0];
}

Convert array result into integer for calculating

I have a little problem with an array.
I have an array which looks like this:
Array
(
[start] => Array
(
[0] => 15168
)
[ende] => Array
(
[0] => 43
)
[string] => Array
(
[0] => 1050
)
)
The number I need is 1050. So I get it like this:
$number = $tabelle['string'][0];
Now my problem is that I can't use it in calculations. I already tried to convert it into an integer with the following line:
$number = intval($tabelle['string'][0]);
But this doesn't work. I always get 0 for $number. How to do it properly? I already searched on Google for about 2 hours.
Best regards
My whole script:
<?php
class data_pars {
var $datei;
var $read_laenge = 2000;
var $result;
function set_datei($datei) {
$this->datei = $datei;
}
function read($start,$ende) {
$file = #fopen ($this->datei,"r");
while (!feof($file)) {
$inhalt .= fgets($file,$this->read_laenge);
}
if(!$start) $start = 0;
if(!$ende) $ende = strlen($inhalt);
if($ende > strlen($inhalt)) $ende = strlen($inhalt);
$this->result = substr($inhalt,$start,$ende);
}
function get_result() {
return $this->result;
}
function get_in_out($in,$out,$in_out) {
$anzahl_ende = strlen($out);
$anzahl_start = strlen($in);
$start = 0;
$anzahl = substr_count($this->result, $in);
$count = 0;
if(!$in_out) {
$ad_start = $anzahl_start;
$ad_ende = $anzahl_ende;
}
while($count < $anzahl) {
$ar_start = strpos($this->result, $in, $start);
$ar_ende = strpos($this->result, $out, $ar_start + $anzahl_start);
$ar_string = substr($this->result,$ar_start + $ad_start, $ar_ende - $ar_start + $anzahl_ende - $ad_ende - $ad_start);
$output[start][] = $ar_start;
$output[ende][] = $ar_ende - $ar_start + $anzahl_ende;
$output[string][] = trim($ar_string);
$start = $ar_start + $anzahl_start;
$count++;
}
return $output;
}
}
$data = new data_pars();
$data->set_datei('http://www.elitepvpers.com/theblackmarket/profile/6005376');
$data->read('0','20000');
$tabelle = $data->get_in_out('<td>elite*gold:</td>','</td>',false);
$number = intval($tabelle['string'][0]);
echo '<pre>';
print_r($tabelle);
echo '</pre>';
echo $number;
?>
So I always get 0 for $number instead of 1050;
You did 2 main errors:
1. You have to initialize $inhalt before your while loop like this:
$inhalt = "";
while (!feof($file)) {
$inhalt .= fgets($file,$this->read_laenge);
}
2. You forgot to put quotes around the indexes:
$output["start"][] = $ar_start;
$output["ende"][] = $ar_ende - $ar_start + $anzahl_ende;
$output["string"][] = trim($ar_string);
And now why did your intval() failed? Because if you right click and show source you will see in the array the value is:
<td>1050
So this can't convert to a int! And the <td> you don't see, because it's a html tag
Now you can easy extract only the number with this lines:
$tabelle["string"]["0"] = filter_var($tabelle["string"]["0"], FILTER_SANITIZE_NUMBER_INT);
echo $number = intval($tabelle["string"]["0"]);
Output:
1050
If I understand your code and logic correctly.
try replace:
$output[start][] = $ar_start;
$output[ende][] = $ar_ende - $ar_start + $anzahl_ende;
$output[string][] = trim($ar_string);
to this:
$
output['start'][] = intval($ar_start);
$output['ende'][] =intval( $ar_ende - $ar_start + $anzahl_ende);
$output['string'][] = intval(trim($ar_string));

Increment based on another incrementing variable

I have this odd situation and I can't think of a solution for it.
I have a variable $cat_count = 1; and I use it inside a loop and then do $cat_count++ somewhere below where I've used it.
Then I have another alphabetical counter which works the following way:
I have $alpha_string = 'abcdefghijklmnopqrstuvwxyz'; and $alpha_counter = 0;. I use this the following way - $alpha = $alpha_string{$alpha_counter}. I want my alphabetical counter to start counting from a, whenever $cat_count gets incremented by one.
So for example we would have this:
$cat_count = 1
$alpha = a
$alpha = b
$cat_count = 2
$alpha = a
$alpha = b
What I get momentarily is this:
$cat_count = 1
$alpha = a
$alpha = b
$cat_count = 2
$alpha = c
$alpha = d
Ideas?
Thank you.
following my answer in comments..
$counter = 0;
$cat_count = 1;
$alpha_count = 'abcdefghijklmnopqrstuvwxyz';
$rule_id = null;
$public_cats = array();
while ($row = $db->sql_fetchrow($result))
{
if ($rule_id != $row['rule_id'])
{
$group_ids = array_map('intval', explode(' ', $row['groups']));
$is_grouped = false;
// Check if user can see a specific category if he is not an admin or moderator
if (!$auth->acl_get('a_') && !$auth->acl_get('m_'))
{
$is_grouped = (group_memberships($group_ids, $user->data['user_id'], true)) ? true : false;
}
else
{
$is_grouped = true;
}
// Fill $public_cats with boolean values
if ($is_grouped !== false)
{
$public_cats[] = $is_grouped;
}
$rule_id = $row['rule_id'];
$template->assign_block_vars('rules', array(
'RULE_CATEGORY' => $row['rule_title'],
'ROW_COUNT' => $cat_count,
'CAN_SEE_CAT' => $is_grouped
));
$cat_count++;
$counter = 0;
}
$uid = $bitfield = $options = '';
generate_text_for_storage($row['rule_desc'], $uid, $bitfield, $options, $row['bbcode'], $row['links'], $row['smilies']);
$template->assign_block_vars('rules.rule', array(
'RULE_DESC' => generate_text_for_display($row['rule_desc'], $uid, $bitfield, $options),
'ALPHA_COUNT' => $alpha_count{$counter}
));
$counter++;
}

PHP print every second hour?

Is there a easier/better way to get every second hour than this
if(date("H")=='00'){$chart_updates = '|02|04|06|08|10|12|14|16|18|20|22|00';}
if(date("H")=='01'){$chart_updates = '|03|05|07|09|11|13|15|17|19|19|23|01';}
if(date("H")=='02'){$chart_updates = '|04|06|08|10|12|14|16|18|20|21|00|02';}
if(date("H")=='03'){$chart_updates = '|05|07|09|11|13|15|17|19|21|23|01|03';}
if(date("H")=='04'){$chart_updates = '|06|08|10|12|14|16|18|20|22|00|02|04';}
if(date("H")=='05'){$chart_updates = '|07|09|11|13|15|17|19|21|23|01|03|05';}
if(date("H")=='06'){$chart_updates = '|08|10|12|14|16|18|20|22|00|02|04|06';}
if(date("H")=='07'){$chart_updates = '|09|11|13|15|17|19|21|23|01|03|05|07';}
if(date("H")=='08'){$chart_updates = '|10|12|14|16|18|20|22|00|02|04|06|08';}
if(date("H")=='09'){$chart_updates = '|11|13|15|17|19|21|23|01|03|05|07|09';}
if(date("H")=='10'){$chart_updates = '|12|14|16|18|20|22|00|02|04|06|08|10';}
if(date("H")=='11'){$chart_updates = '|13|15|17|19|21|23|01|03|05|07|09|11';}
if(date("H")=='12'){$chart_updates = '|14|16|18|20|22|00|02|04|06|08|10|12';}
if(date("H")=='13'){$chart_updates = '|15|07|19|21|23|01|03|05|07|09|11|13';}
if(date("H")=='14'){$chart_updates = '|16|08|20|22|00|02|04|06|08|10|12|14';}
if(date("H")=='15'){$chart_updates = '|17|09|21|23|01|03|05|07|09|11|13|15';}
if(date("H")=='16'){$chart_updates = '|18|20|22|00|02|04|06|08|10|12|16|16';}
if(date("H")=='17'){$chart_updates = '|19|21|23|01|03|05|07|09|11|13|15|17';}
if(date("H")=='18'){$chart_updates = '|20|22|00|02|04|06|08|10|12|14|16|18';}
if(date("H")=='19'){$chart_updates = '|21|23|01|03|05|07|09|11|13|15|17|19';}
if(date("H")=='20'){$chart_updates = '|22|00|02|04|06|08|10|12|14|16|18|20';}
if(date("H")=='21'){$chart_updates = '|23|01|03|05|07|09|11|13|15|17|19|21';}
if(date("H")=='22'){$chart_updates = '|00|02|04|06|08|10|12|14|16|18|20|22';}
if(date("H")=='23'){$chart_updates = '|01|03|05|07|09|11|13|15|17|19|21|23';}
I need this for google charts and wanted to check if this way is stupid.
1) take the current hour
2) mod2 (there are only two different sets of numbers, odd and even)
3) build array of hours
4) sort array by value
5) split array where the original hour was, and recombine.
$h = date("H");
$line = '';
for($i=0; $i<=24; $i++)
{
if($i % 2 == $h % 2)
$line .= '|' . ($i < 10 ? '0'.$i : $i);
}
One way is to create an array with keys:
$theHour['00'] = '|02|04|06|08|10|12|14|16|18|20|22|00';
Then you can call it like this:
$chart_updates = $theHour[date("H")];
There is also probably a better way to generate this too, but since you already typed it out, its there.. It would just suck if you want to make a change.
Nice code :)
There's actually much easier way to do this in php:
$chars = array();
$start = date("H")+2;
for( $i = 0; $i < 12; $i++){
$chars[] = str_pad( ($start+2*$i)%24, 2, '0', STR_PAD_LEFT);
}
$chart_updates = '|' . implode( '|', $chars);
function helper_add($h,$plus=0){
if($h+$plus > 23){
return $h+$plus-24;
}
return $h+$plus;
}
function helper_10($in){
return $in < 10 ? '0'.$in : $in;
}
function getchartupdates(){
$now = date('G');
for($i=($now%2==0?0:1); $i<=24 ;$i+=2)
$res[] = helper_10(helper_add($now,$i));
return '|'.implode('|',$res);
}
used this to test it !

Categories