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;
}
Related
How do I save a token for each user that visits my site so that when I select the items , I use that token to get the items that the user added? I was trying to save the token into a variable but that functions runs only once . I have one table and I wont be implementing a login system yet ; this is just for guests. I want each user to have one unique token that I could use to select user's items .
I tried using session storage imgur.com/C3FhmV1 and my db imgur.com/10RjR9f but it didn't work out well.
Thank you
//
function RandomStr($length = 10)
{
session_start();
$state = $_SESSION['state'] ?? false;
if ($state) return;
$_SESSION['state'] = true;
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
$userId = RandomStr();
echo $userId;
$sql = "INSERT INTO posts (productname,productmodel,productquantity,token,productcolor,productprice)
values ('$productname','$productmodel','$productquantity','$userId','$productcolor','$productprice')";
//
Use PHP Cookies!
Whenever a user visit your site for first, set a random/unique token in their Cookies and use same to identify cart items.
Use js
<script>
if(localStorage.getItem("guestId").length() < 1 ){ //undefined || null
//means he is a new guest
localStorage.setItem("guestId",<?php echo $yourUserId;?>);
//assigned a permanent id fo the guest. valid till hard reload or browserchange.
}else{
//you already have the users unique id inside localStorage so.
var guestId = localStorage.getItem("guestId");
// use ajax here or simply reload page with
location.href = "mypage.php?user="+guestId;
}
</script>
//Note: this will raise a lot of security issue.
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)));
}
Im currently using the below code on my wordpress to display posts randomly but not duplicate them. This works apart from when I refresh the page it stays the same as it is. The only way to change what is displayed is to clear my cache and cookie. Is it possible to make it so that on each refresh it changes?
Here is my code:
session_start();
add_filter('posts_orderby', 'edit_posts_orderby');
function edit_posts_orderby($orderby_statement) {
$seed = $_SESSION['seed'];
if (empty($seed)) {
$seed = rand();
$_SESSION['seed'] = $seed;
}
$orderby_statement = 'RAND('.$seed.')';
return $orderby_statement;
}
Remove the if condition, in current situation - rand option set only if the session is empty. So that it working at first time i.e session not set.
$seed = rand();
$_SESSION['seed'] = $seed;
instead of
if (empty($seed)) {
$seed = rand();
$_SESSION['seed'] = $seed;
}
you can try out like
session_start();
session_regenerate_id();
echo session_id();
This returns you with unique session ids on each refresh
I'm trying to simulate The words game in as3.
The same random characters or all users and 2 minutes countdown is needed
I've a code That generate 25 random characters. How Can I Show The Random Characters For all Users ?
<?PHP
function randStr($rts=20) {
$act_chars = "ABCÇADAEFGĞHEIİJKELMNOAÖPRKSŞTUÜVYZ";
$act_val = "";
for($act=0; $act <$rts ; $act++) {
mt_srand((double)microtime()*1000000);
$act_val .= mb_substr($act_chars, mt_rand(0, mb_strlen($act_chars)-1), 1);
}
return $act_val;
}
$dene = randStr(25);
print "izinliharfler=$dene";
?>
maybe I need to use cron job, I do not know
You Can Store The Generated string (Characters String) In A Table,
Then Create An ajax call To Pull It For All Users.
You can use ip address of the user and then change seed accordingly.
<?PHP
function randStr($rts=20,$ip) {
$act_chars = "ABCÇADAEFGĞHEIİJKELMNOAÖPRKSŞTUÜVYZ";
$act_val = "";
for($act=0; $act <$rts ; $act++) {
mt_srand((double)microtime()*1000000+$ip);
$act_val .= mb_substr($act_chars, mt_rand(0, mb_strlen($act_chars)-1), 1);
}
return $act_val;
}
$ip = ip2long($_SERVER['REMOTE_ADDR']);
$dene = randStr(25,$ip);
print "izinliharfler=$dene";
?>
I am selling a subscription viewing service. Once people have paid they get a unique URL e-mailed to them. The link is set to expire after a certain time but I'd like to only allow the first three IP addresses to use the link before it expires to stop piracy. I'm doing it like this to avoid having yet another database running holding thousands of logins. I assume I can write to a directory and have a filename as the suffix of the link (zFZpj4b2AkEFz%2B3O in this case) with up to three IPs listed in the file.
It all works well so far barring the IP address counting and the unique link the e-mail looks like this:
http://www.blah.com/download.php?file=zFZpj4b2AkEFz%2B3O
The file download.php looks like this:
<?
$time = time();
include('settings.php');
class RC4Crypt {
/**
* Encrypt the data.
* #param string private key.
* #param string data to be encrypted.
* #return string encrypted string.
*/
function encrypt ($pwd, $data)
{
$key[] = '';
$box[] = '';
$pwd_length = strlen($pwd);
$data_length = strlen($data);
for ($i = 0; $i < 256; $i++)
{
$key[$i] = ord($pwd[$i % $pwd_length]);
$box[$i] = $i;
}
for ($j = $i = 0; $i < 256; $i++)
{
$j = ($j + $box[$i] + $key[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
}
$cipher = '';
for ($a = $j = $i = 0; $i < $data_length; $i++)
{
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $tmp;
$k = $box[(($box[$a] + $box[$j]) % 256)];
$cipher .= chr(ord($data[$i]) ^ $k);
}
return ($cipher);
}
/**
* Decrypt the data.
* #param string private key.
* #param string cipher text (encrypted text).
* #return string plain text.
*/
function decrypt ($pwd, $data)
{
return RC4Crypt::encrypt($pwd, ($data));
}
}
if(!isset($_GET['file']) || empty($_GET['file'])) {
echo 'Invalid Request';
return;
}
$data = $_GET['file'];
$id_time = RC4Crypt::decrypt($secret,base64_decode(rawurldecode($data)));
list($product_id,$timestamp) = explode('|',$id_time);
if(!isset($products[$product_id])) {
echo 'Invalid Request';
return;
}
if ($timestamp < $time - ($download_life * 60 )) {
echo 'Link Expired';
return;
}
if(isset($products[$product_id])) {
print ("<html><head><meta http-equiv=Refresh content=\"0;URL=http://www.blah.com/view/\"></head><body></html>");
return;
}
?>
Can any kind soul take pity on someone who has spent far too long looking at this already please ? :) Thanks very much.
--EDIT --
A thought: Forgetting the 3 IPs what about storing a Server-side cookie when the link is pressed the first time and denying access if it exists ?
To do this, you have to create a table for each subscription.
table subscription: subId, subCode, subVisitTimes, subVisitedIP
subCode will be something like zFZpj4b2AkEFz%2B3O
for each visit, you get client's IP using $_SERVER['REMOTE_ADDR'].
If it does exist in subVisitedIP then allow access.
If it does not exist then check subVisitTimes value:
if subVisitTimes = 3 then deny access
If subVisitTimes < 3 then allow access and increase its value by one also add client's IP to subVisitedIP (you should use serialize function to store array of three IPs).
You're going to want to set up a simple database for this. You only need one row - the hash/id, the original IP, expired, etc and can simply set expired to 1 when access runs out. This way you're not running costly DELETE queries, and if need be you can simply delete those rows all at once a couple times a month to save space.
Otherwise it's going to get too complex and more error-prone using flatfiles.