increment variable each time page gets called or opened? - php

<!doctype html>
<html>
<head>
<title>Index</title>
</head>
<form action="newquestion.php" method="post">
Question <input type="text" name="question">
<input type="submit">
</form>
<body>
</body>
</html>
PHP file...
<?php
static $q = 1;
echo $q;
$q++;
?>
I'm new in PHP. Will this not increment $q by 1 each time "newquestion.php" is called? if not how to increment this variable each time this page(newquestion.php) gets called or opened?

No, because $q resets to 1 each time the page is called. You need some sort of persistence strategy (database, writing to a text file, etc) in order to keep track of the page views.
It's also a good idea to consolidate this functionality into a class, which can be used across your code base. For example:
class VisiterCounter {
public static function incrementPageVisits($page){
/*!
* Beyond the scope of this question, but would
* probably involve updating a DB table or
* writing to a text file
*/
echo "incrementing count for ", $page;
}
}
And then in newquestion.php,
VisiterCounter::incrementPageVisits('newquestion.php');
Or, if you had a front controller that handled all of the requests in your web application:
VisiterCounter::incrementPageVisits($_SERVER['REQUEST_URI']);

Every php script inside in a page is executed when you are loading this page. So everytime your script is executes line by line. You can not count page loading number by the process you are trying.
you can follow one of the process below:
1) you can save it to the database and each time when it is loading you can execute query to increment the count value.
2) you can do it by session like this:
session_start();
if(isset($_SESSION['view']))
{
$_SESSION['view']=$_SESSION['view']+1;
}
else
{
$_SESSION['view']=1;
}

