I'm trying to access my file where it contains a home page using a function from another file (redirect.php). MyWebsite/main/main.html this is the location of my file that I want to access. I stuck in here redirect::toMain('main.html'); don't have a idea how to link the full path so I will be directing to the home page. I tried to pass ('main.html') value to the function toMain() but it didn't work. Location of folder below.
So MyWebsite is the main folder and it contains sub-folder listed below.
function (folder) contains a redirect function
main (folder) contains a html. main.html where it set as my home page. This is where the user will redirect.
Class: redirect.php Location: MyWebsite/function/redirect.php
<?php
class redirect
{
public static function toMain($location = null)
{
if($location)
{
header('Location: ' . $location);
exit();
}
}
}
$a = new redirect();
?>
loginProcess.php
<?php
session_start();
require_once('../connection/connection.php');
require_once('../connection/loginCRUD.php');
require_once('../function/redirect.php');
if(isset($_POST['submit']))
{
$dbusername = $_POST['loginUsername']; //Store value of textfield in array
$dbpassword = $_POST['loginPassword'];
if(!empty($dbusername) && !empty($dbpassword))
{
if((new loginCRUD)->readLogin($dbusername,$dbpassword)) //If true
{
// echo "You are logged in!";
$_SESSION['loginUsername'] = $dbusername;//Session are stored in array.
// redirect the user to the home page
redirect::toMain('main.html');
}
else
{
echo "Incorrect username and/or password";
}
}
}//end of isset
?>
Here is one way that I would do this:
class redirect
{
private static $baseUrl = 'http://localhost/MyWebsite/main/';
public static function toMain($location = null)
{
if($location)
{
header('Location: ' . self::$baseUrl . $location);
exit();
}
}
}
The $baseUrl can also be this:
private static $baseUrl = '/MyWebsite/main/';
Make sure that MyWebsite starts with http:// or it will redirect to a relative URL. You don't need $a = new redirect(); since you are accessing the methods statically.
Now you can do this:
redirect::toMain('main.html');
Related
I have a problem with my script. I have been using this same script for months. Lat week I got a message from my client that cannot access their
dashboard anymore. I check it was showing too much redirect problem. I
quickly made attempt to solve this programming but all availed. I found out
that the session actually set on the Login page because I echo it out
without redirecting, but whenever I redirect to member dashboard the session
variable will be undefined. I have gone through other people similar problem
on this forum but none were able to proffer solution to my problem. Because
this same script has been working for months. Please take a look at the code
and help me out.
This is Login page. Login.php The session actually set because when display LoginId when I echo echo it out. but lost when redirecting to another page. though It was working for more four months before this unexpected problem
<?php
require("includes/config.php");
require_once(ROOT_PATH . "main/class.member.php");
$auth_member = new MEMBER();
if($auth_member->is_loggedin() != ""){
$auth_member->redirect(BASE_URL.'member');
}
if(isset($_POST['loginMemBtn'])){
$userLoginID = strip_tags($_POST['userID']);
$password = strip_tags($_POST['password']);
if($auth_member->memberLogin($userLoginID, $password)){
$auth_member->redirect(BASE_URL.'member');
}
else{
$error[] = "Inccorrect Login Details!";
}
}
?>
class.member.php
This is the class that holds all the member details and where the session
was set. It contain MemberLogin Function
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once(ROOT_PATH.'includes/dbconnect.php');
// Class
class MEMBER{
private $connect;
public function __construct(){
$database = new Database();
$db = $database->dbConnection();
$this->connect = $db;
}
public function lastInsertId(){
return $this->connect->lastInsertId();
}
public function runQuery($sql){
$stmt = $this->connect->prepare($sql);
return $stmt;
}
public function memberLogin($userLoginID, $password){
try {
$stmt = $this->connect->prepare("SELECT * FROM members
WHERE status='Active'
AND (email=:email OR phone=:phone OR username=:email)
");
$stmt->execute(array(':email'=>$userLoginID, ':phone'=>$userLoginID));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0) {
if(password_verify($password, $userRow['password'])) {
$_SESSION['member_session'] = $userRow['login_id'];
return true;
}else{
return false;
}
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
public function is_allowuser(){
if(isset($_SESSION['member_session'])) {
return true;
}
}
public function redirect($url){
header("Location: $url");
}
public function doMememberLogout(){
session_destroy();
unset($_SESSION['member_session']);
return true;
}
}
?>
session.php this file that check whether session is set or not and it
include i to all other script
<?php
$session = new MEMBER();
if(!$session->is_allowuser()){
$session->redirect(BASE_URL.'login');
exit();
}else{
$auth_member = new MEMBER();
$loginID = $_SESSION['member_session'];
$stmt = $auth_member->runQuery("SELECT * FROM members WHERE
login_id=:loginID");
$stmt->execute(array(":loginID"=>$loginID));
$userInfo = $stmt->fetch(PDO::FETCH_ASSOC);
if($userInfo['status'] != 'Active'){
unset($_SESSION['member_session']);
}
}
?>
This is dashboard.php this is the page that member redirect to from Login
Page
<?php
require("../includes/config.php");
require_once(ROOT_PATH . "main/class.member.php");
require_once(ROOT_PATH . "main/session.php");
//echo $_SESSION['member_session'];
?>
public function redirect($url){
header("Location: $url");
exit;
}
Use exit after header call in redirect method of class.member.php file
I have to pass parameter through index, The the parameter of the index is used for user acess,
in my web site I gave each user different URL(www.domain.com/username)
as the user enter url it get to login page;
Now the url is www.domain.com/user_Method/username
its working fine , I want it as www.domain.com/username;
function user_Method($name)//LOGIN of store users According to privilage;
{
if($name=="")//if empty Url
{
redirect($this->config->base_url()."Error");
}
else if($name)
{
$data['storeid']=$this->admin_lib->get_where_id();//Get Store details
if($data['storeid']!="")
{
$this->load->view('login',$data);
}
else
{
redirect($this->config->base_url()."Error");
}
}
}
Set the base_url in config file and assign username to a variable then redirect to Base URL appended with username.
$config['base_url'] = 'http://www.example.com/';
$var = username;
redirect(base_url().$var);
When you want to pass a username or a id you may need to configure route
On the routes.php file Examples
$route['default_controller'] = 'test';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['(([^/]+)/?)'] = 'test/$1';
$route['error'] = 'test/error';
$route['(([^/]+)/?)'] = 'test/user_Method/$1';
User Guide http://www.codeigniter.com/user_guide/general/routing.html
Working image
<?php
class Test extends CI_Controller {
function index($somename = null) {
$somename = 'example';
if($somename == "") {
redirect(base_url() . 'error');
} else {
redirect(base_url() . $somename);
}
}
function user_Method($somename = NULL) {
echo "Working ";
echo $this->uri->segment(1);
}
public function error() {
echo "ERROR PAGE";
}
}
Url
http://localhost/codeigniter-project/username
With index.php
http://localhost/codeigniter-project/index.php/username
Config Base URL
$config['base_url'] = 'http://www.domain.com/';
I have a base class which is inherited by all the controllers. I am having a function in the base class which determines the logged in users role using Auth. Once the users role is determine a variable $LoggedIn_role is set.
This method is correctly called on the initial page load, but later i am issuing ajax calls to check whether the user is still logged in, at that time the Auth::logged_in() always returning 0.
The kohana version i am using is 3.3
Can any one please suggest what is the best approach to circumvent this issue. Thanks.
To login -
if ($ValidObj->check()) {
if (Auth::instance()->login($_POST['email'], $_POST['password'],FALSE)) {
$this->DoPostLoginJobs();
} else {
$this->ManageError(Controller_Application::MsgWrongUserCredentials);
}
} else {
$this->Form_Errors = $ValidObj->errors('');
}
To Logout -
public function action_logout() {
$loggedout = Auth::instance()->logout();
if ($loggedout)
HTTP::redirect ('/home/'); // redirects to the home page.
}
Inside the controller_Application . The base class of all the controllers
public function DetermineUserRole() {
$this->LoggedIn_Role = Controller_Application::None;
try {
if (Auth::instance()->logged_in('freelancer')) {
$this->LoggedIn_Role = Controller_Application::Freelancer;
$this->LoggedIn_Id = Auth::instance()->get_user()->pk();
} else if (Auth::instance()->logged_in('employer')) {
$this->LoggedIn_Role = Controller_Application::Employer;
$this->LoggedIn_Id = Auth::instance()->get_user()->pk();
}
} catch (Gettrix_Exception $exc) {
$this->ManageError(Controller_Application::RedirectNonRecoverableError);
}
public function before() {
if ($this->request->is_ajax()) {
$this->auto_render = false;
}
$this->DetermineUserRole();
if($this->auto_render==TRUE){
parent::before();
$this->template->content = '';
$this->template->styles = array();
$this->template->scripts = array();
View::set_global('site_name', 'TheWebTeam');
View::bind_global('Form_Errors', $this->Form_Errors);
View::bind_global('LoggedIn_Role', $this->LoggedIn_Role);
View::bind_global('LoggedIn_Id', $this->LoggedIn_Id);
View::bind_global('InvitedEmail', $this->InvitedEmail);
View::bind_global('InvitedUniqueID', $this->InvitedUniqueID);
View::bind_global('scripts', $this->template->scripts);
View::bind_global('styles', $this->template->styles);
}
//This is inside the Home page controller, where it lists all the jobs for the logged in user.
public function action_joblist()
{
echo Auth::instance()->logged_in() . //The state holds to the initial state, doesn't //change when the user is logged out or logged in.
}
Please note that action_joblist() is called via AJAX/Jquery call.
The issue is fixed by following the instructions given in the link : http://forum.kohanaframework.org/discussion/9619/session-timeout-corruption-problems/p1
i am using opencart in one project,
every thing is working fine but i am unable to find an option to stop view of home page until LOGIN.
actually this is project requirement, no one can see home until LOGIN.
is there way to do this with OPEN CART ?
Thanks
this is untested, but should point you in the right direction:
(OpenCart 1.4.9.x)
Save this to:
catalog/controller/common/check_login.php
<?php
class ControllerCommonCheckLogin extends Controller {
public function index() {
if (!$this->customer->isLogged()) {
// Require to be logged in
$ignore = array(
'account', 'payment'
);
$match = false;
if (isset($this->request->get['route'])) {
foreach ($ignore as $i) {
if (strpos($this->request->get['route'], $i) !== false) {
$match = true;
break;
}
}
}
// Show site if logged in as admin
$this->load->library('user');
$this->registry->set('user', new User($this->registry));
if (!$this->user->isLogged() && !$match) {
return $this->forward('account/login');
}
}
}
}
?>
Edit /index.php
Find:
// Maintenance Mode
$controller->addPreAction(new Action('common/maintenance/check'));
Add After:
// Login Check
$controller->addPreAction(new Action('common/check_login'));
Essentially use the same logic as the maintenence check... The big difference is it looks for the word 'account' in the string... If it finds it it allows the page to be displayed, if not it redirects to the login page...
Use the word "account" instead of "login" in case they need to register... All of the account pages already check for loggin so there is no worry there...
Again, untested so you may need to tweak one or two things - but it should/may work by dropping in the code
check_login.php for opencart 1.5.3
<?php
class ControllerCommonCheckLogin extends Controller {
public function index() {
// Require to be logged in
if (!$this->customer->isLogged()) {
// Require to be logged in
$ignore = array(
'account','payment'
);
$match = false;
if (isset($this->request->get['route'])) {
foreach ($ignore as $i) {
if (strpos($this->request->get['route'], $i) !== false) {
$match = true;
break;
}
}
}
// Show site if logged in as admin
$this->load->library('user');
$this->user = new User($this->registry);
if (!$this->user->isLogged() && !$match) {
$this->redirect($this->url->link('account/login'));
}
}
}
}
?>
There is nothing built-in that I know of, but you can do it yourself. Based on your answers to #CarpeNoctumDC's questions you may have to do some digging, but this should get you started:
system/library/customer.php
public function isLogged() { ... }
catalog/controller/common/home.php
if (!$this->customer->isLogged()) {
// login page
exit;
}
The right way to go about this is to open
/catalog/controller/common/home.php
find public function index() { at the top of the code, and after it put
if(!$this->customer->isLogged()) {
$this->session->data['redirect'] = $this->url->link('common/home');
$this->url->redirect('account/login', '', 'SSL');
}
In case you're unsure how to do this properly, just take a look at the first few lines after public function index() { in
/catalog/controller/account/account.php
setting your code in the home controller to common/home in place of account/account
I'm trying to set up a redirect on my SilverStripe site.
I have created my own module, and now I want the user to be redirected to that after log in.
I've tried with Director::redirect($Url_base . 'myModule'), but it doesn't work.
Does anyone have any suggestions?
Try this: http://www.ssbits.com/customize-the-redirect-after-a-successful-member-login/
I did something like this:
class MyLoginForm extends MemberLoginForm {
public function dologin($data) {
parent::dologin($data);
if (Director::redirected_to() && $Member = Member::currentUser()) {
$this->controller->response->removeHeader('Location');
if ($Member->Email == 'admin') {
$destination = '/admin';
} else {
$destination = '/user/' . $Member->Username;
}
Director::redirect($destination);
}
}
}
If it is the admin user I redirect them to /admin. If it is another user I redirect them to /user/username.