Hits Counter code error set cookie - php

I have a PHP code for hits counter with cookies:
$id = intval($_GET['id']);
if(!isset($_COOKIE['visited'])) {
echo "not set";
setcookie("visited",$id,time()+3600);
mysql_query("UPDATE movie SET movie_views = ( movie_views + 1) WHERE id = $gid ");
}
Now the problem is that when I refresh the page, it counts 1 hit everytime and doesn't wait for 1 hour.

I think your requirements are:
1) Someone visits your site with an ID of a record passed as part of the URL ($_GET).
a) IF they visit after some elapsed 'time interval' then the 'ID' is recorded.
b) If they have visited before and the 'time interval' has not expired then the request to record the 'id' is ignored.
The 'time interval' is recorded in a COOKIE called 'visited'.
You record the details in a database - i store the id in a $_SESSION variable. It is for demonstration only.
I show the method only. It is not meant to be efficient. It is designed to be debugged very easily. It reports every step and state.
I use a 'time interval' of 20 seconds.
I have a working example at: viper-7.com?id=9/. Note: the $_GET[id] parameter is passed on the 'viper-7' URL! you can change it to ensure the code works. It will reject your new id until the 20 seconds have elapsed.
The code (it is commented):
<?php
session_start(); // Testing only - store last ID in $_SESSION['id']!
define ('VOTE_DELAY', '20'); // seconds
// show 'visited cookie or if missing...
if (isset($_COOKIE['visted'])) {
echo '<pre>';
var_dump($_COOKIE['visited']); // show all cookies currently active
echo '</pre>';
}
else {
echo '<br />No current $_COOKIE[visited] found!';
echo '<br />';
}
// DEBUG - show current ID
echo '<br />Current Session ID: ', !empty($_SESSION['id']) ? $_SESSION['id'] : 'none';
echo '<br />';
// process whether visited in the last interval (20 seconds)
if (isset($_COOKIE['visited'])) {
echo '<br />active Cookie: ', $_COOKIE['visited'],' - will leave now...';
return; // no more voting until cookie expires
}
// no id provided - is error
if (empty($_GET['id'])) {
echo '<br />no valid $_GET[id] provided : will leave - NO Visited Cookie set ';
return; // do nothing
}
$id = $_GET['id']; // store new id in the session rather than the database
echo "<br />New VALID visit: will store cookie for: ", $id, ' in the $_SESSION[id] variable';
setcookie("visited", "$id", time() + VOTE_DELAY); // set the 'visited cookie
$_SESSION['id'] = $id; // store in session rather than the database.
// mysql_query("UPDATE movie SET movie_views = ( movie_views + 1) WHERE id = $gid ");
echo "<br /> new cookie set...";
I have no idea why your code does not work.
Also, if the client deletes the 'visited' cookie then they can get the 'id' recorded as often as they wish. You will need to analyse the records in the database to ensure 'recordings of 'id' are valid.

Related

Check to see if a cookie exists based on part of its name in PHP