The easy way is using a SESSION or a COOKIE based persistence methodology.
Using SESSION example:
In the beggining of the page (firt line prefered) put the following code:
session_start();
Check if a session for this user has been created and recorded, if so, increment by one the value of q session variable and display it.
If not, initialize q session variable with value 1, store and display.
if(!isset($_SESSION["q"]) //check if the array index "q" exists
$_SESSION["q"] = 1; //index "q" dosen't exists, so create it with inital value (in this case: 1)
else
$_SESSION["q"]++; //index "q" exists, so increment in one its value.
$q = $_SESSION["q"]; //here you have the final value of "q" already incremented or with default value 1.
//doSomethingWith($q);
Using COOKIE example:
$q = 0; //Initialize variable q with value 0
if(isset($_COOKIE["q"])) //check if the cookie "q" exists
$q = $_COOKIE["q"]; //if so, override the q value 0 with the value in the cookie
$q++; //increment in one the q value.
setcookie("q",$q); //send a HTTP response header to the browser saving the cookie with new value
//doSomethingWith($q);
//here you have the final value of "q" already incremented or with value 1 like in session.
With cookies, you cannot use $_COOKIE["index"] = value for set a value for cookie, you must use setcookie instead for that. $_COOKIE["index"] is only for read the cookie value (if it exists).
SESSION still use cookie, but only for identify that user is the owner of that session, the user cannot change the value of session directly (only if you provide a way to they do that).
Using COOKIE the user will see a cookie with name "q" and it's value and can easily change the value through simple javascript code, browser tools (like Google Chrome Developer Console Tool) or any extension for Browser (Edit This Cookie, a Google Chrome extension that list all cookies, values and parameters for a webpage).
Remeber that any session_start call (only one per page is necessary) or setcookie calls must be made before any buffer output like (but not just) echo, print. Because both calls produces a HTTP Header "Set-Cookie" and HTTP Headers must be sent before content body, calling this methods after a buffer flushing will throw a exception.
The two examples above are per user count. If you need a per application or per page count, you must implement a custom counter system, using file system to store data (the pageviews/page requests) or database to track individuals request (with date, ip address, page url, page name, anything else).

It won't work as you think. PHP code is executed each time from start to finish - meaning that no variables are kept over from one run to the next.
To get around this, you could use a session variable (this is a special sort of variable) which will keep a value in it that you could keep for each visitor to the site. This will however work for EACH VISITOR individually.
If you want to increment the value for all users (you open the first one, it says 1, I open the second it says 2 and so on) you will need to either store it in a database (good option), write it out to a text file (not really a good option) or magic up some other way to keep it saved.

Put $q initialization in any of your init page then increment the value.

or put the variable to increment in the session. with that, you could at least see, how often one user calls your pages.

The problem with your code is that the variable is first set to 1 each and everytime the page is visited. You will have to make use of $_SESSION. But then again the problem with using session variable would be that if you are trying to increase the value of your variable from different PCs or different systems, session would not work. For this the best thing will be to insert the value in database.

Related

passing varables' value from one form to another in php

I have three forms - payment.php , payment1.php and paydb.php . payment.php contains the front end form.payment1.php contains the back end of the form of payment.php. whereas we are shifting to paydb.php from payment1.php. Now I'm filling the form by entering member number in payment.php which is retrieved in a variable $member_no in payment1.php .Now I want to get the value of member_no in paydb.php . How to do that ?
After receiving $member_no in payment1.php redirect to paybd.php with a get array
using
header('Location: http://www.example.com/paydb.php?member_no=$member_no');
then receive $_GET['member_no'] number and assign to a variable
example:
$member_no = $_GET['member_no']
The first thing is make sure you are not passing sensitive information where the public can see it. Such as in a URL.
As soon as you get the member's number... store it in a session variable.
You can probably do this when they log in.
session_start();
$_SESSION['member_no'] = $member_no;
OR on the first payment page (assuming 'member_no' is the name of the form element being passed) like this...
$_SESSION['member_no'] = $_POST['member_no'];
Now that session will persist as long as the visitor has their browser open and you don't have to worry about passing it from page to page.
You can use that session on any subsequent page simply by calling it.
<?php echo $_SESSION['member_no'] ?>
Without showing this information to the public.
ALWAYS make sure you place this at the top of any page where you want to use session variables.
if (!isset($_SESSION)) {
session_start();
}

PHP Session Variable not Available

I have a PHP file (approvals.php) that only gets executed on an AJAX call. It has a postgresql query that searches a table and uses a customer id, which is set as a session variable. Problem is, it seems I can't access this session variable in this file. My query is like:
$query = "SELECT merchant_id FROM ndovu_merchant_users WHERE customer_id={$_SESSION['customer_id']}";
$result = pg_query($query);
I have tried to echo the session variable $_SESSION['customer_id'] but nothing. However on passing a fixed value to the query, it returns a result.
In your case, i would have checked if the session is set in the first place.
//this should be put at the header of the page
session_start();
if(isset($_SESSION['customer_id']) && !empty($_SESSION['customer_id'])){
echo $_SESSION['customer_id'];
}else{
echo 'session is not set';
}
You need to place session_start(); above the code section where you use it; the top of the page is usually the best place to place it.
Also, it should be noted; you have what is potentially a large security flaw here, by passing in unescaped data.
You should look into using prepared statements if possible; or at least escape your inputs.
The user session is not accesed when the script is called by an ajax request.
The session token wich php requires to obtain the session data is stored in the client side(user) inside a session cookie.
You can read more here
https://stackoverflow.com/a/1535712/3922692
Just pass the user id with GET or POST in the ajax request.
There is not enough code presented but if you realy need to get the id from the session you can use an iframe (which is not recommended), process fetch data server side and output it in the iframe.

How can you check if a PHP session exists?

Just wondering how to check if a PHP session exists... My understanding is that no matter what, if I am using sessions, I have to start my files with session_start() to even access the session, even if I know it already exists.
I've read to user session_id() to find out if a session exists, but since I have to use session_start() before calling session_id(), and session_start() will create a new ID if there isn't a session, how can I possible check if a session exists?
In PHP versions prior to 5.4, you can just the session_id() function:
$has_session = session_id() !== '';
In PHP version 5.4+, you can use session_status():
$has_session = session_status() == PHP_SESSION_ACTIVE;
isset($_SESSION)
That should be it. If you wanna check if a single session variable exists, use if(isset($_SESSION['variablename'])).
I find it best many times (depends on the nature of the application) to simply test to see if a session cookie is set in the client:
<?php
if (isset($_COOKIE["PHPSESSID"])) {
echo "active";
} else {
echo "don't see one";
}
?>
Of course, replace the default session name "PHPSESSID" with any custom one you are using.
In PHP there is something called the session name. The name is co-related to the cookie that will be being set if the session was already started.
So you can check the $_COOKIE array if there is a session cookie available. Cookies are normally the preferred form to interchange the session id for the session name with the browser.
If a cookie already exists this means that a PHP session was started earlier. If not, then session_start() will create a new session id and session.
A second way to check for that is to check the outgoing headers if the cookie for the session is set there. It will be set if it's a new session. Or if the session id changed.
isset($_SESSION) isn't sufficient because if a session has been created and destroyed (with session_destroy()) in the same execution, isset($_SESSION) will return true. And this situation may happen without your knowing about it when a 3rd party code is used. session_id() correctly returns an empty string, though, and can be called prior to session_start().
Check if session exists before calling session_start()
if(!isset($_SESSION))session_start();
You can call session_id before session_start. http://www.php.net/manual/en/function.session-id.php - read the id param
I've always simply used
if (#session_id() == "") #session_start();
Hasn't failed me yet.
Been quite a long time using this.
NOTE: # simply suppresses warnings.
Store the session_id in $_SESSION and check against it.
First time
session_start();
$_SESSION['id'] = session_id();
Starts a session and stores the randomly given session id.
Next time
session_start();
$valid_session = isset($_SESSION['id']) ? $_SESSION['id'] === session_id() : FALSE;
if (!$valid_session) {
header('Location: login.php');
exit();
}
Starts a session, checks if the current session id and the stored session id are identical (with the ternary ? as replacement for the non-existing short circuit AND in php). If not, asks for login again.
switch off the error reporting if noting is working in your php version put top on your php code
error_reporting(0);
I solved this three years ago, but I inadvertently erased the file from my computer.
it went like this. 3 pages that the user had to visit in the order I wanted.
1) top of each php page
enter code heresession start();enter code here
2) first page:
a) enter code here$_session["timepage1"] = a php date function; time() simple to use
b) enter code here$_session["timepage2"]= $_session["timepage1"];
b) enter code here$_session["timepage3"]=$_session["timepage1"];
3) second page:
a) enter code here$_session["timepage2"] = a php date function; time() simple to use
b) enter code here$_session["timepage3"]= $_session["timepage3"];
3) third page:
a) enter code here$_session["timepage3"] = a php date function; time() simple to use
the logic:
if timepage3 less than timepage3 on page 2
{the user has gone to page 3 before page 2 do something}
if timepage2 on page 2 less than timepage1
{the user may be trying to hack page two we want them on page 1 do something}
timepage1 should never equal timepage2 or timepage3 on any page except page1 because if it is not greater on pages two or three the user may be trying to hack "do something"
you can do complex things with simple arithmetic with the 3 timepage1-2-3 variables. you can either redirect or send a message to say please go to page 2. you can also tell if user skipped page 2. then send back to page 2 or page one, but best security feature is say nothing just redirect back to page1.
if you enter code hereecho time(); on every page, during testing, you will see the last 3 digits going up if you visit in the correct order.

