I have some simple system to upload files and keep track of them for each particular user, using a database.
The problem of mine is, I connect to the database in the file checklogin.php, which is responsible to handle the $_POST from main_login.php.
In file 'checklogin.php':
$current_user_name = NULL;
which is a global variable for all files. Now in file signup.php, I try to include the checklogin.php to define that variable:
require_once '/checklogin.php';
...
mysql_query("INSERT INTO " . tbl_name . " (username, userpassword, userisadmin)
VALUES (''" . $_POST['myusername'] . "',"
. "'" . md5($_POST['mypassword']). "',"
. "0)");
$current_user_name = $_POST['myusername'];
header("location:login_success.php");
As you can see, I'm trying to set the value of the variable $current_user_name = $_POST['myusername'];, but when header goes to the file login_success.php, which is having require_once '/checklogin.php'; too, the variable is set again to null.
How can I solve this problem? i.e. How can I store the current user so that it is accessible by all files?
You cannot store a variable like that. Each request will be new execution in sever. In this kind situation we have to use session please check this
And another issue with your code is SQL injection, Please read this too
You can not access the Parameter received at checklogin.php
what you can do you can check the the login status and set the current user in session.
From session variable you can access and set the current user.
you can set a session variable for it and on every you can use it like this
session_start();
if(isset($_SESSION['current_user_name']))
{
$current_user_name = $_SESSION['current_user_name'];
}
else
{
$current_user_name = NULL;
}
and set your session variable as follows
session_start();
require_once '/checklogin.php';
////...
mysql_query("INSERT INTO " . tbl_name . " (username, userpassword, userisadmin)
VALUES (''" . $_POST['myusername'] . "',"
. "'" . md5($_POST['mypassword']). "',"
. "0)");
$current_user_name = $_POST['myusername'];
$_SESSION['current_user_name'] = $current_user_name; // set your session here
header("location:login_success.php");
Related
I build a internet site with php and html. I detect the access from the users with a code like this :
$qry ="SELECT * FROM visit WHERE ip='" .$ip ."' AND date(quando)=CURRENT_DATE";
$arr=$dbcls->query_arr($qry);
if(count($arr)==0)
{
$data=get_location2($row["ip"]);
if($data)
{
$country=$dbcls->escape_string($data->country);
$sub=$dbcls->escape_string($data->subdivision);
$city=$dbcls->escape_string($data->city);
$qry="INSERT INTO visit(ip,n,country,region,city)
VALUES('" . $ip ."',1,'". $country. "','" . $sub . "','". $city. "');";
//echo $qry;
}
else
$qry="INSERT INTO visit(ip,n) VALUES('" . $ip ."',1);";
}
else
$qry="UPDATE visit SET n=n+1 WHERE ip='" . $ip ."' AND date(quando)=CURRENT_DATE ;";
$dbcls->query_command($qry);
that allow me to save all the users that login in my site. The next step is to save how many users downloads my program.
The question is: how can I detect when a user make a download with php? If I have to create code with Javascript How can access to my database with javascript?
Your URL downloads/Treebase.zip is not served by PHP, is a static file.
The download is managed by the web server not by PHP.
To manage by PHP you'll need to make a route and make the PHP send the file.
Something like downloads/download.php?file_name=Treebase.zip.
I have one serious problem.
There is a little PHP system, which contains admin panel and customer panel.
These panels must be functioning independently from each other.
For example - if admin logs out, customer must stay inside, etc.
There is my logout.php script (which is called by logout button javascript handler):
<?php
require_once("./setup/additional_functions.php");
require_once("./setup/mysql_settings.php");
session_start();
$functionName = filter_input(INPUT_GET, "functionName");
if($functionName == "logoutAdmin") {
initiateLogout("um_status", "users_managers", "um_id", $_SESSION['admin_id'], "admin");
} else if($functionName == "logoutCustomer") {
initiateLogout("customer_visit", "users_customers", "customer_id", $_SESSION['cust_id'], "../customer");
} else {
echo "Unknown error!";
}
function initiateLogout($loginTime, $tableName, $id, $sessionName, $backPage) {
$sqli = new sqlSettings();
$sql = "SELECT ". $loginTime ." FROM ". $tableName ." WHERE ". $id ." = ". $sessionName;
$result = $sqli->setConnection()->query($sql);
$user = $result->fetch_array();
$timestamp = $user[$loginTime] - 300;
$sql = "UPDATE " .$tableName. " SET " .$loginTime ." = ". $timestamp. " WHERE " .$id ." = ". $sessionName;
$result = $sqli->setConnection()->query($sql);
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 50000, '/');
}
unset($sessionName);
//redirect_to($backPage);
echo "../" . $backPage;
}
?>
Data inside $_SESSION['admin_id'] and $_SESSION['customer_id'] - absolutely different! But anyway - when I hit button (for example) on admin side - customer also logs out!!! It shouldn't be like this.
How to avoid this? Will be very thankful for any help!!
You don't need to be setting $_SESSION to an empty array.
You need to be setting the respective $_SESSION key to null or insetting it.
For customers this would be unset($_SESSION['cust_id']) and for admin this would be unset($_SESSION['admin_id'])
Your current code destroys the whole session which logs both customer and admin accounts out.
Well, I think my mistake was in testing whole system on my local computer. Cause if you do the same - session is being created during one browser and one pc. And it doesn't matter by whom you're logged in. After I placed my system on remote server and tested my old code from different "points" - everything works perfect.
I'm learning php and mysql and i'm making fake login site. -for learning purpose-
<?php
$id = $_POST[mb_id];
$password = $_POST[mb_password];
// Create connection
$conn = mysqli_connect(localhost, u982680175_root, temp, u982680175_test);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO student (id, password)
values ('$id', '$password')";
if (mysqli_query($conn, $sql)) {
header("Location: http://www.dtg.hs.kr/");
exit();
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
i sucess saving data in to my server and redirected to realhomepage. but i want to redirect to logined real site after saving database.
how can i call real php and give data?
this is the real login page: http://www.dtg.hs.kr/sys/bbs/login.php
Short answer...
After the data from the user being created is inserted into the database you will need to have the script create some sort of $_SESSION[] variable that uniquely identifies the user.
Here is the PHP documentation related to SESSIONs http://php.net/manual/en/book.session.php
When the redirect occurs there will be a check to see if the $_SESSION variable is set or not. If the $_SESSION variable is set, then do a check to see if the $_SESSION variable is valid.
In then you will be able to show different data based on the validated $_SESSION or if no $_SESSION is set.
Hope this helps!
I am trying to set up a user login/logout system using php and mysql. I have found some documentation on the subject here: http://phpmaster.com/writing-custom-session-handlers/. I am trying to follow along with it (I have also been pulling from other sources too - but this is the main one).
Here is some of my code from "my_session_handler.php":
class MySessionHandler implements SessionHandlerInterface {
private $path = session_save_path();
private $name = session_name();
private $sessionId = session_id();
function open($path, $name) {
$db = new PDO("mysql:host=localhost;dbname=itit", "root", "bonjour3");
$sql = "INSERT INTO session SET session_id =" . $db->quote($sessionId) . ", session_data = '' ON DUPLICATE KEY UPDATE session_lastaccesstime = NOW()";
$db->query($sql);
...
My question is, where are the "$path" and "$name" variables coming from in the example I cited above? I declared them as private variables and used some functions to do what I am thinking needs to be done. But on the website that I am following along with - neither of these variables get declared - along with $sessionId. I see that the read function returns $data. So I used it in the "write" function like this:
function write($sessionId, this.read($sessionId)) {
$db = new PDO("mysql:host=localhost;dbname=itit", "root", "bonjour3");
$sql = "INSERT INTO session SET session_id =" . $db->quote($sessionId) . ", session_data =" . $db->quote($data) . " ON DUPLICATE KEY UPDATE session_data =" . $db->quote($data);
$db->query($sql)
}
Am I doing this right?
These parameters are used by the default session save handler, which saves the session data in files. They come from the php.ini file, and are used to form the filenames. They're supplied to your handler when PHP calls the open() method.
If you're writing a custom handler, you can ignore them, as the code on that web page does.
I'm sure i've badly written this. I have a simple form which you enters bits into, which sends the info onto a process page and inserts a row into a table on the database. My problem is that the insert part works fine. But my template class within the page or anything else is shown. Just a blank page. Its driving me nuts.
The function
Public function UpdateReason($reason, $bundlereference) {
error_reporting(E_ALL ^ E_NOTICE);
$db_selected = mysql_select_db(DB_DATABASE_NAME, $this->conn);
if (!$db_selected) {
die("Can't use db : " . mysql_error());
}
$_reason = mysql_real_escape_string($reason,$this->conn);
$_bundlereference = mysql_real_escape_string($bundlereference,$this->conn);
$sql = "UPDATE `ArchiveBundle`
SET `Issue` = '" . $_reason . "'
WHERE `BundleReference` = '" . $_bundlereference . "'";
mysql_query($sql, $this->conn);
die(mysql_error());
exit;
}
The form
<table>
<form method='post' action='addissue.php'>
<p>Reason: <input type='text' name='reason' /></p><br/>
<p><input type='hidden' name='bundlereference' id='Username'
value='" . $x['Reference'] . "' /></p>
<input type='submit' name ='add'/>
</form>
</table>
The process page
<?php
// First of all initialise the user and check for permissions
require_once "/var/www/users/user.php";
$user = new CHUser(2);
// Initialise the template
require_once "/var/www/template/template.php";
$template = new CHTemplate();
// And create a cid object
require_once "/var/www/Testing/DisplayWIPOnLocation.php";
$BundleProgress= new CHWIPProgress();
$reason = $_POST['reason'];
$reference = $_POST['bundlereference'];
$issue = $BundleProgress->UpdateReason($_POST['reason'],$_POST['bundlereference']);
Print "Your information has been successfully added to the database.";
$template->SetTag("content", $content);
echo $template->Display();
?>
I also want to know/learn what the best practices are for forms in php
The reason you aren't getting output is the following two lines. This is killing your script in place. Just remove these.
die(mysql_error());
exit;
Overall, it's not terrible. You're using objects, and you're sanitizing your user input before inserting into the db. I do have a couple suggestions.
Don't use die() in a production script. Handle errors and exceptions properly.
Look into prepared statements (PDO) or stored procedures for mysql.
Instead of the print "Your information has been added..." line, can you create a field in your template and pass in that value through your template class?
You set $reason and $reference then pass in the value from $_POST, making those unused variables. Maybe this is just due to testing code though?
Depending on your needs, you may want to consider checking that the data the form has received is valid before running an update query. What if $reason or $bundlereference aren't valid values?