Pass value from one php file to another php file - php

I create php file for my login.....
<?php
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
$tbl_name="user_master"; // Table name
$myusername=mysql_real_escape_string($_POST['uname']);
$mypassword=mysql_real_escape_string($_POST['passwd']);
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = "SELECT uid FROM "." ".$tbl_name. " "."WHERE uname = '$myusername' AND passwd= '$mypassword' ";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if($row = mysql_fetch_assoc($result))
//echo mysql_result($result,0); // for correct login response
{
echo "User Found";
}
else {
echo "No Such User Found";
}
?>
It is just like this way...So here I select uid. I want get this uid & connect it to another php file. Really I want to get the details of the registered user by mapping so many tables. So I wrote the php file for that also. In the query inside that php file I want to equal the uid I get from above php file to the user_locator_tbl(the table in my database) uid. I did that. But I didn't think its correct. So pls help me.......
I gave here my other php file also....also I'm not fluent php...It is new to me...
<?php
require_once("dataget.php");
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
// Table name
$conn = mysqli_connect($host,$user,$pswd,$db);
//mysql_select_db($db, $conn);
//run the query to search for the username and password the match
//$query = "SELECT * FROM "." ".$tbl_name. " "."WHERE uname = '$myusername' AND passwd= '$mypassword' ";
$query = "select user_master.uid,device_locator_tbl.imei,device_locator_tbl.speed,device_locator_tbl.datetime,device_locator_tbl.number,device_master.icon
from device_locator_tbl,device_master,device_registration,user_master where user_master.uid=device_registration.uid
AND device_registration.imei=device_master.imei AND device_registration.imei=device_locator_tbl.imei AND user_master.uid='$query'";
//echo ($result);
$resultarray = mysqli_query($conn,$query) or die("Unable to verify user because : " );
//if($row = mysql_fetch_assoc($result))
if($row = mysqli_fetch_assoc($resultarray))
//echo mysql_result($result,0); // for correct login response
{
$rows[] = $row;
}
// close the database connection
mysqli_close($conn);
// echo the application data in json format
echo json_encode($rows);
?>

First off, you should use prepared statements, the mysql_ functions are deprecated in PHP and create a real issue for SQL injection, particularly in a login.
But using your example, refer to: PHP Login & MySql Query
The questioned code & answer there is perfectly pertinent to what you have thus far, and a simple, vastly more secure way to accomplish everything you need:
The original posters script you see is meant to store the users info into a $_SESSION[] array, from the database query like you have. Once the login attempt is validated the header(location:) call that you see in the original questions code will redirect the user to the location required.
Once the user is redirected, all the information from your user table query will be stored in the $_SESSION array and from then on accessible like $_SESSION[loggedinuser][userid], $_SESSION[loggedinuser][email] etc.
Remember to configure your PHP install appropriately for destroying sessions via a timeout, and also consider a logout function to destroy the user session.
So you should edit your first page like this ONLY IF you are NOT/CANNOT switching over to PDO - remember if you use sessions you should start session on page top:
<?php
session_start();
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
$tbl_name="user_master"; // Table name
$myusername=mysql_real_escape_string($_POST['uname']);
$mypassword=mysql_real_escape_string($_POST['passwd']);
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = "SELECT uid FROM "." ".$tbl_name. " "."WHERE uname = '$myusername' AND passwd= '$mypassword' ";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if($row = mysql_fetch_assoc($result))
//echo mysql_result($result,0); // for correct login response
{
$_SESSION['uid'] = $row['uid'];
header("Location: nextpage.php");
//echo "User Found";
}
else {
echo "No Such User Found";
}
?>
And You can catch this value from next page like this:
<?php
session_start();
// this section validate your inner files no one can enter this file without login
if(empty($_SESSION['uid'])){
header("Location: index.php");
}
// now you can do whatever you like
echo $_SESSION['uid'];
require_once("dataget.php");
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
// Table name
$conn = mysqli_connect($host,$user,$pswd,$db);
//mysql_select_db($db, $conn);
//run the query to search for the username and password the match
//$query = "SELECT * FROM "." ".$tbl_name. " "."WHERE uname = '$myusername' AND passwd= '$mypassword' ";
$query = "select user_master.uid,device_locator_tbl.imei,device_locator_tbl.speed,device_locator_tbl.datetime,device_locator_tbl.number,device_master.icon
from device_locator_tbl,device_master,device_registration,user_master where user_master.uid=device_registration.uid
AND device_registration.imei=device_master.imei AND device_registration.imei=device_locator_tbl.imei AND user_master.uid='$query'";
//echo ($result);
$resultarray = mysqli_query($conn,$query) or die("Unable to verify user because : " );
//if($row = mysql_fetch_assoc($result))
if($row = mysqli_fetch_assoc($resultarray))
//echo mysql_result($result,0); // for correct login response
{
$rows[] = $row;
}
// close the database connection
mysqli_close($conn);
// echo the application data in json format
echo json_encode($rows);
?>

