I am in a complicated situation. I have two projects. One is designed using Yii Framework, another one includes only pure PHP code (I mean no framework). What I want to do is that, when user logged in the project, he/she should be logged in Yii project either. I tried to set session_id in Yii project, but it didn't work. I am redirecting user by using php header function in order to Yii project in order to let user log in. Here are the codes:
PHP project:
if (isset($_POST['giris-yap'])) {
$_POST['eposta'] = $this->cstring->validEmail($_POST['eposta']);
$_POST['sifre'] = md5($_POST['sifre']);
if ($_POST['eposta'] != '' && $_POST['sifre'] != '') {
$params = array(
'e-posta' => $_POST['eposta'],
'sifre' => $_POST['sifre']
);
$sonuc = $this->loginKendim($params);
if ($sonuc) {
$_SESSION['_utmkendim'] = md5('üyegirişyaptı'.$_POST['eposta']);
//mya user authentication
if($_SERVER["REMOTE_ADDR"] = "88.248.192.175")
{
header("Location: https://mya.genel.com/?sessionId=" . $_COOKIE["PHPSESSID"]);
exit;
}
//end of mya user authentication
header("Location: https://www.kendim.com/panel");
exit;
}
else
$this->_kayithata = 1;
}
else
$this->_kayithata = 1;
}
Yii Project:
public function beforeAction($action) {
if(isset($_GET["sessionId"]) && $_GET["sessionId"] != "")
{
Yii::app()->session->setSessionID($_GET["sessionId"]);
session_id($_GET["sessionId"]);
header("Location: https://www.kendim.com/panel");
exit;
}
# mya wl-api den gelen kullanıcıyı login edelim.
if(isset($_GET['_MYAU'])){
$_useruniqueid = Yii::app()->CString->CleanSTR($_GET['_MYAU']);
$userlogin = UserslogLogin::model()->findByAttributes(array('login_uniqueid' => $_useruniqueid ));
if($userlogin){
$user = UsersAccounts::model()->findByPk($userlogin->user_id, array('select' => 'user_id, user_name, user_email, user_pass'));
$identity = new UserIdentity($user->user_email, $user->user_pass);
$identity->id = $user->user_id;
$identity->name = $user->user_name;
$identity->username = $user->user_email;
$duration = 3600*24; //$this->rememberMe ? 3600*24*30 : 1800; // 30 days
Yii::app()->user->login($identity, $duration);
Yii::app()->request->redirect('/anasayfa');
Yii::app()->end();
}else{
$action = 'actionError';
$this->$action();
Yii::app()->end();
}
}
# kullanıcı login değilse indexe yönlendir
if(Yii::app()->user->isGuest){
$action = 'actionIndex';
$this->$action();
Yii::app()->end();
}else{
$this->getuser = UsersAccounts::user();
Controller::$projectModel = Projects::loadModel($this->getuser->project_code);
}
return parent::beforeAction($action);
}
I don't think the problem was the framework. The problem are the domains, as DaSourcerer guessed.
Take a look at this previous post:
Preserving session variables across different domains
Ok I found the solution. I've forgotten using session_start();. Problem is solved. I can transfer session between domains right now.
Related
I have installed the Xibo CMS 1.7 version and able to log in and use CMS properly. After that, according to the requirement, I have upgraded my CMS to 1.8 version. I have already taken the backup of all required files as well as the database. I have followed steps for upgrade CMS from 1.7 to 1.8 from this link.
https://xibo.org.uk/docs/setup/upgrade-manual-custom-install
I am able to upgrade to 1.8 from 1.7 but I am not able to log in into CMS. I have debugged the code and found that in session token is not stored. But in CMS version 1.7 I am able to get those session values. I have debugged below code in CMS files
public static function CheckToken($tokenName = "token")
{
if (!isset($_POST[$tokenName]) || !isset($_SESSION[$tokenName]))
return false;
if ($_POST[$tokenName] == $_SESSION[$tokenName])
{
// See if its still in Date
if (($_SESSION[$tokenName.'_timeout'] + 1200) <= time())
{
return false;
}
return true;
}
else
{
unset($_SESSION[$tokenName]);
Debug::LogEntry('error', "Form token incorrect from: ". $_SERVER['REMOTE_ADDR']. " with token [" . $_POST[$tokenName] . "] for session_id [" . session_id() . ']');
return false;
}
}
and below code from index.class.php file
function login()
{
$db =& $this->db;
$user =& $this->user;
global $session;
// this page must be called from a form therefore we expect POST variables
$username = Kit::GetParam('username', _POST, _USERNAME);
$password = Kit::GetParam('password', _POST, _PASSWORD);
$referingpage = rawurldecode(Kit::GetParam('referingPage', _GET, _STRING));
// Check the token
if (!Kit::CheckToken()) {
// We would usually issue a HALT error here - but in the case of login we should redirect instead
// Split on & and rejoin with &
$params = explode('&', $referingpage, 3);
$referingpage = implode('&', $params);
$session->set('message', __('Sorry the form has expired. Please refresh.'));
header('Location:index.php?' . $referingpage);
exit;
}
if ($user->login($username,$password))
{
$userid = Kit::GetParam('userid', _SESSION, _INT);
$session->set_user(session_id(), $userid, 'user');
}
Debug::LogEntry('audit', 'Login with referring page: ' . $referingpage);
if ($referingpage == '')
{
header('Location:index.php?p=index');
}
else
{
// Split on & and rejoin with &
$params = explode('&', $referingpage, 3);
unset($params['message']);
$referingpage = implode('&', $params);
header('Location:index.php?' . $referingpage);
}
exit;
}
can anyone help me to resolve this issue?
My website is nearly ready to be released - an online game. One of the final problems I am facing is that the login form does not seem to be working on Google Chrome on MOBILE only. The website and form work perfectly on the Edge browser on mobile, and it also works perfectly on Chrome and all other browsers on PC - it's just Google Chrome on mobile for some reason. It's important as users of the game will need mobile access as I believe that it's the way forward.
I imagine it's something to do with cookies/cache - despite flushing the cache on mobile and enabling cookies, it still doesn't seem to work. Below is the script I am using - can anyone help!?
<?php
define('BASEPATH', true);
require('system/config.php');
if($_GET['e'] != '' && is_numeric($_GET['e'])){$ref_id = $db->EscapeString($_GET['e']); $_SESSION['NGRefCookie'] = $ref_id;}elseif(isset($_SESSION['NGRefCookie'])){$ref_id = $_SESSION['NGRefCookie'];}else{$ref_id = 0;}
if($config['affiliate_module']){
if(!empty($_GET['aff']) && is_numeric($_GET['aff'])){
$aff_id = $db->EscapeString($_GET['aff']);
$_SESSION['NGACookie'] = $aff_id;
}elseif(isset($_SESSION['NGACookie'])){
$aff_id = $_SESSION['NGACookie'];
}else{
$aff_id = 0;
}
}
$orign = empty($_GET['orign']) ? '/game/?side=startside' : $_GET['orign'];
if (IS_ONLINE)
{
header("Location: " . $orign);
exit;
}
$tSource = $_SERVER['HTTP_REFERER'];
if(!empty($tSource)){
$main_domain = parse_url($config['base_url']);
$http_referer = parse_url($tSource);
if($http_referer['host'] != $main_domain['host']){
setcookie('refSource', $db->EscapeString($tSource), time()+60*60*24, '/');
}
}
$sider = array(
'login' => 'login',
'signup' => 'signup',
'recover' => 'recover',
'contact' => 'contact'
);
$side = $sider[$_GET['side']];
if (isset($_COOKIE['MZ_Language']) && $languages_supported[$_COOKIE['MZ_Language']])
{
$langBase_lang = $_COOKIE['MZ_Language'];
}
if (isset($_GET['setLang']) && $languages_supported[$_GET['setLang']])
{
$lang = $languages_supported[$_GET['setLang']];
$langBase->language = $lang[0];
setcookie('MZ_Language', $langBase->language);
}
Thank you!
After doing my SQL Schema (Different types of users redirected to same page (index.php) with different content), I'm starting to make my login system.
I now have this:
function login($email,$password){
$mysqli = $this ->dbConnect();
if($mysqli){
$strQuery = "SELECT USERS.ID, USERS.EMAIL, TYPES.NAME FROM `USERS` LEFT JOIN `TYPES` ON USERS.TYPEID = TYPES.ID WHERE `EMAIL` = '$email' AND `PASSWORD` = '$password'";
$recordSet = $mysqli->query($strQuery);
$row = $recordset->fetch_assoc();
if($recordset->num_rows>0){
$_SESSION['auth'] = $row['ID'];
$_SESSION['username'] = $row['EMAIL'];
$_SESSION['type'] = $row['NAME'];
header ("location:"index.php");
return true;
}
//....
}
}
Does this look good? Is the query right? Any suggestions for improvement?
UPDATE
I have my login working now. And it's redirecting to index.php. But in index php I don't have acess to the $_SESSIONS variables i have stored on my function login. Is there any problem with the attribuitions? Placing the header inside the function not good?
Thanks :)
I summarized the previous comments.
1. Issue: you didn't used the same variables
function login($email,$password){ and $strQuery = " ... WHERE EMAIL = '$email' AND PASSWORD = '$password'";
2. Recomendation: use the same namming convention
On your SQL request you used two way to use fields: USERS.EMAIL and EMAIL = (with ` arround).
Use the same. This will be easier for later & debugging.
i.e.: of course, you should not use table.field each time. Not mandatory for example if you have only one table OR if the fields are not shared between them. For my perosnnal usage, I always use this table.field. This will prevent any future issue :)
3. Protect your data from any injection
Example:
$post_email = isset($_POST['email']) ? htmlspecialchars($_POST['email']) : null;
Alter call
$this->login($post_email, ...)
And finally use something like this to protect your data:
$email = $mysqli->real_escape_string($email);
and you are ready for your request:
" SELECT [..] FROM users as u [...] WHERE u.email = '$email' "
4. Or use specific functions
Example (real_escape_string not needed anymore):
$stmt = $dbConnection->prepare('SELECT * FROM users WHERE email = ? AND password = ?');
$stmt->bind_param('s', $email);
$stmt->bind_param('s', $password);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
http://php.net/manual/fr/class.mysqli.php
5. Sessions
If you want to activate sessions on a spacific page, the first code (at the first line) should be session_start().
Calling this method will activate the sessions and load the $_SESSION variable with content.
<?php // index.php
session_start(); // first line
// ... code
var_dump($_SESSION);
?>
&
<?php // page.php
session_start(); // first line
// ... code
$_SESSION['test'] = time();
Header('Location: index.php');
?>
Visit index.php -> nothing on the debug
Visit page.php -> you will be redirected on index.php
On index.php -> you will have data
Enjoy session :p
6. Handle specific data
To begin with, you should coose a way to store the credential access (ACL) for each user. For example, store on the database some values as 100001, and each number is a yes/no access for a specific action (binary access mode) ; another system is to store the level '1,2,3,4,5' ... or 'member,customer,admin, ...'. So many ways :)
I will choose the USER.ACCESS = member|customer|admin solution
On the login page
// is user successfully logged
$_SESSION['access'] = $row['access']; // member|customer|admin
// Header('Location: index.php');
On any page of your site:
if( in_array($_SESSION['access'], ['member', 'admin']) ) {
echo 'You are a member, you can see this part';
}
if( in_array($_SESSION['access'], ['customer', 'admin']) ) {
echo 'You are a customer, you can see this part';
}
Or
if( checkAccess() ) {
echo 'Welcome user !';
if( checkAccess(['member', 'customer']) ) {
echo 'This is a section for member, customer or admin :)';
}
if( checkAccess('member') ) {
echo 'You are a member, you can see this part';
}
if( checkAccess('customer') ) {
echo 'You are a customer, you can see this part';
}
}
function checkAccess($types = null) {
if( !isset($_SESSION['access']) )
return false; // not logged
if( is_null($types) )
retun true; // if empty, provide info about loggin.
// admin has always access to all sections of the website
$hasAccess = in_array($_SESSION['access'], ((array) $types) + ['admin']);
return $hasAccess; // user is logged + has accessor not ?
}
Of course, you can also use includes
if( checkAccess('member') ) {
include 'secret_page_for_member.php';
}
Or, at the begening of the included page:
<?php
if( !checkAccess('admin') ) {
return '403 - Not authorized';
// die('403');
// throw new Exception('403');
}
// your code
?>
Hello guys I'm new to composer thing. Previously I had configured dropbox manually in my codeigniter project but my head asked me to do it using composer now. I have configured composer somehow and installed dropbox using composer. Now this was my login function which I used before
public function login() {
// $this->CI->session->set_userdata('state', 1);
$this->CI->session->dropbox_success = false;
$oauth = new Dropbox_OAuth_PHP($this->CI->config->item('APP_KEY'), $this->CI->config->item('APP_SECRET'));
$this->dropbox = new Dropbox_API($oauth);
if ($this->CI->session->state) {
$state = $this->CI->session->state;
} else {
$this->CI->session->set_userdata('state', 1);
$state = 1;
}
switch ($state) {
/* In this phase we grab the initial request tokens
and redirect the user to the 'authorize' page hosted
on dropbox */
case 1 :
// echo "Step 1: Acquire request tokens\n";
$tokens = $oauth->getRequestToken();
// echo "<a href='".$oauth->getAuthorizeUrl(site_url())."' >Authorize</a>";
// header('Location: '. $oauth->getAuthorizeUrl());
echo "<img width='30px' src='" . base_url() . "somePAth'> Connect Dropbox";
$this->CI->session->set_userdata('state', 2);
$this->CI->session->set_userdata('oauth_tokens', $tokens);
return FALSE;
/* In this phase, the user just came back from authorizing
and we're going to fetch the real access tokens */
case 2 :
if (!$this->CI->session->oauth_tokens) {
$this->CI->session->set_userdata('state', 1);
header("Location: ?");
}
$oauth->setToken($this->CI->session->oauth_tokens);
$tokens = null;
try {
$tokens = $oauth->getAccessToken();
} catch (Exception $e) {
$this->CI->session->set_userdata('state', 1);
header("Location: ?");
return false;
}
$this->CI->session->set_userdata('state', 3);
$this->CI->session->set_userdata('oauth_tokens', $tokens);
header("Location: ?");
case 3 :
// echo "The user is authenticated\n";
$this->CI->session->dropbox_success = true;
$oauth->setToken($this->CI->session->oauth_tokens);
echo "<a class='btn btn-primary float-right' href=" . base_url('somePath') . ">Disconnect Dropbox</a>";
return true;
}
}
Now after I installed dropbox using composer and after going through the configration I created the app-info.json file and included the code which dropbox asked me to add in the code which is $oauth = dbx\AppInfo::loadFromJsonFile("../config/app-info.json"); in place of the second uncommented line but it's not working. It is throwing me this error.
ERROR : Exception of type 'Error' occurred with Message: Class 'dbx\AppInfo' not found in File D:\Ampps\www\softcake\application\libraries\Dropbox.php at Line 30
So can somebody please guide me what is it that I'm doing wrong and redirect me to some solution which would help me in configuring drop box in my app. Thanks in advance
I have a website running on a less well known CMS called Ushahidi. There is built in OpenID functionality where folk can login with Facebook or Google.
I don't have enough dev skills to understand whats happening here but, it appears that I've almost got it working, except, I'm receiving the following error when trying to test it out on my own Google login:
An error was detected which prevented the loading of this page. If
this problem persists, please contact the website administrator.
application/controllers/login.php [503]: Undefined variable: user
I suspect, but am not sure, that defining a variable is easy enough but since I lack the knowledge I hoped to ask someone on here if they could see where I need to define the variable. Line 503 is part of a larger code block of about 100 lines, I know that it's not good practice to post larger chunks of code on here but I'm really unsure of what is and is not relevant. So forgive me. I have highlighted in bold where line 503 is. Can anyone point out what I must do here?
// OpenID Post
try
{
$openid = new OpenID;
// Retrieve the Name (if available) and Email
$openid->required = array("namePerson", "contact/email");
if( ! $openid->mode)
{
if(isset($_POST["openid_identifier"]))
{
$openid->identity = $_POST["openid_identifier"];
header("Location: " . $openid->authUrl());
}
}
elseif ($openid->mode == "cancel")
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = "You have canceled authentication!";
}
else
{
if ($openid->validate())
{
// Does User Exist?
$openid_user = ORM::factory("openid")
->where("openid", $openid->identity)
->find();
if ($openid_user->loaded AND $openid_user->user)
{
// First log all other sessions out
$auth->logout();
// Initiate Ushahidi side login + AutoLogin
$auth->force_login($openid_user->user->username);
// Exists Redirect to Dashboard
**(THIS IS LINE 503)** url::redirect($user->dashboard());
}
else
{
// Does this openid have the required email??
$new_openid = $openid->getAttributes();
if ( ! isset($new_openid["contact/email"]) OR
empty($new_openid["contact/email"]))
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $openid->identity . " has not been logged in. No Email Address Found.";
}
else
{
// Create new User and save OpenID
$user = ORM::factory("user");
// But first... does this email address already exist
// in the system?
if ($user->email_exists($new_openid["contact/email"]))
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $new_openid["contact/email"] . " is already registered in our system.";
}
else
{
$username = "user".time(); // Random User Name from TimeStamp - can be changed later
$password = text::random("alnum", 16); // Create Random Strong Password
// Name Available?
$user->name = (isset($new_openid["namePerson"]) AND ! empty($new_openid["namePerson"]))
? $new_openid["namePerson"]
: $username;
$user->username = $username;
$user->password = $password;
$user->email = $new_openid["contact/email"];
// Add New Roles
$user->add(ORM::factory('role', 'login'));
$user->add(ORM::factory('role', 'member'));
$user->save();
// Save OpenID and Association
$openid_user->user_id = $user->id;
$openid_user->openid = $openid->identity;
$openid_user->openid_email = $new_openid["contact/email"];
$openid_user->openid_server = $openid->server;
$openid_user->openid_date = date("Y-m-d H:i:s");
$openid_user->save();
// Initiate Ushahidi side login + AutoLogin
$auth->login($username, $password, TRUE);
// Redirect to Dashboard
url::redirect($user->dashboard());
}
}
}
}
else
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $openid->identity . "has not been logged in.";
}
}
}
catch (ErrorException $e)
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $e->getMessage();
}
The problem is that the code is using $user several lines before it's actually defined. It might be a typo, though - maybe $openid_user->user->dashboard() at line 503 might work, though it's a WAG.