Since couple of days, i have a problem with my function who generate a random id.
Here is the function :
public static function generatePin($max)
{
$key = "";
$possibilities = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$possibilities .= "abcdefghijklmnopqrstuvwxyz";
$possibilities .= "0123456789";
$i = 0;
while ($i <= $max) {
$detail = Tools::substr($possibilities, mt_rand(0, Tools::strlen($possibilities)-1), 1);
$key .= $detail;
$i++;
}
return $key;
In my file, when i want to use this function, i used to do that (works fine since many months) :
$this->my_secure_pin = Tools::encrypt(Class::generatePin(7));
Now, my variable "secure_pin" can't change.. I always have the same ID and it doesn't want to change as it used to do.. My random ID become a same ID for every request.. Grrrr
Here an example :
1/ I go on my page, my variable "secure_pin" is 622c7da19ec263b59f452b9fc5.
2/ I refresh my page, my variable "secure_pin" is always 622c7da19ec263b59f452b9fc5
3/ I leave my page and i come back to her, my variable "secure_pin" is always 622c7da19ec263b59f452b9fc5
4/ If i empty cache, my variable "secure_pin" is changing !..
=> So, when many persons come to my page, they have all the same "secure_pin"... :-(
I want (as couple days ago) a secure_pin for every persons who come on this page, a changing "secure_pin" if i refresh page or if i come back to her etc..
No changes, No updates, nothing.. Any idea ? :'(
Many thanks for your help !
EDIT 1 : Here is the "encrypt" function :
public static function encrypt($passwd)
{
return md5(pSQL(_COOKIE_KEY_.$passwd));
}
EDIT 2 : Here is the "substr" function :
static function substr($str, $start, $length = false, $encoding = 'utf-8')
{
if (is_array($str))
return false;
if (function_exists('mb_substr'))
return mb_substr($str, (int)($start), ($length === false ? self::strlen($str) : (int)($length)), $encoding);
return substr($str, $start, ($length === false ? self::strlen($str) : (int)($length)));
}
Related
I have a url with a page system.
For instance https://myURL?p=50
But I want a script to find the last page available, for instance, let's say p=187
I have a function checkEmpty() that tells me whether the page is empty or not.
So for instance:
$myUrl = new URL(50); //https://myURL?p=50
$myUrl->checkEmpty();
//This evaluates to false -> the page exists
$myUrl = new URL(188); //https://myURL?p=188
$myUrl->checkEmpty();
//This evaluates to true -> the page does NOT exist
$myUrl = new URL(187); //https://myURL?p=187
$myUrl->checkEmpty();
//This evaluates to false -> the page exists
I did a naive algorithm, that you might guess it, performs too much requests.
My question is:
What would be the algorithm to find the last page with the minimal amount of requests?
EDIT
As requested by people in the comment here is the checkEmpty() implementation
<?php
public function checkEmpty() : bool
{
$criteria = "Aucun contenu disponible";
if(strstr( $this->replace_carriage_return(" ", $this->getHtml()), $criteria) !== false)
{
return true;
}
else
{
return false;
}
}
Since the upper bound is not known, exponentially increase the page no by 2 starting from 1. The moment you hit a non-existent page, you can do a binary search from previous existing page + 1 till this new upper bound where the page doesn't exist.
This way, you can get your answer in O(log(n)) attempts asymptotically where n is the no. of existing pages here as the sample space.
<?php
$lowerBound = 1;
$upperBound = 1;
while(true){
$myUrl = new URL($upperBound);
if($myUrl->checkEmpty()){
break;
}
$lowerBound = $upperBound + 1;
$upperBound <<= 1;
}
$ans = $lowerBound;
while($lowerBound <= $upperBound){
$mid = $lowerBound + (($upperBound - $lowerBound) >> 1);
$myUrl = new URL($mid);
if($myUrl->checkEmpty()){
$upperBound = $mid - 1;
}else{
$lowerBound = $mid + 1;
$ans = $lowerBound;
}
}
echo $ans;
bit of a strange one that I've not been able to resolve for months so I finally have given in and have come here for the answer. Hopefully.
I have the below shortcode that when ran returns the phone number depending on what variable has a value. This PHP code works as expected, the one thing that doesn't work as expected however, is the first ever page load.
When someone goes to the site for the first time (or in incognito mode) the shortcode doesn't output anything, however, refresh the page just once and it'll display the output of the correct value and I have no idea why.
<?php function gw_cookie($atts) {
extract(shortcode_atts(array(
"value" => ''
), $atts));
$getVariable = isset($_GET[$value]) ? $_GET[$value] : '';
$newGetVariable = str_replace('_', ' ', $getVariable);
$cookiePhone = isset($_COOKIE[$value]) ? $_COOKIE[$value] : '';
$acfField = get_field('page_cookie_'.$value.'');
$optionsACF = get_field('options_company_details', 'options');
$area = $optionsACF['options_area'];
$phone = $optionsACF['options_telephone'];
if(!empty($cookiePhone) && $cookiePhone !== 'undefined') { //If cookie is not empty do the following
echo '1';
} elseif(!empty($newGetVariable)) { //If cookie is empty and get variable is not
echo '2';
} elseif($acfField) { //If ACF field is not empty do the following
echo '3';
} elseif ($value == "phone") {
return '4';
}
} add_shortcode("gw-cookie", "gw_cookie");
This codes file is being imported into the functions.php file using the following line:
require_once( __DIR__ . '/shortcodes/gw-cookies.php' );
A cookie itself would be created on the first run and your criteria requires cookiePhone which is why you have to refresh to make it work.
As per the comments, change:
$cookiePhone = isset($_COOKIE[$value]) ? $_COOKIE[$value] : '';
to:
$cookiePhone = isset($_COOKIE[$value]) ? $_COOKIE[$value] : NULL;
I'm not really understanding why this is, but Pager is producing paginated results like the following:
http://www.mywebsite.ca/reports-publications/reports/?field_executive_summary_value=&field_publication_date_value[value]&field_report_type_tid_selective=All&field_natural_resource_region_tid_selective=All&field_forest_district_tid_selective=All&field_keywords_tid_selective=All&page=1#
Instead of simply:
http://www.mywebsite.ca/reports-publications/reports/?page=1
Additionally, "page=1" represents the second page ... as in an array of pages where 0 is actually the first result.
Does anyone know why Pager is producing links like this?
I was able to fix the page number issue by altering pager.inc file.
in pager_find_page function,
function pager_find_page($element = 0) {
$page = isset($_GET['page']) ? $_GET['page'] : '';
$page_array = explode(',', $page);
if (!isset($page_array[$element])) {
// Change here
// $page_array[$element] = 0;
$page_array[$element] = 1;
}
// Add this
$page_array[$element]--;
return (int) $page_array[$element];
}
and, in theme_pager_link function,
if ($new_page = implode(',', pager_load_array($page_new[$element], $element, explode(',', $page)))) {
// Change here
// $parameters['page'] = $new_page;
$parameters['page'] = $new_page + 1;
}
I want to generate a session ID. This unique sessionId represents some different data for every different user.
My code till now:
onclick and onload of a page I call a function create_session_id();
function create_session_id() {
// This function sends a string to a PHP page using ajax post.
}
On my PHP page, I receive this data and then insert it:
session_start();
$a = session_id();
$object->insert_sessionid($a);
My Question
Is it possible to use only session_start() (no session_id()) and store some unique session ID value that I can use later when I fetch data and throw data to my web page. I don’t want any clicks to register sessionid. It should happen on page load and without any function create_session_id().
I am thinking to bring some cookies in to the picture.
Note: My website doesn’t allow login.
use a function like
function createRandomVal($val){
$chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,-";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i<=$val)
{
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
and pass return value in session id
The above code is a little bit buggy since user669677 has edited it.
Here is the proper code:
function createRandomVal($val) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,-";
srand((double)microtime() * 1000000);
$i = 0;
$pass = '';
while ($i < $val) {
$num = rand() % 64;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
I'm in PHP working on an Euler problem. I have this function so far:
<?php
$biggest = 0;
$counter = 1;
function test($i){
global $biggest;
global $counter;
if ($i == 1) {
echo "I'm done! Took me $biggest steps";
}
else {
if ($i%2 == 0) {
$counter = $counter + 1;
if ($counter>$biggest) {
$biggest = $counter;
}
test($i/2);
}
else {
$counter = $counter + 1;
if ($counter>$biggest) {
$biggest = $counter;
}
test(3*$i+1);
}
}
}
test(13);
?>
I have the problem mostly licked, but I can't seem to get back at the original input. The question is "When you have a number, if odd get 3n+1, when even, get n/2, do until returns 1. What starting value yields the most "steps" before you get to one?" I currently am returning the number of steps, but I keep resetting $i as I recurse, so I can't record what starting # yielded my $biggest number of steps.
How can I keep track of that number, but also not have it destroyed at the next instance of the loop? (I'll eventually wrap this in a for ($i=1, $i<1000000, $i++) loop)
Thanks!
A common approach is to pass the original argument through each time, so that when eventually you get to your base case, you still have it available. A primitive (and almost entirely unrelated example):
<?php
function fact($n) {
if($n == 1) return 1;
else return $n * fact($n - 1);
}
?>
This is an extremely basic implementation of the factorial function in PHP. Now say you wanted for whatever reason to have the initial value available in the final step: you'd build a wrapper function fact($n) that would call something like memory_fact($n, $initial):
<?php
function fact($n) {
return memory_fact($n, $n);
}
function memory_fact($n, $initial) {
if($n == 1) return 1;
else return $n * memory_fact($n - 1, $initial);
}
?>
This way, memory_fact always knows where it started.
It's easy, just pass it around as a parameter! Here's some python-ish pseudocode:
def func(start, arg):
if foo(arg):
return func(start, arg+1)
else:
return [start, arg]
You don't need the globals; globals are evil. Try returning something useful from test(). Also, you'll find the test() above wastes many cycles. Try using memoization.
Here's a memoization example for calculating Fibonacci numbers:
function fib($n) {
static $data = array(1, 1);
if (!isset($data[$n])) {
$data[$n] = fib($n-1) + fib($n-2);
}
return $data[$n];
}
Note that there are other time-efficent constant-space approaches to handle Fibonacci numbers (including one in O(log n) time), but the Collatz conjecture is a little trickier.