php/ajax random characters and countdown - php

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";
?>

Related

Generating a Non-Repeating Random Number - PHP

I'm trying to get a custom function in php to return a random number between 1 and 20 that does not repeat i.e. produce the same number more than once, since I need to subsequently use this number to navigate to one of twenty web pages, and I don't want the same web page displayed.
Here is my code in three steps:
<form action="rand.php">
<p>Click this button to display a random number that does not repeat...</p>
<p><input type="submit" value="Generate"></p>
</form>
Here is rand.php:
require_once('functions.php');
$page = generateNumber();
echo $page;
Here is functions.php:
<?php
$check = array();
function generateNumber() {
global $check;
$page_no = mt_rand(1,20);
$check[] = $page_no;
if (count($check) != 1) {
foreach ($check as $val) {
if ($val == $page_no) {
$page_no = mt_rand(1,10);
continue;
}
}
return $page_no;
}
else {
return $page_no;
}
}
?>
My code seem to be functioning, however, it is repeating numbers so I am obviously doing something wrong. The reason I initially check the count is so that is returns the first number regardless, since it would be a single fresh number.
In order to see the number change I have been refreshing the rand.php page in my browser.
I would keep it simple.
// List numbers 1 to 20
$pages = range(1,20);
// Shuffle numbers
shuffle($pages);
// Get a page
$page = array_shift($pages);
In order to go through all the 20 numbers on each page visit, without repeating, you will need to set a session variable.
<?php
session_start();
if (!isset($_SESSION['numbers'])) {
$_SESSION['numbers']="*"; //---create the session variable
}
function get_number() {
$i = 0;
do {
$num=rand(1,20); //---generate a random number
if (!strstr($_SESSION['numbers'],"*".$num."*")) { //---check if the number has already been used
$_SESSION['numbers']=$_SESSION['numbers'] . $i . "*"; //---add the number to the session variable to avoid repeating
if (substr_count($_SESSION['numbers'],"*")>=21) { //---resets the session variable when all 20 number have been used
$_SESSION['numbers']="*";
}
$i=$num; //---ends the while loop to return the value
}
} while ($i==0);
return $i;
}
?>

Loop to check dupilicate random strings

I have this function which creates random string:
function genID($length) {
$chars = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM#!";
//only allowed chars in the blowfish salt.
$size = strlen($chars); $str = "";
for ($i = 0; $i < $length; $i++)
$str .= $chars[rand(0, $size - 1)]; // strings can be used as char arrays
// Yes, I am aware this salt isn't generated using the OS source.
// use mycrypt_create_iv or /dev/urandom/
return $str;
}
This output something like:
#iBUQvldLq
Now I have users list with something like that:
userid | username | usermail ...
--------------------------------------
#iBUQvldLq test test#gmaik.com ....
Now when some one register I create new string and insert the new string to userid row in database, after that I create a new string, then I check if the new string created doesn't exist, something like this:
function newID()
{
$newid = genID(10);
$query = "SELECT * FROM users WHERE userid = '".$newid."'";
$result1 = mysql_query($query);
$num = mysql_num_rows($result1);
if($num == 1)
{
$newid = genID(10);
return $newid;
}
else
{
return $newid;
}
}
Any one have any idea how to loop on the check function?
I mean the generate function create new random string, then the function check if it already exist, then create new one, if not return the one created.
So now if he create new one, and the new one also match the same other userid, so how I loop until the new string won't match never to other userid string?
Something like loop:
create new string
verify if exist
if exist create new one
if the new one also exist create new one and so on
Till its never match other userid, make a loop, any idea ?
EDITED :
The new function for loop if any need:
function newID(){
$continue = true;
while ($continue) {
$newid = genID(10);
$query = mysql_query("SELECT * FROM users WHERE userid='".$newid."' LIMIT 1");
if (mysql_num_rows($query) != 1)
$continue = false;
return $newid;
}
}
$newid = newID();
It looks like your wanting code like this..
function uHash(){
$continue = true;
while ($continue) {
$hash = substr(MD5(microtime()), 0, 7);
$query = mysql_query("SELECT `Link` FROM Table WHERE `value`='$hash' LIMIT 1");
if (mysql_num_rows($query) != 1)
$continue = false;
return $hash;
}
}
The script will loop until it finds a unique value.
Setting your user_id column as an auto_increment field would solve this issue. [Best Approach]
If you really want to do with PHP, couple uniqid() with rand() to generate a unique seed that doesn't collide.
Something like this
<?php
echo $id = uniqid(rand(), true);
?>
Just you can use for unique id
<?php
function genID() {
return uniqid();
}
echo genID();
?>

