Return URL after validating loggedin user - php

I need to return a URL that opens a support chat window on a mobile app from my PHP function after validating the user is correctly logged in via the mobile app and provide them with the URL. Below is my code sample.
<?php
if((isset($_POST['key']) && $_POST['key'] != "") && isset($_POST['userName']) && $_POST['userName'] != "")
{
$acc = new userAccount();
//if($acc->clientloginIntoAccount($_POST['userName'],$_POST['passWord'],$_POST['key']) == 1)
$Response = array();
if($acc->ClientLoginEncryptionUpgrade($_POST['userName'], $_POST['passWord'], $_POST['key'], $Response))
{
$_SESSION['clientloggedin'] = $Response['details']['session_data'];
$_SESSION['clientloggedin']['cost_centre'] = $Response['details']['company'];
$_SESSION['clientloggedin']['time'] = $_POST['time'];
$_SESSION['primary_color_1'] = $Response['details']['primary_color_1'];
$_SESSION['primary_color_2']= $Response['details']['primary_color_2'];
$_SESSION['footer_colour']= $Response['details']['footer_colour'];
$_SESSION['email_color'] = $Response['details']['email_color'];
$_SESSION['client_logo'] = $Response['details']['client_logo'];
$_SESSION['link_color'] = $Response['details']['link_color'];
$_SESSION['menu_items'] = $Response['details']['menu_items'];
$_SESSION['menu_items_icons'] = $Response['details']['menu_items_icons'];
$employee = getTableValue("personnel","id","employee_number='{$_POST['key']}'");
$_SESSION['loggedin']['personnelID'] = $employee;
echo "<script>window.location.href='home';</script>";
return "<script>javascript:void($zopim.livechat.window.openPopout())</script>";
}
else
{
echo "<div class = 'bg-danger'> Incorrect username / password. Please try again. </div>";
?>

Related

How can I redirect one url to another?

I have an 'api' so to speak where I am trying to proxy an api on another server for an App.
The target url is formed like:
http://example.com/live/username/password/filename.mp4
how can I dynamically redirect to that?
here is the php I have so far which grabs the filename and user/password
<?php
if (isset($_GET['username']))
{
$username=$_GET['username'];
$password=$_GET['password'];
}
else if (isset($_POST['username']))
{
$username=$_POST['username'];
$password=$_POST['password'];
}
$action = isset($_GET['action']) ? $_GET['action'] : '';
$db = new SQLite3('./.dns.db');
$res = $db->query('SELECT * FROM dns');
$arr = array();
while ($row = $res->fetchArray(SQLITE3_ASSOC))
{
$arr[] = $row['url'];
foreach ($arr as $value)
{
$api_call = $value.'/player_api.php?username='.$username.'&password='.$password;
$api = json_decode(file_get_contents($api_call), TRUE);
$api2 = json_decode(json_encode($api["user_info"]) ,TRUE) ;
$auth = $api2["auth"];
if ($auth == 1)
{
$dns = $value;
}
}
}
if (isset($_GET['vod_id']) && $_GET['vod_id'] !== "")
{
$vodid = $_GET["vod_id"];
$vodinfo = file_get_contents($dns.'/player_api.php?username='.$username.'&password='.$password.'&action=get_vod_info&vod_id='.$vodid);
echo $vodinfo;
}
else if (isset($_GET['series_id']) && $_GET['series_id'] !== "")
{
$seriesid = $_GET["series_id"];
$seriesinfo = file_get_contents($dns.'/player_api.php?username='.$username.'&password='.$password.'&action=get_series_info&series_id='.$seriesid);
echo $seriesinfo;
}
else if ($action !== "")
{
$get_actions = file_get_contents($dns.'/player_api.php?username='.$username.'&password='.$password.'&action='.$action);
echo $get_actions;
}
else
{
$login = file_get_contents($dns.'/panel_api.php?username='.$username.'&password='.$password);
echo $login;
}
?>
The app will read from the JSON provided and grab the 'filename' and then attempt to go to /live/ on the api host, but this will lead too http://example2.net/live/username/password/filename.mp4
which doesn't exist.
I thought about maybe something in htaccess?
Im trying to provide the App with the http://example.com/live/username/password/filename.mp4
not the
http://example2.net/live/username/password/filename.mp4
(The example2.net is the $dns in the PHP)
Sorry I know this is a bad explanation - hopefully I've explained enough to be able to find an answer.
(1st post)
edit: I have been reading about turing folders in links to querystring where I can point to this
<?php
if (isset($_GET['username']))
{
$username=$_GET['username'];
$password=$_GET['password'];
$streamid=$_GET['streamid'];
}
else if (isset($_POST['username']))
{
$username=$_POST['username'];
$password=$_POST['password'];
$streamid=$_POST['streamid'];
}
header('Location: http://example.com/live/'.$username.'/'.$password.'/'.$streamid);
?>
I just need now to figure out how to use htaccess to turn the requested folder url into a query string from
example2.net/live/username/password/file.mp4 to
example2.net/live.php?username=username&password=password&streamid=streamid.mp4
I ended up using this which worked for .htaccess
RewriteEngine on
RewriteRule ^live\/([^\/]+)\/([^\/]+)\/([^\/]+) /path/to/api/live.php?username=$1&password=$2&streamid=$3 [L]

Login System in PHP for multi user

I am making a login system in php xampp. After correct authentication of the user they get redirected depending on what role they play. For Admin it goes to Admin Page and for Sales Person it goes to the main menu. In the code below you can see how the login is setup. Now my problem is: For example more than one user login as Sales they will be redirected to the main menu page. Now lets say user x logs in first then user y logs in. Now both are at the main menu page. Now when I refresh the page of the main menu I see user y's name even though I am as user x and on the same main menu page.
function Encrypt($Word)
{ //Encryption method
$ciphering = "AES-128-CTR"; //method of encryption
$options = 0;
// Non-NULL Initialization Vector for Encryption
$Encryption_iv = '1234567891011121';
// Store the Encryption key
$Encryption_key = "GeeksforGeeks";
// Use openssl_Encrypt() function to Encrypt the data
return openssl_encrypt($Word, $ciphering, $Encryption_key, $options, $Encryption_iv);
}
//Getting user information. SQL injection protection and XSS Attack.
$username = (htmlspecialchars(mysqli_real_escape_string($con, $_POST['user'])));
$password = htmlspecialchars(mysqli_real_escape_string($con, $_POST['pass']));
/* $UserOption = (htmlspecialchars(mysqli_real_escape_string($con, $_POST['Level'])));
$PinCode = htmlspecialchars(mysqli_real_escape_string($con, $_POST['Pin'])); */
$Option = htmlspecialchars(mysqli_real_escape_string($con, $_POST['option']));
$Hash = Encrypt($username);
$SalesHash = Encrypt($username);
$GetActivestmt = $con->prepare("SELECT Active FROM logins WHERE Username=?");
$GetActivestmt->bind_param("s", $Hash);
$GetActivestmt->execute();
$ActiveResult = $GetActivestmt->get_result();
//Fetching
if ($ActiveResult->num_rows === 0) exit("No Records");
while ($Active = $ActiveResult->fetch_assoc()) {
$ActiveRow = $Active['Active'];
}
$GetActivestmt->close();
global $ActiveRow;
$con->next_result();
/* if($UserOption == $row['User_Type'] && $Hash==$row['Username'] && password_verify($password, $row['HashPassword'])
&& $PinCode ==$row['PinCode']){
echo $row['User_Type'];
}else if($UserOption == $row['User_Type'] && $Hash==$row['Username']
&& password_verify($password, $row['HashPassword']) && $PinCode == $row['PinCode']){
echo $row['User_Type'];
}else{
echo '<script>alert("Info Mis-Match");</script>';
exit();
} */
if ($ActiveRow === 0) {
$GetLoginstmt = $con->prepare("SELECT * FROM logins WHERE Username=? LIMIT 1;");
$GetLoginstmt->bind_param("s", $Hash/* , $PinCode */);
$GetLoginstmt->execute();
$LoginResult = $GetLoginstmt->get_result();
//Fetching
if ($LoginResult->num_rows === 0) exit('<script>alert("User not found");</script>');
while ($Login = $LoginResult->fetch_assoc()) {
$Username = $Login['Username'];
$HashPassword = $Login['HashPassword'];
$UserType = $Login['User_Type'];
$Pin = $Login['PinCode'];
$ID = $Login['ID'];
}
$GetLoginstmt->close();
global $Username, $HashPassword, $UserType, $Pin;
echo "<script>alert('$Username');</script>";
$con->next_result();
if (
$Hash == $Username && password_verify($password, $HashPassword)
&& $Option == $UserType
) {
echo "<br/>";
if ($Option == "Admin") {
$UpdateItems = mysqli_query($con, "CALL Update_Items('$Hash')");
if ($UpdateItems) {
$_SESSION['HashUsername'] = $Hash;
$_SESSION['datetime'] = date('Y/m/d'); //storing date in datetime session
$url = "../PinCodes/VerifyPinForm.php"; //url to be redirected
echo '<script language="javascript">window.location.href ="' . $url . '"</script>'; //redirects the user to the main page
} else {
echo "Error in Query";
}
} else if ($Option == "Sales") {
$UpdateItems = mysqli_query($con, "CALL Update_Items('$SalesHash')");
if ($UpdateItems) {
$_SESSION['SalesHash'] = $Username;
$_SESSION['User_ID'] = $ID;
// setcookie("Username", $Hash, time()+84600, "/", '', '', true);
$_SESSION['datetime'] = date('Y/m/d'); //storing date in datetime session
$url1 = "../MainMenu/main.php";
echo '<script language="javascript">window.location.href ="' . $url1 . '"</script>';
}
} else {
echo "Error";
}
} else {
echo '<script>alert("Incorrect User Info");</script>';
}
} else {
echo '<script>alert("User Already Logged in.");</script>';
global $username, $password, $Option;
$_SESSION['HashUsername'] = $Hash;
$_SESSION['datetime'] = date("Y/m/d");
$_SESSION['SalesHash'] = $SalesHash;
if ($Option == "Sales") {
$UpdateItems = mysqli_query($con, "CALL Update_Items('$SalesHash')");
if ($UpdateItems) {
$url1 = "../MainMenu/main.php";
echo '<script language="javascript">window.location.href ="' . $url1 . '"</script>';
}
} else if ($Option == "Admin") {
$UpdateItems = mysqli_query($con, "CALL Update_Items('$Hash')");
if ($UpdateItems) {
$url1 = "../PinCodes/VerifyPinForm.php";
echo '<script language="javascript">window.location.href ="' . $url1 . '"</script>';
}
}
}
$con->close();
?>
<?php
require '../connection1.php';
function Decrypt($Word)
{ //decrypting data using openssl decrypt method
$ciphering = "AES-128-CTR";
$options = 0;
// Non-NULL Initialization Vector for decryption
$decryption_iv = '1234567891011121';
// Store the decryption key
$decryption_key = "GeeksforGeeks";
// Use openssl_decrypt() function to decrypt the data
return openssl_decrypt($Word, $ciphering, $decryption_key, $options, $decryption_iv);
}
if ($con) {
session_regenerate_id(true);
$User = $_SESSION['SalesHash'];
$UserID = $_SESSION['User_ID'];
$GetInfo = $con->prepare("SELECT * FROM logins WHERE Username=? AND ID=?");
$GetInfo->bind_param("si", $_SESSION['SalesHash'], $_SESSION['User_ID']);
$GetInfo->execute();
$GetResult = $GetInfo->get_result();
//Fetch info
if ($GetResult->num_rows === 0) exit(header("Location: ../Login/LogoutForm.html"));
while ($row = $GetResult->fetch_assoc()) {
$Active = $row['Active'];
$Username = $row['Username'];
$LoginTime = $row['Last_Login'];
$UserType = $row['User_Type'];
$ID = $row['ID'];
}
$GetInfo->close();
global $Active, $Username, $LoginTime;
}
if ($Active == 1 && $UserType == "Sales" && $Username == $User) {
} else {
header("Location: ../Login/Logout.html");
}
?>
This code is the main menu page. Now I don't know where I am going wrong.
I have started the session from xampp php.ini file.
You wouldn't need to store each salesperson in a session. What you want to do is store one user in the session, then have that user have access to many salespersons.
For instance your user table might have id, email address and password columns.
Then, your salespersons table would have id, user_id, and name.
In you session, you'd store which user_id was logged in. Then, one your page you could query something like SELECT * FROM salespersons WHERE user_id = $session['user_id']
If you use a modern PHP framework like Laravel you can handle this easily with relationships:
https://laravel.com/docs/7.x/eloquent-relationships
User authentication also comes baked out of the box:
https://laravel.com/docs/7.x/authentication
Edit: maybe I'm misunderstanding your question. If you dont want one user to access multiple salespeople, you don't need to worry about separating the sessions. A session by it's nature is a single user accessing your service. If you research how php sessions work there's a ton of resources out there to help get you started.

PHP authentication dialog keeps repeating

I'm using PHP and want to authenticate a user against an entry in a MySQL database. All pages use HTTPS.
The problem is when I enter the correct username and password, the authorize dialog box disappears then reappears with the username and password blank.
Does anybody know how to fix it?
Snippets of code:
<?php
session_start();
if($_SERVER["HTTPS"] != "on")
{
header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER ["REQUEST_URI"]);
exit();
}
require_once("../php-files/cookies.php");
require_once("../php-files/db_connect.php");
/* If user tries to bypass logging in then we need to redirect back
* to main page. First though, we need to get whether we're localhost or
* live production.
*/
if($_SESSION["atHome"] == true)
{
require_once("/Calendar/Month.php");
require_once("/Calendar/Month/Weekdays.php");
}
else
{
require_once("../Calendar/Month.php");
require_once("../Calendar/Month/Weekdays.php");
}
include("../php-files/create-calendar.php");
include("../php-files/put-footer.php");
include("../php-files/timestamp.php");
//if cookie not set redirect back to home page
// prevents people from getting this page by using /php-files/new_event.php
// unless they have a cookie set
if(!isset($_COOKIE['www_broken_com']))
{
if($_SESSION["atHome"] == true)
header("Location: https://localhost");
else
header("Location: https://www.broken.com");
}
$theCookie = $_COOKIE['www_broken_com'];
$theCookie = explode(";",$theCookie);
//check to see if an Admin is going to enter a new event
//if so ask if they want to enter or to approve events submitted
function authenticate_user()
{
header('WWW-Authenticate: Basic Realm="New"');
header("HTTP/1.0 401 Unauthorized");
return(FALSE);
}
$authenticate = TRUE;
$authorized = FALSE;
$authorizedName = "";
$privleges = "";
//Compare the email address of the person currently accessing and see if
//he's in the admin database. If so then he as admin privleges.
$db_conn = new db_stuff();
$db = $db_conn->connect();
$query = "SELECT * FROM admin WHERE email = '$theCookie[5]'";
if(!$result = $db->query($query)) exit("Could not select for new event");
if($result && $result->num_rows != 0)
{
if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']))
$authenticate = authenticate_user();
if($authenticate == TRUE)
{
$userName = $_SERVER['PHP_AUTH_USER'];
$userPwd = $_SERVER['PHP_AUTH_PW'];
$query = "SELECT * FROM admin WHERE name = '$userName' AND pwd = PASSWORD('$userPwd')";
if(!$result = $db->query($query))
echo "<br />Could not select for authentication";
if($result && $result->num_rows != 0)
{
while($admin = $result->fetch_array())
{
$authorizedName = $admin[2] . " " . $admin[1];
}
$authorized = TRUE;
$privleges = ", you have administrator privleges.";
$_SESSION['authorizedName'] = $authorizedName;
}
}
else
{
exit("In FALSE");
$authorized = FALSE;
$_SERVER['PHP_AUTH_USER'] = "No one";
}
}
else
$privleges = " ";
After much digging......
run phpinfo() to see if: Server API = CGI/FastCGI (It should be the 4th line from the top)
If it is set, you can't do basic-authorization without a work-around.
Common workaround is to alter htaccess and add this line: RewriteRule .*-[E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
This worked for me.
See stackoverflow: Basic Authentication with PHP gives an endless loop for more info.

web service for mobile application in yii

In my Yii web application I want to write a web service for mobile application. I create a url for access student details with GET method. That I want to change GET method to POST method or PUT method. My url is,
url/index.php/user/login/studentdetails/?username=demo
I am getting this username from client side and giving the response from server side to client side in json format.
My code is,
public function actionStudentdetails() {
if (isset($_GET['username'])) {
$user = Users::model()->findByAttributes(array('username' => $_GET['username']));
$usertypeid = $user->usertypeid;
if ($usertypeid === '1') {
$studentid = $user->userid;
} else if ($usertypeid === '3') {
$guardianid = $user->userid;
$studentid = $_GET['studentid'];
} else {
$employeemasterid = $user->userid;
}
$student = Student::model()->findByPk($studentid);
header('Content-type: application/json');
$response["student_admissionno"] = $student->student_admissionno;
$response["student_firstname"] = $student->student_firstname;
$response["student_middlename"] = $student->student_middlename;
$response["student_lastname"] = $student->student_lastname;
$response["student_admissiondate"] = $student->student_admissiondate;
$response["student_dob"] = $student->student_dob;
$response["student_gender"] = $student->student_gender;
$response["student_religion"] = $student->student_religion;
$response["student_caste"] = $student->student_caste;
$response["student_address1"] = $student->student_address1;
$response["student_address2"] = $student->student_address2;
$response["student_city"] = $student->student_city;
$response["student_state"] = $student->student_state;
$response["success"] = 1;
$response["message"] = "success";
echo json_encode($response);
}
}
}
Please help me.
you can try this code for webserivce. you can used any method GET or POST Method of data posting in server side.
StudentController.php
public function actionStudentdetails() {
$json_data = array();
$params = isset($_REQUEST) ? $_REQUEST: "";
if (!empty($params)) {
$username = $params['username'];
if($username == "") {
$json_data['success'] = false;
$json_data['message'] = 'Username are required.';
} else {
$user = Users::model()->findByAttributes(array('username' => $params['username']));
$usertypeid = $user->usertypeid;
if ($usertypeid === '1') {
$studentid = $user->userid;
} else if ($usertypeid === '3') {
$guardianid = $user->userid;
$studentid = $_GET['studentid'];
} else {
$employeemasterid = $user->userid;
}
$student = Student::model()->findByPk($studentid);
header('Content-type: application/json');
$json_data["student_admissionno"] = $student->student_admissionno;
$json_data["student_firstname"] = $student->student_firstname;
$json_data["student_middlename"] = $student->student_middlename;
$json_data["student_lastname"] = $student->student_lastname;
$json_data["student_admissiondate"] = $student->student_admissiondate;
$json_data["student_dob"] = $student->student_dob;
$json_data["student_gender"] = $student->student_gender;
$json_data["student_religion"] = $student->student_religion;
$json_data["student_caste"] = $student->student_caste;
$json_data["student_address1"] = $student->student_address1;
$json_data["student_address2"] = $student->student_address2;
$json_data["student_city"] = $student->student_city;
$json_data["student_state"] = $student->student_state;
$json_data['success'] = true;
$json_data['message'] = "Data found Successful.";
}
} else {
$json_data['success'] = false;
$json_data['message'] = "Please try again.";
}
echo json_encode($response);
}

want to place part of php code somewhere else on page

I'm very new to php. I found some CMS like code for east text editing here on SO and now I'm trying to implement it on our micro site.
My problem is, that I want login error report to show on exact position on the page - just under the login button.
Can someone tell me how can I put that error report text whereever I want? I don't want to override it with CSS positioning.
In basic, I want to put that p class="error":
<?php
if (empty($_POST) && isset($_GET['action'])) {
$action = $_GET['action'];
switch ($action) {
case 'logout':
session_unset();
session_destroy();
break;
}
}
if (!isset($_SESSION['user'])) {
$user = '';
$pass = '';
if (isset($_POST['login'])) {
$user = strtolower(trim($_POST['user']));
$pass = $_POST['pass'];
$errors = array();
if ($user == '' || $user != '1') {
$errors['user'] = '';
}
if ($pass == '' || $pass != '1') {
$errors['pass'] = '';
}
if (empty($errors)) {
$_SESSION['user'] = $user;
} else {
echo '<p class="error">Insert correct ';
if (isset($errors['user']))
echo 'name';
if (count($errors) == 2)
echo ' a ';
if (isset($errors['pass']))
echo 'password';
echo '.</p>', "\n";
}
}
}
if (isset($_SESSION['user'])) {
$user = $_SESSION['user'];
?>
somewhere else in the whole code of my page. Do I need to cut out something from that php code, or do I need to write new part of code for that?
Thank you for you help, Matej
Instead of just doing 'echo' all over the place, which means you get output at the place where the PHP code is embedded in the page, set some flags/message variables to output later.
e.g.
<?php
$errors = false;
$msgs = '';
if (....) {
$errors = true;
$msgs = "something dun gone wrong";
}
?>
... various bits of your html go here ...
<?php if ($errors) { echo $msgs; } ?>
... more html here ...

Categories