I have set a cookie. I want to add multiple cookies, one for each item and have the quantity of these items in each of the values (this is a shopping cart). My problem is, how do I (for example) check to see how many items there are based on the cookie names. I can'y just count ALL cookies because I have cookies being used for other purposes too.
You can see how I have set them - this might provide a bit of clarity. I can confirm the cookie does set as I intended it to. I just don't know where to start when trying to identify these cookies by name.
if (!isset($_COOKIE['cart_item_' . $_GET['itemadd']])){
//if cookie doesn't, create one
setcookie($cookie_name, "1", time() + 86400, "/");
//echo "did i get here";
}else{
//if cookie does, add to quantity
if (!isset($_GET['quantity'])){
$cookie_value = $_COOKIE['cart_item_' . $_GET['itemadd']] + 1;
}else{
$cookie_value = $_GET['quantity']; //cookie value is the number of items being added
}
//echo "CN:" . $cookie_name . " - CV:" . $cookie_value;
setcookie($cookie_name, $cookie_value, time() + (86400), "/"); // 86400 = 1 day
You can use Session for shopping cart. I hope the following code will help you:
if(!isset($_SESSION['some_product_id'])){
$data = array(
'product_name' => 'some product name',
'quantity' => 5, //some quantity,
'other_things' => 'Some other values',
);
$_SESSION['some_product_id'] = $data;
}else{
echo 'Product Name: '. $_SESSION['some_product_id']['product_name'] . '<br>';
echo 'Product Quantity: '. $_SESSION['some_product_id']['quantity'] . '<br>';
echo 'other_things: '. $_SESSION['some_product_id']['other_things'] . '<br>';
}

Use session variable or copy PHP code from second page to third page of a website

I have three pages in the website. The first is login page,second is profile page and third is main page.
<?php
session_start();
$servername="blah blah blah";
$connectioninfo=array('Database'=>'mbr');
$conn=sqlsrv_connect($servername,$connectioninfo);
if($conn)
{
echo 'connection established';
}
else
{
echo 'connection failure';
die(print_r(sqlsrv_errors(),TRUE));
}
$q1="SELECT * FROM EmployeeTable WHERE EmployeeID = '" . $_SESSION['id'] . "' ";
$stmt=sqlsrv_query($conn,$q1);
if($stmt==false)
{
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors(),TRUE));
}
$row=sqlsrv_fetch_array($stmt);
echo $row['EmployeeName'];
$q2="SELECT * FROM pointsBadgeTable WHERE EmployeeID = '" . $_SESSION['id'] . "' ";
$stmt1=sqlsrv_query($conn,$q2);
if($stmt1==false)
{
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors(),TRUE));
}
$pbrow=sqlsrv_fetch_array($stmt1);
?>
The above is the php used in the second page of the website. Here I am using two queries $q1 and $q2 to retrieve information from two different tables (EmployeeTable and pointsBadgeTable) after connection to the database "mbr" here.
I then echo the desired Info in my html after retrieving info from the tables.
For instance,
<?php echo "". $row['goldTotal'] .""?>>
Here 'goldtotal' is a column in the pointsBadgeTable in the above php. Also please note that I am using " . $_SESSION['id'] ." here to show info only about the person who logs in the first page of the website.
The issue here is that I want to echo the same value in the third page as in second page. Will I have to write the same php code in third page as I wrote in second page or I need to store it in some session variable. How to use a session variable here?
Also, is it correct to rewrite the same code in third page also as in second page and use the same queries $q1 and $q2? I will copy and paste the same PHP to the third page also.
You Can include the second page in third page , you will get the value .
Example : file3.php
**<?php
include 'file2.php';
?>**

How can I manage the lifetime of my PHP sessions?