Related

login page with multiple databases

I have a website that I need users to be able to login to. It is currently on a different server from the company's actual website. I would like to have a single login form that checks for a username and password in multiple databases on the same server.
Heres the setup.
1 Database has 2 different tables that I need to check for username and password.
the other database has 1 table that I need to check.
I will have a checkbox for 1 of the tables in the first database. So the form will have 3 field. (Username, Password, and "I am a reporter" checkbox)
I believe that it has something to do with the UNION sql command.
I don't know a LOT about sql but I am trying to learn as I go...
Here is the code so far.. also, I hope someone will tell me whether the information will be passed securely or not.
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['uname']) || empty($_POST['pswd'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$uname=$_POST['uname'];
$pswd=$_POST['pswd'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$con = mysql_connect("10.0.0.3", "webaccess", "ccrweb");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("company", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from dbo.contacts where WebPwd='$password' AND WebAcctName='$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
header("location: "); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
It is not all complete yet and I am still researching but I am also trying to do this as quick as possible.
any help will be greatly appreciated!
It appears you make a connection declaring one name and then a different connection object name later.
$con = mysql_connect("10.0.0.3", "webaccess", "ccrweb");
$db = mysql_select_db("company", $connection);
I believe the later should use the same name $con and also at the end mysql_close($con);
First, you should use the mysqli_ or PDO API instead of mysql statements
If you need to use mysql, here is what to do:
$QueryReporter = mysql_query("SELECT * FROM $ReporterTable WHERE Username = '$Username' AND Password = '$Password'");
$QueryOthers = mysql_query("SELECT * FROM $UserTable WHERE Username ='$Username' AND Password = '$Password'");
if(mysql_num_rows($QueryReporter)==1){
//Its a reporter
}
else if(mysql_num_rows($QueryOthers)==1){
//Its not a reporter, but a user
}
else{
//Its no user or reporter, show error :)
}
EDIT:
If you are thinking about two different DB servers, you can use a function, then close the connection after the full query and return the result:
function CheckIfReporter($Username, $Password){
//DATABASE CONNECTION TO REPORTER DB
$Query = mysql_query("SELECT * FROM MyTable WHERE Username = '$Username' AND Password = '$Password'");
if(mysql_num_rows($Query)==1){
return TRUE;
}
//Else, no result:
else{
return FALSE;
}
//Close mysqlconnection:
mysql_close();
}
Now, make a similar function for user check,
if(CheckIfReporter($UsernameInput, $PasswordInput)==TRUE){
//Its a reporter
}
else if(CheckIfUser($UsernameInput, $PasswordInput)==TRUE){
//Its a user
}
else{
//Its none
}

Using the session variable after logging and in other php file

Please see the following code:
login.php
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("company", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from login where password='$password' AND username='$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
header("location: profile.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
profile.php
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "");
// Selecting Database
$db = mysql_select_db("company", $connection);
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select username from login where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
?>
<html> ............... </html>
Should we use the part of the code below in each php file that is shown below?
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "");
// Selecting Database
$db = mysql_select_db("company", $connection);
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select username from login where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
........... ?>
I learned creating the login.php and profile.php using this site.But when I see the profile.php it uses the part of the code above: Checking the connection and database and then using the $user_check=$_SESSION['login_user']; and then using the following code:
$ses_sql=mysql_query("select username from login where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
If I have another php file such as the following code to use the payment gateways:
send.php
<?php
include_once("sender.php");
$url = 'http://example.com/payment/gateway-send';
$api = ' Your-API ';
$amount = 1000;
$redirect = 'REDIRECT-PAGE';
$result = send($url,$api,$amount,$redirect);
if($result > 0 && is_numeric($result)){
$go = "http://example.com/payment/gateway-$result";
header("Location: $go");
}
?>
Should I add the following code in the beginning of the send.php file and also for other php files?
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "");
// Selecting Database
$db = mysql_select_db("company", $connection);
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select username from login where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
.................?>
I suggest you should to create a connection file say connection.php with the code -
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "");
// Selecting Database
$db = mysql_select_db("company", $connection);
?>
And another file security.php to set session variables.
session_start();// Starting Session
// Storing Session
$user_check = $_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql = mysql_query("select username from login where username = '$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
.................?>
And include those two files at the beginning of all the php files.
At send.php I can't find any db related operation or session check. So it is not needed to include those two files at send.php .

Query running in PHPmyadmin but not through PHP

I am trying to run a query from PHP which is not running but I can run the query from within phpMyAdmin
here is the code
<?php
ob_start();
//Delete Item question to admin and delete product
include"../storescripts/connect_to_mysql.php";
$conn = mysql_connect("$db_host","$db_username","$db_pass","$db_name") or die ("could not connect to mysql");
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete the item with ID '.$_GET['deleteid'].' ?Yes|No';
exit();
}
if(isset($_GET['yesdelete'])){
// Delete the actual product and delete picture also
//delete from database
$id_to_delete = $_GET['yesdelete'];
$manager=preg_replace('#[^A-Za-z0-9]#i','',$_GET['yesdelete']);
//$sql=mysql_query("SELECT id FROM admin WHERE username = '$manager' AND password='$password' LIMIT 1 ");
$sql = mysql_query( $conn ,"DELETE FROM products WHERE id=`$id_to_delete` LIMIT 1 ") or (mysql_error());
//echo 'The data at number ' . $id_to_delete . ' Deleted Sucessfully';
//mysqli_query("DELETE * FROM products WHERE id=`$id_to_delete`LIMIT1");// or (mysql_error());
//Unlink file from server
$pictodelete=("../inventory_images/$id_to_delete");
//echo $pictodelete;
if(file_exists($pictodelete)){
unlink($pictodelete);
}
// header("location:inventory_list.php");
//exit();
}
?>
I am new to PHP so your help is sought, i am able to connect to to database at another instance the code of which is following
<?php
//checking the user
ob_start();
session_start();
if (!isset($_SESSION["manager"])){
header ("location:admin_login.php");
exit();
}
//be sure to check if this manager SESSION value is in the database
$managerID=preg_replace('#[^0-9]#i','',$_SESSION["id"]);
$manager=preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["manager"]);
$password=preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["password"]);
//runMYSQL query to assertain that this is manager
//Connect to mysql database
include"../storescripts/connect_to_mysql.php";
$sql=mysql_query("SELECT*FROM admin WHERE id='$managerID' AND username='$manager' AND password='$password'LIMIT 1");
// make sure person exists in database
$existCount=mysql_num_rows($sql);
if ($existCount== 0)
{
echo "your data do not match our records";
exit();
}
?>
The code in connect_to_my_sql.php is as follows
<?php
/*
1: "die()" will exit the script and show an error statement if something goes wrong with the "connect" or "select" functions.
2: A "mysql_connect()" error usually means your username/password are wrong
3: A "mysql_select_db()" error usually means that the database does not exist
*/
// Place db host name Sometimes "localhost" but
// sometimes looks like this:>> ???mysql??.someserver.net
$db_host = "localhost";
//Place the username for the MySQL database here
$db_username = "storeuser";
//Place the password for the MySQL database here
$db_pass = "rajjar";
//Place the name for the MySQL database here
$db_name="mystore";
// Run the actual connection here
$conn = mysql_connect("$db_host","$db_username","$db_pass","$db_name") or die ("could not connect to mysql");
//mysql_select_db("$db_name") or die ("no database");
?>

Passing data between MySql and Objective C

I am working on a small social web application as a final project for my iOS class. I have a profile view controller where all the info about the user from the database is supposed to be displayed on the labels. The problem is that I don't really know the best way to do this. Here is my php script:
<?
// Database credentials
$host = 'localhost';
$db = 'blabla';
$uid = 'blabla';
$pwd = 'blabla';
// Connect to the database server
$link = mysql_connect($host, $uid, $pwd) or die("Could not connect");
//select the json database
mysql_select_db($db) or die("Could not select database");
// Create an array to hold our results
$arr = array();
//Execute the query
$rs = mysql_query("SELECT IdUser, username, fullname, phonenumber, facebook, instagram FROM login");
// Add the rows to the array
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
//return the json result.
echo '{"users":'.json_encode($arr).'}';
?>
So here I get the info about all the users in the database. I am sure this is not the right way to go, so I guess I need to change the SQL query to retrieve the data for the current user only. But how can I do this? Should I put the username which I enter on the login page into an extra variable and then pass it with JSON to this php script and add the 'WHERE username = 'blabla' statement to the SQL query then? If so, how can I pass the variable to this script with JSON?
Can you please give me some sample code? Or is there a different way to do this?
Thank you so much!
<?php
// Database credentials
$host = 'localhost';
$db = 'blabla';
$uid = 'blabla';
$pwd = 'blabla';
// Connect to the database server
$link = mysql_connect($host, $uid, $pwd) or die("Could not connect");
//select the json database
mysql_select_db($db) or die("Could not select database");
//Execute the query
$rs = mysql_query("SELECT IdUser, username, fullname, phonenumber, facebook, instagram FROM login");
// Add the rows to the array
$data = mysql_fetch_array($rs);
foreach($data as $rec){
echo "user: $rec<br>";
}
?>

Copying data from a MySQL table to another MySQL table not showing

I'm trying to make a registration form that validates the account by sending a validation code to the email. Once the user receive the code in his email he must click the link to validate his account(I simulated this using the localhost). BTW, I have 2 database for the registered members and for the temporary members(these are the members that are waiting for validation).
When the validation code is processed and matched, the data from the temporary table will be copied to the registered members table, after the copying is done the user data from temporary table will deleted.
when I checked my updated database(registered members table) the ID column had incremented but the username, password and email field has no data. what is the problem here?
here is the website I'm following for the tutorial but I did some little tweaks
http://phpeasystep.com/phptu/24.html
localhost/validated_email.php?passkey=639900974e5fc25626af1a6ce5da8b01
<html>
<body>
<?php
ob_start();
//define a function for temporary database (temporary_members)
function temporary_members_db(){
$host="localhost";
$db_username="root";
$db_password="";
$db="forum_members";
$db_table="temporary_members";
//=======================connect to database
mysql_connect("$host","$db_username","$db_password") or die("Could not connect to the database!");
mysql_select_db("$db") or die("database not found!");
}
function members_db() {
$host="localhost";
$db_username="root";
$db_password="";
$db="forum_members";
$db_table="members";
//=======================connect to database
mysql_connect("$host","$db_username","$db_password") or die("Could not connect to the database!");
mysql_select_db("$db") or die("database not found!");
}
//connect to the temporary_member table
temporary_members_db();
$code = $_GET['passkey'];
//execute mysql query to check the validation code
$check_code = "SELECT `validation_code` FROM `temporary_members`";
$execute_code = mysql_query($check_code);
$result_code = mysql_num_rows($execute_code);
if ($result_code==1) {
$rows=mysql_fetch_array($execute_code);
$username = $rows['username'];
$password = $rows['password'];
$email = $rows['email'];
$table_members = "members";
members_db();
$copy_values = "INSERT INTO $table_members(username, password, email) VALUES ('$username', '$password', '$email')";
$execute_copy = mysql_query($copy_values);
}
else {
echo "Wrong validation code";
}
if ($execute_copy) {
echo "Your account has been activated!";
//delete data from the temporary_members
$table_temporary_members = "temporary_members";
$delete_data = "DELETE FROM $table_temporary_members WHERE validation_code = '$code'";
$execute_delete = mysql_query($delete_data);
}
ob_end_flush();
?>
</body>
</html>

Categories