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.
Related
I tried to create a login form from an example. I made it works but I don't understand.
Why $_SESSION['umsco'] is required and why should I assign the $username variable to it. I also do not understand if conn->close() required and what is the $result variable.
// I include the database file so we can get the information from there and apply it in here as well.
include "dbc.php";
// here we select the variables we want from the table 'members'.
$sql = "SELECT id, firstName, lastName FROM members";
// here we do something that I dont really know but this is standard procedure.
$result = mysqli_query($conn, $sql);
// declaring username
$username = $_POST["username"];
$password = $_POST["password"];
// my result thing, again, standard procedure.
$result = $conn->query($sql);
// we insert all values in row, standard procedure.
$row = $result->fetch_assoc();
// here we check if the username is the same as the database.
if ($username == $row["firstName"]) {
// if it's correct then we start a session
session_start();
// we give a session some random letters or numbers and set it to $username, not exactly sure why, but it wont work without it.
$_SESSION['umsco'] = $username;
// we change the location to secrect.php
header("location: secret.php");
}
// we close the connection, not sure if this is needed, but it seems logical.
$conn->close();
I advise you to always implement session_start()at the beginning of your code to avoid bad behavior.
What is a session
To understand, you must understand what a PHP session is.
A session is a way to keep variables on all pages of your site for a current user.
How it work
First you must ask PHP to initialize the session. For doing this, you must add session_start() at the beginning of your code.
When the server responds to the client, it append a cookie called PHPSESSID who contains the unique session identifier of the user.
At every request, the browser sends this cookie to the server so that php can recover the session from the hard disk of the server.
The most commun way to register a session variable is $_SESSION['key'] = $value;.
Final answer
To end, the line $_SESSION['umsco'] = $username; store the username of the user in his session until.
the session is destroyed with session_destroy()
the session expire after a time defined in php.ini
you unregister the variable.
In secret.php you probably check whether this value is assigned or if the session exists to check if the user is logged in. That's why it's mandatory, otherwise a login form would have no meaning.
Another ressource : Is closing the mysql connection important?
The result thing is that next time you call
session_start();
$loggedUserName = $_SESSION['umsco'];
you will have that user (username) available for you wherever you need it.
Just read basics of SESSION and you should be able to understand that.
Firstly, you need to query members where username and password match $_POST data.
Secondly, whatever is stored in $_SESSION variable will be available between requests. Typically, you want to "remember" user ID or similar so you do not need to submit username/password and repeat the member lookup with every request.
See more elaborate description here: https://www.johnmorrisonline.com/build-php-login-form-using-sessions/
What others have said about the $_SESSION variable is correct. If using session_start(); those values can be persisted across multiple requests from the users browser. The $_SESSION value will be particular to the user visiting your site.
Regarding the $result object, $result->fetch_assoc(); will only fetch one row from your table. So your current code would only work if the username matches the 1st row of your members table. It'd be best to query only rows where the username matches what they've entered. Note there's a big security risk if you just concatenate strings together for the query, so you should use prepared statements (https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection)
I am working on a simple PHP web-application. And in that I want to get Id of user from the mysql database.
For that I have used session to store userID as soon as user in inserted in database:
session_start();
$_SESSION['customer_id']=mysqli_insert_id($con);
But it always says that undefined index customer_id on other pages.It is working fine on localhost but not on live server.
As per the documentation: mysqli_insert_id Returns the auto generated id used in the latest query. If you don't run an insert query before starting session, then mysqli_insert_id will not return what you're looking for.
Rather, try searching for the user with information obtained upon user login, like the user's email address or username.
E.g.
SELECT id FROM users WHERE users.username = userSuppliedEmail
It goes without saying that you should use prepared statements or some similar technology for this query.
It looks like something is preventing you from creating a session.
Before you do anything, where you declare session_start, do the following:
Instead of session_start() put:
$started = session_start();
echo "Session Started: " . ($started ? "YES" : "NO");
If PHP says the session is indeed started, make sure the session id is staying the same between requests. You can obtain the session id with:
echo session_id();
From request to request, the session id must be the same, unless it's expired, or deleted. If you get a session id on first page, but no session id on second page, then either session_start wasn't executed, or the session was not created.
Since you assured me session_start is executed, the next thing you need to do is verify that the session is indeed created, and written to a file on the server.
After you obtain the session id, (eg. 7815696ecbf1c96e6894b779456d330e) you should check your sessions folder for a file named 7815696ecbf1c96e6894b779456d330e (this is just an example, your file name will be different).
$sessionPath = ini_get('session.save_path'); // obtains the path to session
echo "Our session path is: $sessionPath <br/>";
$filesInSessionFolder = scandir($sessionPath); // obtain all files in session folder
if($filesInSessionFolder == false){
echo "Could not access session folder<br/>";
}else{
// display all files in the folder
print_r($filesInSessionFolder);
}
Now make sure that the session id exists in the list.
<!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.
I have a page a to which I am posting the data from a python script. I am processing that data, storing the data into SQL. I want to store the time when this post request is made.
Note that the post request is made continuously. So the session variable keeps on changing. Well here is the little code for that-
<?PHP
session_start();
include 'db.inc.php';
if(isset($_POST['data']){
$data_decode = (array)json_decode($_POST['data']);
$data_var1 = $data_decode['var1'];
$data_var2 = $data_decode['var2'];
$data_var3 = $data_decode['var3'];
$date = date('Y-m-d H:i:s');
$_SESSION['time'] = $date; //Set the session with current time
$sql = "UPDATE `table` SET row1=$data_var1, row2=$data_var2 WHERE row3=$data_var3";
$result = mysqli_query($db,$link) or die('Table could not be updated');
echo "Following data inserted: row1=$data_var1, row2=$data_var2, at $_SESSION['time']"; //Echoing the data and time as expected
?>
Now, I have another page on the same domain, which makes the ajax request and fetches out the data every second from the SQL table I just inserted the data into. So here is the whole scenario- The client python script makes the post request to the webpage, which updates the sql with the received data, sets the session variable. Another page simultaneously fetches that data out using ajax and shows it.
Now I am calling the session variable on another page as shown-
<?php
session_start();
if(isset($_SESSION['time']){ echo $_SESSION['time']; } //Didn't echoes anything
?>
I used <?php print_r($_SESSION) ?> to check whether the session variable is set or not, it echoed "Array()", which means my session variable is not set. So my question is, What I am doing wrong and how can I correct it?
Make sure to call session_start() at the beginning of every page...
You forgot the semicolon after the declaration.
$_SESSION['time'] = $date
should be
$_SESSION['time'] = $date;
You forgot session_start()
<?php
session_start();
if(isset($_SESSION['time']){ echo $_SESSION['time']; } //Didn't echoes anything
?>
I am trying to reconstruct which components are acting in your scenario.
So first you mention a Python script. How does it work together with PHP? Does it actually emit a HTTP request itself, or does it only send HTML to a browser that is then going to PHP? If Python is acting like a HTTP client, this is important, because PHP sessions use cookies, so your Python script has to be able to accept the "Set-cookie" HTTP header and deal with it, especially send it back on later requests.
Second info is that there is some Ajax going on. This points to a browser and some Javascript as a client, and this combo is clearly able to accept any cookie that is set by PHP.
But how do the browser and the Python script communicate? How does the browser know which cookie the Python script got back from PHP so that the session data can be loaded?
I hope you see the hole in your approach. Posting data from Python into the database is one thing, saving the time of this event probably is a global information (date of last DB update), and not a session information (is different per Python client). As such, the session is the wrong location for storage. And the other obstacle is that your Ajax client cannot share the session ID from your Python client! And the last downside to sessions: If it would work, you would constantly interfere with both requests, because sessions use locking to prevent two requests deleting each others data. This is especially bad because a hanging Ajax request might prevent the Python script from writing to the database, and vice versa.
Find a way to store a global information on your server. You already have a database, why not use it for this?
I am fairly new to PHP. What is the best way to control access to a class throughout a PHP application and where is the best place to store these classes that will need to be accessed throughout the entire application? Example; I have a user class that is created on during the login process, but each time the page post it appears that the object is reinitialized.
I have tried to set property IsLoggedIn and then check that variable each time before creating the object as new again, but this doesn't seem work. I have also tried to use the isSet function in PHP to see if the class variable already exists
You're right, the state of your application is not carried over from request to request.
Contrarily to desktop applications, web applications won't stay initialized because to the server, every time it can be a another visitor, wanting something completely different. You know who's using the desktop application, but you don't necessarily know who's requesting the page. Imagine 10 users doing different thing simultaneously on your web application? You wouldn't keep the whole application running necessarily for each of those visitors. Imagine with 10,000 visitors...
There are ways to keep some data from request to request though. The application will be reinitialized each time, yes, but you can then reload the state of what you were doing. It always revolve around around the same general methods:
Cookies; Cookies are a small file that is kept on the client side and which content will be available on each request to you. In PHP, this is available using $_COOKIE variable. In all cases, you could serialize your classes instances and reload them afterwards. The problem is, you wouldn't want to put sensitive data there as any(malicious)body can see and modify it.
POST or GET; In each request, you pass a state in the $_GET request (the URL such as http://localhost/myscript.php?iamatstep=4. Or via a $_POST such as using a hidden input field in a form. This data could be encrypted and make sense only to you, but still, you are putting sensitive data back to the client and anybody could fiddle with it.
Database, Disk; Or anything else on the server. Again, you serialize your data in a file for example at the end of a request ready to be used again for the next request. The main advantage is that it stays on your server. The downside is that at this point, you don't know which data to extract back for which request as there might be multiple users on your application at the same time...
And this is where the notion of $_SESSION comes into play. It's just a packaged way of using all of this at the same time. It's not magical as often it's perceived by beginners. When you use a session, the data put into the $_SESSION is stored somewhere on the server (normally a file in a temporary directory although it can be changed to something else like a database) and a unique ID is attributed to this session and passed in a cookie that will follow the visitor from request to request. So the only thing on the client's side is a big number in the cookie. On the next request, the browser tells PHP on the server that it's session number 12345, loads the corresponding file if it exists and then the data is available to you again. If cookies are not enabled, it could be passed in a GET or POST, although it's often better not to go there (see session.use_trans_sid's note).
It often looks like that on each of your pages you need authentication.
<?php
// verify if we have a current session
if (isset($_SESSION['login'])) {
// get data in current session
$username = $_SESSION['login']['username'];
$isLoggedIn = $_SESSION['login']['isLoggedIn'];
} else {
$username = '';
$isLoggedIn = false;
}
// take care of the unauthorized users
if (!$isLoggedIn) {
// maybe a redirection here...
}
// do the things a logged in users has the permission to do
And to set the session, it'll probably look like that:
<?php
// handle the form post of your login page for example
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// verify the username and password against a database
if ($everythingIsOkay) {
// we can consider this user logged in and create a session
$_SESSION['login']['username'] = $username;
$_SESSION['login']['isLoggedIn'] = true;
// and now maybe redirect the user to the correct page
}
}
// raise an error about an invalid login
And finally, maybe a logout.php page that would do something like that:
<?php
unset($_SESSION['login']);
// redirect the user to the login page
This kind of data is going to have to be stored in a session, the only thing that is carried from page to page is Session data (sessions/cookies/...) so your class initialization is not carried over.
You can add information like the users username to the session with:
$username //username from db
$name //name from db
$_SESSION['username'] = $username;
$_SESSION['name'] = $name;
or if you just want to have easy access to all the information about the user you can do:
$_SESSION['user'] = mysql_fetch_assoc($result); //where $result is the response from the db to your login query
after you do this $_SESSION['user'] will be an array with all the details you selected from the database.