I am quite new to PHP, so I'm working on a simple project to practise. However, I can't manage to make the session management work properly.
What I want is that when the browser is closed, the data (the current page the user is at) is saved for an hour. If the user returns within an hour, he should see the same page he left, and if he return after an hour, he should see the first question.
When all questions have been answered, he should see a score-screen, with a "Try Again" button that preferably destroys/kills/deletes the session and starts a new one, directing the user to the first question.
If I leave out line 3-8 my code works as expected, I run throught the questions until I get stuck at the score-screen with a non-working "Try Again" button, I can only go back to the first question by closing and reopening the browser.
With these lines, the page runs through the questions fine but when I restart the browser, it starts at the first question. When I close the browser without doing anything and open the page a second time, I find the page I left at first. I close and open the browser again and I find the correct page again, I do it again and I'm back to question 0. No matter how often I then restart the browser, I stay at question 0.
When I look at the cookies in my browser, I have the same cookie all the time, one that started at 14 december 2015 18:48:45. However, the experation time isn't correct either, as that is 26 november 2061 13:37:29, instead of an hour later. What am I doing wrong?
Here is my code:
<?php
/* Sart (new) session*/
if (isset($_GET['TryAgain'])){
session_start();
$_SESSION = array();
session_destroy();
}
session_set_cookie_params(time()+3600);
session_start();
/*-------------------------------------------------------------------*/
/* IMPORT DATABASE: $qs[i]=question text, $as[i]=array(choices per question),
$as[i][i]=array('t'=>choice text, 'c'=>BOOLEAN) */
require_once('config.php');
$dbh = new PDO("mysql:dbname=$db;host=$host", $user, $password);
$questions = $dbh->prepare('select * from questions');
$questions->execute();
$choices = $dbh->prepare('select * from choices');
$choices->execute();
$qs = array();
$as = array();
foreach($questions as $row) {
$i = $row['q_nr'];
$qs[$i] = $row['q_text'];
}
foreach($choices as $row) {
$qi = $row['q_nr'];
$ci = $row['c_nr'];
$as[$qi][$ci] = array('t'=>$row['c_text'],'c'=>$row['correct']);
}
/*-------------------------------------------------------------------*/
/*INITIALIZE SESSION VARIABLES*/
/* Creates counter-variable if not set -------- (ini value is 0)*/
if(!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 0;
}
/* Creates score-variable if not set -------- (ini value is 0)*/
if(!isset($_SESSION['score'])) {
$_SESSION['score'] = 0;
}
/*-------------------------------------------------------------------*/
/* SET COUNTER, SCORE AND DONE*/
/* Check if answer previous question has been submitted*/
if (isset($_GET['a'])) {
$submitted = true;
} else {
$submitted = false;
}
/* Set counter*/
if ($submitted){
$_SESSION['counter'] += 1;
}
$cqi = $_SESSION['counter'];
/* Set score*/
if ($submitted) {
if ($as[$cqi-1][$_GET['a']]['c']){
$_SESSION['score'] += 1;
}
}
$score = $_SESSION['score'];
/* Check done*/
if($cqi >= count($qs)){
$done = true;
} else {
$done = false;
}
echo 'cqi: '.$cqi;
echo 'done: '.$done;
/*-------------------------------------------------------------------*/
?>
<!-- START HTML!!! -->
<html>
<head>
</head>
<body>
<br><br>
<?php
if($done){
echo 'You finished the quiz. <br> Your score is: '.$score;
echo "<form action='index.php' method='get'>";
echo "<input type='hidden' name='TryAgain' value=true>";
echo "<input type='submit' value='Try again!'>";
echo "</form>";
} else {
echo $qs[$cqi];
echo "<form action='index.php' method='get'>";
$cci = 0;
foreach($as[$cqi] as $cc){
echo "<input type='radio' name='a' value=".$cci.">".
$cc['t']."<br>";
$cci++;
}
echo "<input type='submit' value='Next question'>";
echo "</form>";
echo "<br><br>Current score: ".$score;
}
?>
</body>
</html>
Please help me, I really am stuck with this.
-Edit-
I tried again omitting line 3-8 and keeping session_set_cookie_params(600);, to test this function as simply as possible. I tested it the same way as cited above, reopening my browser time and time again and noting down which question I got (q. 0 or 1). I got a seemingly random pattern, of first question 0 and the question I should be on, 1, in which 0 is often the most prevalent. I am quite sure it is random, as I removed the cookie and redid the test multiple times and each time I saw a different pattern. The cookie does expire now at the right time though.
I also tried the ini_set('session.cookie_lifetime', 600); instead of session_set_cookie_params(600); function, as suggested in the other question, but I still had random results. And I don't think it is a good idea for me to try and create a login system if I even can't get this right...

How can I accept or delete any pending post?