PHP session values not set

I'm having some strange issues with PHP session variables claiming to not be set. I'm only encountering this in one particular situation:
My site has a 3-step wizard and I use sessions to store the user's selections on each step. To start the wizard, I use an init script that ensures any old wizard session data is wiped out - this init script then redirects the user to step 1. For example:
// Initialize wizard session and send user to step 1
$_SESSION['wizard'] = array();
$_SESSION['wizard']['step1'] = TRUE;
session_write_close();
header('Location: http://mysite.com/wizard/step1.php');
Then at the top of step1.php, I do a check like:
if (!isset($_SESSION['wizard']['step1']))
throw new Exception('Step1 not initialized');
When the user submits the step1 form, it is posted back to itself for validation. If it passes, another redirect is done to step 2.
Most of the time, this works fine. In fact, the init script always works and the step1 form always loads without a problem. But sometimes, after submitting the step 1 form, the 'Step1 not initialized' exception gets thrown. I don't see how the initial load could pass the check but the form post fail it moments later. Especially considering this problem happens infrequently and most of the time there are no problems at all.
I am using a database to store my session data and I don't think this is due to session timeouts or garbage collection - some related php.ini values:
session.use_cookies = 1
session.cookie_lifetime = 0
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 86400
Does anyone know what could be causing such a problem? Any insight would be greatly appreciated.
Thanks, Brian
Make sure that every script that uses your sessions begins with session_start()
If not the entire session is empty, but just that variable/key, you can use this to track the reason:
class foo extends ArrayObject{
function __destruct(){
echo 'dying:';
debug_print_backtrace();
}
}
session_start();
$_SESSION['wizard'] = new foo();
//array access is still possible
$_SESSION['wizard']['foz'] = 1234;
//reading it like an array also
echo $_SESSION['wizard']['foz'];
//on normal completion, it also gets called, the backtrace would be:
//dying:#0 foo->__destruct()
//^ ignore those
//on overwriting / deleting values, like for instance this by accident:
$_SESSION['wizard'] = array();
//the backtrace is something like:
//dying:#0 foo->__destruct() called at [filename:linenumber]
... and you'll have a filename+linenumber
Possibly write it to a temporary file rather then echo'ing it to make sure you don't miss stuff on redirects etc.
Did you remember to call session_start() before interacting with $_SESSION and also before any output has be sent to the browser (including any white space or blank lines before <?php?

Variable persistence in PHP

i have a php page,
on that page i have text boxes and a submit button,
this button runs php in a section:
if(isset($_POST['Add'])){code}
This works fine here and in that section $name,$base,$location etc are calculated and used. but that section of code generates another submit button that drives another section of code.
it is in this second section of code that i wish to add data to the DB.
Now i already know how to do this, the problem is that the variables $name and so forth have a value of NULL at this point.. but they can only be called after the first code section has been run where they gain value.
How do i maintain these values until the point where i add them?
Resources:
the page feel free to try it out:
location mustbe of the form 'DNN:NN:NN:NN' where D is "D" and N is a 0-9 integer
http://www.teamdelta.byethost12.com/postroute.php
the code of the php file as a text file!
http://www.teamdelta.byethost12.com/postroute.php
lines 116 and 149 are the start of the 2 button run sections!
I think you are looking for PHP's session handling stuff ...
As an example, first page:
session_start(); # start session handling.
$_SESSION['test']='hello world';
exit();
second page:
session_start(); # start session handling again.
echo $_SESSION['test']; # prints out 'hello world'
Behind the scenes, php has set a cookie in the users browser when you first call session start, serialized the $_SESSION array to disk at the end of execution, and then when it receives the cookie back on the next page request, it matches the serialised data and loads it back as the $_SESSION array when you call session_start();
Full details on the session handling stuff:
http://uk.php.net/manual/en/book.session.php
Around the add-button you are creating a second form. If you want to have the data within this form then you will have to create hidden input fields. Because you are sending a second form here. Or you are moving the add button up to the other form.
Or as others are mentioning.. Save the values into a session.
you could store them in a session
// first part of form, store name in session
$_SESSION['name'] = $_POST['name'];
// 2nd part of form, store in database
$name = mysql_real_escape_string($_SESSION['name']);
$sql = "INSERT INTO table (name_column) VALUES ('$name');
You can also try using hidden forms variables to store the data

Categories