I have been trying to write a code in PHP that generates a random code, stores it in the database and asks the user to enter it. if the code is entered more than 3 times, the code needs to be expired. this is my code:
<?php
include("ProcessCode.php");
$con = mysqli_connect("localhost","root","") ;
if(mysqli_select_db($con,"login"))
{
echo 'database selected' ;
}
$rand=rand();
echo $rand ;
$sql = "INSERT INTO random (number) VALUES ('$rand') " ;
if(mysqli_query($con,$sql))
{
echo 'inserted' ;
}
?>
$CodeCheck=$_POST['code'];
//Establishing Connection with server
$conn = mysqli_connect("localhost", "root", "");
//Selecting Database
$db = mysqli_select_db($conn, "login");
//sql query to fetch information of registerd user and finds user match.
$query = mysqli_query($conn, "select * from random WHERE number='$CodeCheck'");
$rows = mysqli_num_rows($query);
if (mysqli_num_rows($query) > 0)
{
echo " Code exists already.";
}
if($rows == 1)
{
header("Location: Success.php");
}
else
{
$error = " Code is Invalid";
echo $error;
}
could you please explain how to implement the expiry part?
in your table you could have a field for count. When use login and login is wrong, add + 1 to your count. When user login successfuly, reset the count. If count meet +3, reset the code.
i understand from your question that you need the logic on how to make the random_code expired after inserting from interacted users on your website 3 times ,assuming that , as long as the code is not expired he will be able to do his inserts and you may load it on your page .
i would do that through database queries .
Please follow this instruction listed below
instructions :
while your php page generate the random code , you may store it in database table with a auto reference key , for instance ,
assuming that you have randomly generated a code as below :
"Some random code here"
the above code which was generated by your php page have load it from mysql table called Random_Generated_Code , i would go to edit this table and add new field in it and call it generated_Code_Reference_Key ( could be auto serial number ) to avoid any duplication as well make additional field called Expire_Flag which we are going to use later.
so once your page have loaded the above example code , you should retrieve the generated_Code_Reference_Key along with it and keep it in hidden variable on your page
it should be loaded on the page based on expire_Flag value as a condition
select generated_code from Random_Generated_Code where expire_flag = ""
now once the user try to insert that generated code , in each time he insert it define another table in your database lets call it ( inserted_Codes_by_users) and store in it the username of whoever is doing that on your website as well you have to store the generated_Code_Reference_Key which we are storing in hidden variable as mentioned earlier to indicate which code was used while inserting.
now during page load or any event you want you can find expired code by make select statement from the inserted_Codes_by_users table
select count(generated_Code_Reference_Key) as The_Code_Used_Qty from inserted_Codes_by_users where username = username_of_that_user
so you can get how many times this user have inserted this specific generated_random_Code
retrieve result of the query in a variable and to make sense lets call it The_Code_Used_Qty and make if condition on page load event or any event you like
if The_Code_Used_Qty = 3 then
fire update statement to first table which loaded that random generated code
and update the expire_flag field for that code (Expired) based on reference_key
update Random_Generated_Code set expire_Flag = "expired" where generated_Code_Reference_Key = "generated_Code_Reference_Key" << the one u stored in hidden variable
end if
so now that will get you directly to the point of why we are loading random_generated_code table first time with that condition expire_flag = ""
as it will only retrieve the codes which is not expired .
hopefully this will help you to achieve what you want .
good luck and let me know if you need any help or if you face any confusion while reading my answer.
Good luck .
In my MySQL database you login via the game and then type your username in on the site and see your stats. This is my information snippet from my API.
elseif ($_GET['task'] == 'login') {
$get_user = $_GET['user'];
$get_db = 'engine';
$result = mysql_query("SELECT * FROM $get_db WHERE name = '" . mysql_real_escape_string($get_user) . "'", $link);
while($data = mysql_fetch_array($result)) {
echo '{"task":"login","password":"'; echo $data['hash'];
echo '","lastip":"'; echo $data['lastip'];
echo '","timestamp":"'; echo $data['logindate'];
echo '"}';
}
}
I am trying to add a line of text under the search textbox on the homepage that will pop up if your IP recently logged into a server. It'll say "Hey, aren't you username?"
What type of code would be required to do this? I would need to call upon their IP, and search the database for all users who have authenticated with it, and then make sure to display the latest one based on their timestamp.
You can use both $_SERVER['REMOTE_ADDR'] and $_SERVER['HTTP_X_FORWARDED_FOR'] to get the public IP and sometimes (with the second case) the private IP.
By the way, notice that old mysql_*() functions are deprecated as of PHP 5.5. You should use the mysqli or PDO_MySQL extensions.
$_SERVER['REMOTE_ADDR'] will give you the IP address of the person viewing the page.
From there you just need to compare it to the lastip field in your query.
$userIP = $_SERVER['REMOTE_ADDR'];
$query = "SELECT * FROM ".$get_db." WHERE lastip = ".$userIP." ORDER BY logindate DESC LIMIT 1";
Or something along those lines.
You could use the $_SERVER['REMOTE_ADDR'], which contains the IP of the viewer.
Then you could run
SELECT name FROM 'users' where users.known_ips LIKE '%$ip%' AND users.loggedin = 0 ORDER BY lastlogin DESC LIMIT 1;
('%' represents 0 or more characters. It's a wildcard.) And then you could use
mysqli_stmt_bind_results($ipquery,$name);
mysqli_stmt_fetch($ipquery);
# Now $name = first username found
This method will get their name if they have ever used that computer to log in.
I am capturing the visitors ip address during a form submit using the following.
$users_ip=$_SERVER['REMOTE_ADDR'];
What I would now like to do is see if this ip variable has been used before when submitting a comment, can anyone point me in the right direction?
Maybe a like SQL command?
Assuming you stored client ips in the table named: "ips" then use this:
$connection = mysql_connect($your_db_host, $your_user_account, $your_password);
$mysql_select_db($your_db_name);
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "select 1 from `ips` where `ip`='$ip'";
$sql_resource = mysql_query($sql);
$mysql_close($connection);
if($sql_resource && mysql_num_rows($sql_resource) > 0){
// your logic code if the ip existed in the db
echo 'The ip has been used before';
} else {
// code if the ip not existed in the db
echo 'The ip has not been used before yet';
}
There is a good tutorial explaining how to store IP addresses in MySQL. In short, convert them to long like suggested in this comment, then use simple SELECT statement to find it:
"SELECT COUNT(*) FROM comment WHERE ip = " . ip2long($_SERVER['REMOTE_ADDR'])
Sorry for the vague, title! I have a website with a lot of PDF files and limited monthly bandwith. What i would like to achieve (in PHP) is a way to limit each user ($_SESSION?) to a certain limit - say 50MB, and beyond that when they clicked to download another file they would be redirected to a webpage denying any further downloads (for the next 24 hours, say).
Is this possible? I'm not sure if my download "counter" can only count .pdf files (I dont want vistors to be blocked from browsing the site if they reach the limit). Any psuedo code would be greatly appreciated.
If you have all of your downloads go through a single php script:
<a href="download.php?file='filename.pdf'" />
You can do pretty much whatever you want. That php file can deliver all of your files (keeping them out of the webroot), write to your _SESSION, and it can perform your redirect. Enjoy.
If you already have a user system, I would recommend to store all information within the users profile.
So there's no problem if he deletes all his cookies and relogins!
And for guests, I would recommend captchas and session or IP based restrictions.
// Pseudo code
// download.php
function UserHasReachedLimit($file)
{
$info = $Database->QueryUserInfo('limit');
$max = $Database->GetLimitForFile($file);
if ( $info[$file] > $max )
return false;
else
return true;
}
if ( IsUser() )
{
if ( UserHasReachedLimit() )
error();
else
download();
}
else // guest
{
// session or IP based restrictions...
}
I'd probably stay away from sessions for this. Sessions are volatile and susceptible to various browser behavior. For example, in Firefox if a session is initialized, I can close Firefox, visit the same site, and session is still active. However in IE if I open up multiple tabs and visit the same site, each tabbed instance gets a new session id.
I'd recommend setting up an account system where a user has to log into your site. Then you can track their download amount at the account level, which will persist between multiple sessions.
I think you are trying to avoid forcing user to register in your site, while you are trying to track per visitor bandwidth with is unpractical with the common ways(cookies, ip ...). So, the best way(in my opinion, of course there are many improved solutions) is to make a simple registration form, say name, password and email, put an activation system per email to protect your site from of user, now each user logged in and tried to download a file, you process his request in the following steps:
1) user request for file name.pdf (check its availability and size(important)).
2) check user bandwidth:
$query = sql_query("SELECT Bandwidth, LastDownload FROM Users, Stats WHERE USER_ID=5");
$result = sql_fetch($query);
if ($result['Bandwidth'] < 50M)
showDownloadLink();
else if($result['LastDownload'] - currentTime() !=0)
echo "please wait to the next 24h";
Database should be like this:
Users:
ID_U int(key, auto increment), Name varchar(25), email varchar(255), password varchar(32), Bandwith float
Stats:
ID_S int(key, auto increment), LastDownload time, ID_U integer
Note:
Each time user download a file, you update Bandwidth row for the right user, so later you can check if particular user reach its limit or not. You have also to reset it after each 24H.
This is a generic solution and many thinks have to be checked, like the counter bandwidth must be reset every 24H.
Create a table to store count downloads
CREATE TABLE IF NOT EXISTS `downloaded` (
`ip` varchar(200) NOT NULL,
`count` int(11) NOT NULL DEFAULT '0',
`last_access` datetime DEFAULT NULL,
UNIQUE KEY `ip` (`ip`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
<?php
/*
$limit => Number of Downloads Allowed
$period => In minutes
*/
function UserHasReachedLimit($limit, $period) {
$ip = addslashes($_SERVER['REMOTE_ADDR']);
$dl = false;
$sql = sprintf("SELECT UNIX_TIMESTAMP(last_access) last_time, count FROM downloaded WHERE ip = '%s' ORDER BY last_access DESC", $ip);
$res = mysql_query($sql);
if (mysql_num_rows($res) > 0) { // There is a registered IP already
$last_xs = mysql_result($res, 0, 'last_time');
$last_xs += $last_xs+$period * 60;
$count = mysql_result($res, 0, 'count'); // number of downloads by this ip
if ($count == $limit && $last_xs > time()) { // we check if downloads reached in this period
$dl = true;
} else {
$sql = sprintf("UPDATE downloaded SET count = CASE WHEN count >= %s THEN 0 ELSE count+1 END, last_access=now() WHERE ip ='%s'", $limit+1, $ip); // we just update download count + 1
mysql_query($sql);
}
} else { // There is not a registered IP and we create it
$sql = sprintf("INSERT INTO downloaded VALUES ('%s', '0', NOW());", $ip); mysql_query($sql);
}
return $dl;
}
/*
Usage
*/
$limit = 2;
$period = 2;
if(UserHasReachedLimit($limit, $period) == true) {
// User reached number of 2 downloads in 2 minutes
} else {
// Continue downloading
}
?>
I run a fantasy basketball league. My php website/sql database is designed to let the person running the team do everything through the website - they can waive a player, and the player automatically goes into the FA pool, etc.
Everything has worked perfectly until about a week ago. Anytime now that a team goes to sign a player, after clicking "Sign", they get a blank PHP page. I have no idea why - I have made no adjustments to any files. It just started happening. Below is the code for the blank PHP page - can someone help?
<?php
$username = "me";
$password = "mypassword";
$database = "mydatabase";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$Team_Offering = $_POST['Team_Name'];
$Fields_Counter = $_POST['counterfields'];
$Roster_Slots = $_POST['rosterslots'];
$Healthy_Roster_Slots = $_POST['healthyrosterslots'];
$Type_Of_Action = $_POST['Action'];
$queryt="SELECT * FROM nuke_ibl_team_info WHERE team_name = '$Team_Offering' ";
$resultt=mysql_query($queryt);
$teamid=mysql_result($resultt,0,"teamid");
$Timestamp = intval(time());
// ADD TEAM TOTAL SALARY FOR THIS YEAR
$querysalary="SELECT * FROM nuke_iblplyr WHERE teamname = '$Team_Offering' AND retired = 0 ";
$results=mysql_query($querysalary);
$num=mysql_numrows($results);
$z=0;
while($z < $num)
{
$cy=mysql_result($results,$z,"cy");
$cyy = "cy$cy";
$cy2=mysql_result($results,$z,"$cyy");
$TotalSalary = $TotalSalary + $cy2;
$z++;
}
//ENT TEAM TOTAL SALARY FOR THIS YEAR
$k=0;
$Salary=0;
while ($k < $Fields_Counter)
{
$Type=$_POST['type'.$k];
$Salary=$_POST['cy'.$k];
$Index=$_POST['index'.$k];
$Check=$_POST['check'.$k];
$queryn="SELECT * FROM nuke_iblplyr WHERE pid = '$Index' ";
$resultn=mysql_query($queryn);
$playername=mysql_result($resultn,0,"name");
$players_team=mysql_result($resultn,0,"tid");
if ($Check == "on")
{
if ($Type_Of_Action == "drop")
{
if ($Roster_Slots < 4 and $TotalSalary > 7000)
{
echo "You have 12 players and are over $70 mill hard cap. Therefore you can't drop a player! <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.";
}else{
$queryi = "UPDATE nuke_iblplyr SET `ordinal` = '1000', `droptime` = '$Timestamp' WHERE `pid` = '$Index' LIMIT 1;";
$resulti=mysql_query($queryi);
$topicid=32;
$storytitle=$Team_Offering." make waiver cuts";
$hometext="The ".$Team_Offering." cut ".$playername." to waivers.";
// ==== PUT ANNOUNCEMENT INTO DATABASE ON NEWS PAGE
$timestamp=date('Y-m-d H:i:s',time());
$querycat="SELECT * FROM nuke_stories_cat WHERE title = 'Waiver Pool Moves'";
$resultcat=mysql_query($querycat);
$WPMoves=mysql_result($resultcat,0,"counter");
$catid=mysql_result($resultcat,0,"catid");
$WPMoves=$WPMoves+1;
$querycat2="UPDATE nuke_stories_cat SET counter = $WPMoves WHERE title = 'Waiver Pool Moves'";
$resultcat2=mysql_query($querycat2);
$querystor="INSERT INTO nuke_stories (catid,aid,title,time,hometext,topic,informant,counter,alanguage) VALUES ('$catid','Associated Press','$storytitle','$timestamp','$hometext','$topicid','Associated Press','0','english')";
$resultstor=mysql_query($querystor);
echo "<html><head><title>Waiver Processing</title>
</head>
<body>
Your waiver moves should now be processed. <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.
</body></html>";
}
} else {
if ($players_team == $teamid)
{
$queryi = "UPDATE nuke_iblplyr SET `ordinal` = '800', `teamname` = '$Team_Offering', `tid` = '$teamid' WHERE `pid` = '$Index' LIMIT 1;";
$resulti=mysql_query($queryi);
$Roster_Slots++;
$topicid=33;
$storytitle=$Team_Offering." make waiver additions";
$hometext="The ".$Team_Offering." sign ".$playername." from waivers.";
// ==== PUT ANNOUNCEMENT INTO DATABASE ON NEWS PAGE
$timestamp=date('Y-m-d H:i:s',time());
$querycat="SELECT * FROM nuke_stories_cat WHERE title = 'Waiver Pool Moves'";
$resultcat=mysql_query($querycat);
$WPMoves=mysql_result($resultcat,0,"counter");
$catid=mysql_result($resultcat,0,"catid");
$WPMoves=$WPMoves+1;
$querycat2="UPDATE nuke_stories_cat SET counter = $WPMoves WHERE title = 'Waiver Pool Moves'";
$resultcat2=mysql_query($querycat2);
$querystor="INSERT INTO nuke_stories (catid,aid,title,time,hometext,topic,informant,counter,alanguage) VALUES ('$catid','Associated Press','$storytitle','$timestamp','$hometext','$topicid','Associated Press','0','english')";
$resultstor=mysql_query($querystor);
echo "<html><head><title>Waiver Processing</title>
</head>
<body>
Your waiver moves should now be processed. <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.
</body></html>";
} else {
if ($Healthy_Roster_Slots < 4 and $TotalSalary + $Salary > 7000)
{
echo "You have 12 or more healthy players and this signing will put you over $70. Therefore you can not make this signing. <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.";
} elseif ($Healthy_Roster_Slots > 3 and $TotalSalary + $Salary > 7000 and $Salary > 103) {
echo "You are over the hard cap and therefore can only sign players who are making veteran minimum contract! <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.";
} elseif ($Healthy_Roster_Slots < 1) {
echo "You have full roster of 15 players. You can't sign another player at this time! <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.";
} else {
$queryi = "UPDATE nuke_iblplyr SET `ordinal` = '800', `bird` = '0', `cy` = '1', `cy1` = '$Salary', `teamname` = '$Team_Offering', `tid` = '$teamid' WHERE `pid` = '$Index' LIMIT 1;";
$resulti=mysql_query($queryi);
$Roster_Slots++;
$topicid=33;
$storytitle=$Team_Offering." make waiver additions";
$hometext="The ".$Team_Offering." sign ".$playername." from waivers.";
// ==== PUT ANNOUNCEMENT INTO DATABASE ON NEWS PAGE
$timestamp=date('Y-m-d H:i:s',time());
$querycat="SELECT * FROM nuke_stories_cat WHERE title = 'Waiver Pool Moves'";
$resultcat=mysql_query($querycat);
$WPMoves=mysql_result($resultcat,0,"counter");
$catid=mysql_result($resultcat,0,"catid");
$WPMoves=$WPMoves+1;
$querycat2="UPDATE nuke_stories_cat SET counter = $WPMoves WHERE title = 'Waiver Pool Moves'";
$resultcat2=mysql_query($querycat2);
$querystor="INSERT INTO nuke_stories (catid,aid,title,time,hometext,topic,informant,counter,alanguage) VALUES ('$catid','Associated Press','$storytitle','$timestamp','$hometext','$topicid','Associated Press','0','english')";
$resultstor=mysql_query($querystor);
echo "<html><head><title>Waiver Processing</title>
</head>
<body>
Your waiver moves should now be processed. <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.
</body></html>";
}
}
}
}
$k++;
}
?>
Put the following right after the open PHP tag:
error_reporting(E_ALL);
ini_set('display_errors', 'On');
If this doesn't work, there is a probably a parse error and then you'll need to check the error log.
You will also need to escape your values that you are putting in the queries. This maybe causing a MySQL query to fail. If someone puts a " in $_POST['Team_Name'] your first query may fail.
Another final possible problem: are you sure it can still connect to MySQL?
An option to find the problem is commenting out large portions of code and then piece by piece uncommenting sectons.
Edit: So your first problem is the mysql_connect line. It needs to be changed to, notice the quotes: mysql_connect('localhost',$username,$password); Also, the variable $result and $queryt are spelt wrong in this line and used in their correct spelling: $resultt=mysql_query($queryt); I haven't checked the rest, but there maybe other errors that will cause your script to break. Some of the errors list are important to fix, but won't break your script.
Escaping: Check out the following page: http://php.net/manual/en/function.mysql-escape-string.php This basically prevents people from deleting your entire database.
Check the sample code on this page to find out how to connect to MySQL and check to see if you are connected.
Another suggestion: Are you sure none of your queries are failing? You probably want to check if the result from query is false before continuing, like:
if ($resultcat2 === false) {
trigger_error('query failed ' . $sql, E_USER_ERROR);
echo 'Sorry, there was a problem processing your request. Please try again later.';
exit;
}
Turn error reporting on for PHP in your php.ini file and see if any errors or warnings are reported. Also try removing the trailing whitespace at the end of the file before the last ?>, this has caused problems for me in the past.
Added comments to some of the above responses. Please try to dumb down for me as much as possible - I'm extremely new to this. I can't figure out why it would suddenly stop working, though, when I've made no changes at all to the code.
If you made no changes to any files and it just "broke" then that would indicate that either your webhost went thru a configuration change, your database got hosed somehow, or that someone else may've changed something.
To help spot the culprit, after every one of these
if{
else{
while{
or/and after every few statements (statements end with a semicolon ;) add this to the next line
print "<br> made it to this label: some_unique_label_name_here";
Where you should replace the label each time to help you trace the code.
This will be your first step into debugging the script to figure out how far the code execution is reaching.
Without going through your code in too much detail,I would suggest you look for any sections that may loop for a long time,without returning
After enabling error reporting, make sure to put in else statements that correspond with all of your if-statements so you can determine if those statements are being triggered or not. Throw in some echos.
Also, to clarify - I have probably three dozen PHP files on the site - this is the ONLY one that has stopped working.
As an aside, you should change every variable from a get or post such as:
$Team_Offering = $_POST['Team_Name'];
to
$Team_Offering = mysql_real_escape_string($_POST['Team_Name']);
before using it in a mysql query, otherwise you are vunerable to SQL injection attacks.
This is where I got...everything below the print line wouldn't show up if I put the print line below it.
$k=0;
$Salary=0;
print "<br> made it to this label: some_unique_label_name_here";
while ($k < $Fields_Counter)
{
$Type=$_POST['type'.$k];
$Salary=$_POST['cy'.$k];
$Index=$_POST['index'.$k];
$Check=$_POST['check'.$k];
$queryn="SELECT * FROM nuke_iblplyr WHERE pid = '$Index' ";
$resultn=mysql_query($queryn);
$playername=mysql_result($resultn,0,"name");
$players_team=mysql_result($resultn,0,"tid");
So an update...nothing. lol
If you review this code:
$k=0;
$Salary=0;
print " made it to this label: some_unique_label_name_here";
while ($k < $Fields_Counter)
{
$Type=$_POST['type'.$k];
$Salary=$_POST['cy'.$k];
$Index=$_POST['index'.$k];
$Check=$_POST['check'.$k];
$queryn="SELECT * FROM nuke_iblplyr WHERE pid = '$Index' ";
$resultn=mysql_query($queryn);
$playername=mysql_result($resultn,0,"name");
$players_team=mysql_result($resultn,0,"tid");
If I put the print statement below while, the page goes blank and it doesn't show up. If the print statement is before while, the statement shows up but there's no action made on the page. The end result is that when running this page, the player selected on the previous page should be removed from Free Agents, added to the user's team, and a story should be posted on the front page announcing it. Obviously none of those are happening here.