I am very very disappointed this time. I wasted my whole day and I couldn't help me out. Here is the problem:
I need accept or delete the pending jobs. If I accept, only then it will publish on my site. Please look at the image.
Here I am trying this code to handle this matter. Firstly if anyone post a new job, I pass a hidden value=0 according to the job.
<input type="hidden" name="pending" value=0/>
Then I store it in my database.
INSERT INTO job (Pending) VALUES ('$_POST[pending]');
Then I go to the image(above) page to accept or delete.
echo "<a href='accept.php?accept=1'>ACCEPT</a> Or ";
echo "<a href='accept.php?accept=0'>DELETE</a>";
After accepting Pending column will be replaced from 0 to 1 and thus it will be published. Or deleting time, the job will be simply be deleted from database.
$accept=$_GET['accept'];
if($accept==1){
mysql_query("UPDATE job SET Pending='$accept'
WHERE ID='5'");
}
else{
mysql_query("DELETE FROM job WHERE ID='5'");
}
In the 'job' table, I use a primary auto increment column named ID. I put 5 for ID. So this code will work only for the pending job which ID is 5. So my problem is here. How can I alternate this 5 with a dynamic variable?
FOR MORE ASSISTANCE HERE IS the CODE OF 'PENDING JOBS' PAGE;
$result1 = mysql_query("SELECT * FROM job ORDER BY ID DESC");
while($row1 = mysql_fetch_array($result1))
{
$id=$row1['ID'];
$cat=$row1['Category'];
$title=$row1['Title'];
$type=$row1['Type'];
$desp=$row1['Description'];
$salary=$row1['Salary'];
$day=$row1['Day'];
$month=$row1['Month'];
$year=$row1['Year'];
$info=$row1['Contact'];
$pending=$row1['Pending'];
$now = time();
$last_date = strtotime("$year-$month-$day");
$datediff = $last_date - $now;
$day_left=ceil($datediff/(60*60*24));
if($day_left>=0&&$pending==0){
echo "<div class=cat>Job field: $cat<br/></div>";
echo "<div class=yel2>";
echo "This is a <b>$type time</b> job and we are looking for <b>$title</b>. $desp<br/>";
if ($salary!=0) echo "Salary: $salary<br/>";
echo "Contact info: $info<br/>Last date: $day-$month-$year";
if($day_left==0)
echo "<br/><span class=ash><i>Today is the last day to apply</i><br/>";
else
echo "<br/><span class=ash><i>$day_left day(s) left</i></span><br/>";
echo "<span class=acc><a href='accept.php?accept=1'>ACCEPT</a><span> Or ";
echo "<span class=del><a href='accept.php?accept=0'>DELETE</a></span>";
Just pass the id along with the accept url.
echo "<span class=acc><a href='accept.php?id=$id&accept=1'>ACCEPT</a><span> Or ";
You can grab the id inside the accept.php script using
$post_id = $_GET['id'];
The code would require little change
$accept = intval($_GET['accept']); // safe against sql-injections
$post_id = intval($_GET['id']);
if($accept==1){
mysql_query("UPDATE job SET Pending='$accept'
WHERE ID='$post_id'");
}
else{
mysql_query("DELETE FROM job WHERE ID='$post_id'");
}

PHP & MySQL vote count problem?

I found this script on about.com which I'm trying to learn from on how to create a rating system but the script for some reason wont count a vote when the link is clicked and just reloads the page.
I was wondering how can I fix this problem? And what part of the code do I need to change and where?
Here is the full script below.
<?php
// Connects to your Database
mysql_connect("localhost", "root", "", "sitename") or die(mysql_error());
mysql_select_db("sitename") or die(mysql_error());
//We only run this code if the user has just clicked a voting link
if ( $mode=="vote") {
//If the user has already voted on the particular thing, we do not allow them to vote again $cookie = "Mysite$id";
if(isset($_COOKIE[$cookie])) {
echo "Sorry You have already ranked that site <p>";
} else {
//Otherwise, we set a cooking telling us they have now voted
$month = 2592000 + time();
setcookie(Mysite.$id, Voted, $month);
//Then we update the voting information by adding 1 to the total votes and adding their vote (1,2,3,etc) to the total rating
mysql_query ("UPDATE vote SET total = total+$voted, votes = votes+1 WHERE id = $id");
echo "Your vote has been cast <p>";
}
}
//Puts SQL Data into an array
$data = mysql_query("SELECT * FROM vote") or die(mysql_error());
//Now we loop through all the data
while($ratings = mysql_fetch_array( $data )) {
//This outputs the sites name
echo "Name: " .$ratings['name']."<br>";
//This calculates the sites ranking and then outputs it - rounded to 1 decimal
if($ratings['total'] > 0 && $ratings['votes'] > 0) {
$current = $ratings['total'] / $ratings['votes'];
} else {
$current = 0;
}
echo "Current Rating: " . round($current, 1) . "<br>";
//This creates 5 links to vote a 1, 2, 3, 4, or 5 rating for each particular item
echo "Rank Me: ";
echo "Vote 1 | ";
echo "Vote 2 | ";
echo "Vote 3 | ";
echo "Vote 4 | ";
echo "Vote 5<p>";
}
?>
$mode is never set? While it may have worked if register globals was on, it is not on by default any more (and is removed in later versions of PHP)
//We only run this code if the user has just clicked a voting link
if ( $mode=="vote") {
Maybe you mean
if ( $_GET['mode']=="vote") {
The same goes for $id and $voted, which are also never set.
EDIT
I also would like to add, that if I went and changed id to 1';DROP TABLE vote; You would have a whole lot of data lost. Look at SQL Injection
EDIT
If the row in the table doesn't exist, you will need to INSERT it before you can UPDATE it.
I can also see $cookie is never set, looking at the code it should be 'Mysite' . $id. I added quotes for the string, though PHP will treat any unquoted text as string but avoid misunderstanding and errors later, its always a good idea.
Also this script assumes PHP option register_globals is on, you need to make that register_globals = ON in your php.ini

Categories