how to generate unique session ID without the use of session_id()?

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;
}

Advanced PHP: Allow a unique URL to be clicked by the first three IPs only

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.

How do I block a user temporarily

I want to block visitor between 2 to 5 minutes every 100 view.. if user view 100 page between 2 to 5 minutes then block user, if user view 100 view in 6 minutes then don't block and reset the counter.
I already create the counter script but i have issue with creating the function which can block visitor between 2-5 mint.
I need help to fix this problem... I try to create a if condition but no luck.. help me please...
$sb_current_time = date("Y-m-d H:i:s", Time());
/////////////////// Cookies Encryption //////////////
function encrypt($text)
{
$key = "E4HD9h4DhS23DYfhHemkS3Nf"; // 24 bit Key
$iv = "fYfhHeDm"; // 8 bit IV
$bit_check = 8;
$text_num = str_split($text, $bit_check);
$text_num = $bit_check - strlen($text_num[count($text_num) - 1]);
for ($i = 0; $i < $text_num; $i++) {
$text = $text . chr($text_num);
}
$cipher = mcrypt_module_open(MCRYPT_TRIPLEDES, '', 'cbc', '');
mcrypt_generic_init($cipher, $key, $iv);
$decrypted = mcrypt_generic($cipher, $text);
mcrypt_generic_deinit($cipher);
return base64_encode($decrypted);
}
//////////////// Encription end /////////
////// Cookies decription /////
function decrypt($encrypted_text)
{
$key = "E4HD9h4DhS23DYfhHemkS3Nf"; // 24 bit Key
$iv = "fYfhHeDm"; // 8 bit IV
$bit_check = 8;
$cipher = mcrypt_module_open(MCRYPT_TRIPLEDES, '', 'cbc', '');
mcrypt_generic_init($cipher, $key, $iv);
if ($encrypted_text != "") {
$decrypted = mdecrypt_generic($cipher, base64_decode($encrypted_text));
mcrypt_generic_deinit($cipher);
$last_char = substr($decrypted, -1);
for ($i = 0; $i < $bit_check - 1; $i++) {
if (chr($i) == $last_char) {
$decrypted = substr($decrypted, 0, strlen($decrypted) - $i);
break;
}
}
}
return $decrypted;
}
///////// Coookies decription end /////////////////
//$sb_check_ban_time = date($sb_current_time, strtotime("+20 minute"));
if ($_COOKIE['spamer_check_time'] == "") {
setcookie('spamer_check_time', encrypt(time()));
}
function time_deff($date2)
{
$date1 = time();
//sleep(2000);
// $date2 = decrypt($_COOKIE['spamer_check_time']);
//echo $date2;
$mins = ($date1 - $date2) / 60;
//echo $mins;
return $mins;
}
//$sb_cookie_expiration = time() + 1200;
//echo $sb_cookie_expiration;
if ($_COOKIE['view2'] != "") {
$explod = explode("-", decrypt($_COOKIE["view2"]));
}
$i_print = $explod[0];
// $i2=$explod[1];
//echo $i2;
$i = 1 + $i_print;
setcookie("view2", encrypt($i . "-123456789")); //// Need to add extra bit to block unwanted text and secure the cookes more..
//
$i = $i++;
// echo $i_print;
//echo "empty".decrypt($_COOKIE["spamer_check_time"]);
$spammer_blocker = decrypt($_COOKIE["spammer_blocker"]);
// or $spammer_blocker==""
$mins = time_deff(decrypt($_COOKIE['spamer_check_time']));
$diff_time = .1; /// User BLock Time
if ($mins >=1 or $mins <=2) {
$block_user=1;
} elseif ($mins >= 2.1) {
$block_user=2;
} else {
}
/* if (.2>$mint) {
// echo "not done";
$block_user=0;
} elseif (.2 <= $mint) {
echo "block User";
$block_user=1;
} elseif ($mins>=1) {
echo "reset cookies";
$block_user=2;
}*/
if ($block_user==1 and $i_print >= 15) {
if ($spammer_blocker == "") {
setcookie("spammer_blocker", encrypt(time()));
header('HTTP/1.1 403 Forbidden');
$time_rev = $diff_block_time - $diff_time;
$round_time = round($time_rev, 2);
$time_reverse = str_replace('-', '', $round_time);
echo "Wait " . $time_reverse . " Minuts before using this site..";
exit(0);
} else {
//$sb_check_ban_time = $spammer_blocker;
$diff_block_time = time_deff($spammer_blocker);
//echo $diff_block_time;
//$sb_check_ban_time = date($spammer_blocker, strtotime("+1 minute"));
if ($diff_time <= $diff_block_time) {
/// echo "Delete the IP and cookies";
setcookie("spammer_blocker", "");
setcookie("view2", "");
setcookie("spamer_check_time", "");
} else {
//echo "Still Block"; /// echo "Still Block";
header('HTTP/1.1 403 Forbidden');
// echo "IP Block for Spaming wait few mint";
$time_rev = $diff_block_time - $diff_time;
$round_time = round($time_rev, 2);
$time_reverse = str_replace('-', '', $round_time);
echo "Wait " . $time_reverse . " Minuts before using this site..";
exit(0);
}
}
} elseif ($block_user==2) {
setcookie("spammer_blocker", "");
setcookie("view2", "");
setcookie("spamer_check_time", "");
echo "cookies reset";
} else {
}
First, you need to know who they are...
For casual users, you can rely on cookies. But if you are having problem with an abuser, then they will simply ignore your attempt to stop them and not send a cookie.
There are various levels of knowing "who" someone is.
ID in URL
Cookies
IP Address
And they can ALL be overcome with different levels of diffulculty...
Way too easy (just spoof a different ID, etc...)
Cookies are the same as #1
IP addresses are harder to overcome unless you have a botnet or similar
For your case, you should likely block the IP address as it's the only reasonable way for you to get done what you are looking for.
--
Next, you need to be able to keep track of their connections. iptables in Linux has a way to track the number of connections and block for a specific number of minutes after a certian threshold is reached.
Using only PHP, you need to record each hit, and the IP address of that hit. An SQL database would be one of the more efficient ways of doing this.
If you don't care about history, then simply (mysql):
INSERT INTO HitTable SET IP=..., Visits=1
ON DUPLICATE KEY UPDATE Visits=Visits+1
A background crontab could run a query like this every minute?
UPDATE HitTable SET Visits = Visits - 10
DELETE FROM HitTable WHERE Visits < 1
Finally, when a visitor visits, you would check the database table for
SELECT Visits<100 WHERE IP=...
AND if that returns True, let them in, else block them.
Hope this helps a bit.
Storing the timeout value in a cookie will be absolutely trivial for a user to change/delete the cookie
Storing it in a session variable is a bit more reliable, but again - the user could just delete the session cookie, get a new session going, and start reading again.
That being said, you'd do something like this:
<?php
session_start();
if (user_should_be_blocked()) {
$_SESSION['blocked_start_time'] = time();
header("Location: timeout.html");
}
if ($_SESSION['blocked_start_time'] > (time() - 300)) {
header("Location: timeout.html");
}
// got here, must not be blocked and/or timeout has expired
$_SESSION['blocked'] = false;
$_SESSION['block_start_time'] = null;
.... continue on
I would use the header funciton to redirect them to another page, either empty or just less bankwidth intensive (assuming that's why you're making this anyway). Soemthing like...
if ($block_user == 1)
header("Location: blockPage.php");
At the top of all pages you need to block.
Edit: actually, come to think of it, (2) is of course not necessary, if 2 people or 2 computers are logged in they'll only consume their alloted amount of views faster..
You can do this provided:
A user needs to be logged in to see the pages.
You don't allow the same user(name) to be logged in twice with different sessions.
You store the count per-user, not per-session or per-ip/whatever.
(2) is not possible with default file based sessions. A custom database or other persistent storage solution is needed in which you can scan for other session-id's of a current user-id. In a database you would just store a user-id field, a custom memcached solution could also be built, etc. To prevent users being locked out of a session they no longer have my solution was always to destroy any old session a user had the moment they log in. Effectively, if it's tried with multiple sessions/ips, they'll have to log in again and again invalidating the previous session.
(3) again some persistent storage with a timestamp+userid+count (in MySQL's case an INSERT INTO tablename (user_id,time,count) VALUES (<id>,NOW(),1) ON DUPLICATE KEY UPDATE count=count+1 comes to mind to easily increment view counts.
And on every view query the database again and again about how many views the visitor had the last X minutes.

Categories