#php #html #forms #codeigniter
#php #HTML #формы #codeigniter
Вопрос:
Я создаю форму входа и регистрацию на одной странице, но у меня возникли проблемы с регистрационной формой, которая, когда моя регистрация перенаправляется не на нужную мне страницу, а у меня появляется уведомление «404 Страница, которую вы ищете, не найдена!», но данные, уже введенные в регистрационную форму, успешно сохранены в базе данных. данные, которые включены в регистрационную форму, которые могут быть использованы для входа в систему!
Контроллер входа
<?php class Login extends Front {
var $customer;
public function __construct()
{
parent::__construct();
$this->customer = CI::Login()->customer();
}
public function login($redirect= '')
{
//find out if they're already logged in
if (CI::Login()->isLoggedIn(false, false))
{
redirect($redirect);
}
CI::load()->library('form_validation');
CI::form_validation()->set_rules('email', 'lang:address_email', ['trim','required','valid_email']);
CI::form_validation()->set_rules('password', 'Password', ['required', ['check_login_callable', function($str){
$email = CI::input()->post('email');
$password = CI::input()->post('password');
$remember = CI::input()->post('remember');
$login = CI::Login()->loginCustomer($email, sha1($password), $remember);
if(!$login)
{
CI::form_validation()->set_message('check_login_callable', lang('login_failed'));
return false;
}
}]]);
if (CI::form_validation()->run() == FALSE)
{
$this->view('login', ['redirect'=>$redirect, 'loginErrors'=>CI::form_validation()->get_error_array()]);
}
else
{
redirect($redirect);
}
}
public function logout()
{
CI::Login()->logoutCustomer();
redirect('login');
}
public function forgotPassword()
{
$data['page_title'] = lang('forgot_password');
CI::form_validation()->set_rules('email', 'lang:address_email', ['trim', 'required', 'valid_email',
['email_callable', function($str)
{
$reset = CI::Customers()->reset_password($str);
if(!$reset)
{
CI::form_validation()->set_message('email_callable', lang('error_no_account_record'));
return FALSE;
}
else
{
//user does exist. and the password is reset.
return TRUE;
}
}
]
]);
if (CI::form_validation()->run() == FALSE)
{
$this->view('forgot_password', $data);
}
else
{
CI::session()->set_flashdata('message', lang('message_new_password'));
redirect('login');
}
}
public function register()
{
$redirect = CI::Login()->isLoggedIn(false, false);
//if they are logged in, we send them back to the my_account by default
if ($redirect)
{
redirect('my-account');
}
CI::load()->library('form_validation');
//default values are empty if the customer is new
$data = [
'company' => '',
'firstname' => '',
'lastname' => '',
'email' => '',
'phone' => '',
'address1' => '',
'address2' => '',
'city' => '',
'state' => '',
'zip' => '',
'redirect' => CI::session()->flashdata('redirect')
];
CI::form_validation()->set_rules('company', 'lang:account_company', 'trim|max_length[128]');
CI::form_validation()->set_rules('firstname', 'lang:account_firstname', 'trim|required|max_length[32]');
CI::form_validation()->set_rules('lastname', 'lang:account_lastname', 'trim|required|max_length[32]');
CI::form_validation()->set_rules('email', 'lang:account_email', ['trim','required','valid_email','max_length[128]', ['check_email_callable', function($str){
return $this->check_email($str);
}]]);
CI::form_validation()->set_rules('phone', 'lang:account_phone', 'trim|required|max_length[32]');
CI::form_validation()->set_rules('email_subscribe', 'lang:email_subscribe', 'trim|numeric|max_length[1]');
CI::form_validation()->set_rules('password', 'lang:account_password', 'required|min_length[6]');
CI::form_validation()->set_rules('confirm', 'lang:account_confirm', 'required|matches[password]');
if (CI::form_validation()->run() == FALSE)
{
//if they have submitted the form already and it has returned with errors, reset the redirect
if (CI::input()->post('submitted'))
{
$data['redirect'] = CI::input()->post('redirect');
}
// load other page content
//CI::load()->model('banner_model');
CI::load()->helper('directory');
$data['registrationErrors'] = CI::form_validation()->get_error_array();
$this->view('login', $data);
}
else
{
$save['id'] = false;
$save['firstname'] = CI::input()->post('firstname');
$save['lastname'] = CI::input()->post('lastname');
$save['email'] = CI::input()->post('email');
$save['phone'] = CI::input()->post('phone');
$save['company'] = CI::input()->post('company');
$save['active'] = (bool)config_item('new_customer_status');
$save['email_subscribe'] = intval((bool)CI::input()->post('email_subscribe'));
$save['password'] = sha1(CI::input()->post('password'));
$redirect = CI::input()->post('redirect');
//if we don't have a value for redirect
if ($redirect == '')
{
$redirect = 'my-account';
}
// save the customer info and get their new id
CI::Customers()->save($save);
//send the registration email
GoCartEmails::registration($save);
//load twig for this language string
$loader = new Twig_Loader_String();
$twig = new Twig_Environment($loader);
//if they're automatically activated log them in and send them where they need to go
if($save['active'])
{
CI::session()->set_flashdata('message', $twig->render( lang('registration_thanks'), $save) );
//lets automatically log them in
CI::Login()->loginCustomer($save['email'], $save['password']);
//to redirect them, if there is no redirect, the it should redirect to the homepage.
redirect($redirect);
}
else
{
//redirect to the login page if they need to wait for activation
CI::session()->set_flashdata('message', $twig->render( lang('registration_awaiting_activation'), $save) );
redirect('login');
}
}
}
public function check_email($str)
{
$email = CI::Customers()->check_email($str);
if ($email)
{
CI::form_validation()->set_message('check_email_callable', lang('error_email'));
return FALSE;
}
else
{
return TRUE;
}
}}
Модели входа
<?php Class Login extends CI_Model{
public function __construct()
{
$customer = CI::session()->userdata('customer');
if(empty($customer))
{
//If we don't have a customer, check for a cookie.
if(isset($_COOKIE['GoCartCustomer']))
{
//the cookie is there, lets log the customer back in.
$info = $this->aes256Decrypt(base64_decode($_COOKIE['GoCartCustomer']));
$cred = json_decode($info);
if(is_object($cred))
{
$this->loginCustomer($cred->email, $cred->password, true);
if( ! $this->isLoggedIn() )
{
// cookie data isn't letting us login.
$this->logoutCustomer();
$this->createGuest();
}
}
}
else
{
//cookie is empty
$this->logoutCustomer();
$this->createGuest();
}
}
}
public function customer()
{
return CI::session()->userdata('customer');
}
public function logoutCustomer()
{
CI::session()->unset_userdata('customer');
//force expire the cookie
$this->generateCookie('[]', time()-3600);
}
private function generateCookie($data, $expire)
{
setcookie('GoCartCustomer', $data, $expire, '/', $_SERVER['HTTP_HOST'], config_item('ssl_support'), true);
}
public function loginCustomer($email, $password, $remember=false)
{
$customer = CI::db()->where('is_guest', 0)->
where('email', $email)->
where('active', 1)->
where('password', $password)->
limit(1)->
get('customers')->row();
if ($customer amp;amp; !(bool)$customer->is_guest)
{
// Set up any group discount
if($customer->group_id != 0)
{
$group = CI::Customers()->get_group($customer->group_id);
if($group) // group might not exist
{
$customer->group = $group;
}
}
if($remember)
{
$loginCred = json_encode(array('email'=>$customer->email, 'password'=>$customer->password));
$loginCred = base64_encode($this->aes256Encrypt($loginCred));
//remember the user for 6 months
$this->generateCookie($loginCred, strtotime(' 6 months'));
}
//combine cart items
if($this->customer())
{
$oldCustomer = $this->customer();
CI::session()->set_userdata('customer', $customer);
GC::combineCart($oldCustomer); // send the logged-in customer data
}
return true;
}
else
{
return false;
}
}
public function isLoggedIn($redirect = false, $default_redirect = 'login')
{
//$redirect allows us to choose where a customer will get redirected to after they login
//$default_redirect points is to the login page, if you do not want this, you can set it to false and then redirect wherever you wish.
$customer = CI::session()->userdata('customer');
if(!$customer)
{
return false;
}
if($customer->is_guest == 1)
{
if($redirect)
{
redirect($default_redirect);
}
else
{
return false;
}
}
else
{
return true;
}
}
private function createGuest()
{
//create a temp customer
$customerID = CI::Customers()->createGuest();
$customer = CI::db()->where('id', $customerID)->get('customers')->row();
CI::session()->set_userdata('customer', $customer);
}
private function aes256Encrypt($data)
{
$key = config_item('encryption_key');
if(32 !== strlen($key))
{
$key = hash('SHA256', $key, true);
}
$padding = 16 - (strlen($data) % 16);
$data .= str_repeat(chr($padding), $padding);
return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, str_repeat("", 16));
}
private function aes256Decrypt($data)
{
$key = config_item('encryption_key');
if(32 !== strlen($key))
{
$key = hash('SHA256', $key, true);
}
$data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, str_repeat("", 16));
$padding = ord($data[strlen($data) - 1]);
return substr($data, 0, -$padding);
}}
Функция перенаправления
if ( ! function_exists('redirect')){
function redirect($uri = '', $method = 'auto', $code = NULL)
{
if ( ! preg_match('#^(w :)?//#i', $uri))
{
$uri = site_url($uri);
}
// IIS environment likely? Use 'refresh' for better compatibility
if ($method === 'auto' amp;amp; isset($_SERVER['SERVER_SOFTWARE']) amp;amp; strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== FALSE)
{
$method = 'refresh';
}
elseif ($method !== 'refresh' amp;amp; (empty($code) OR ! is_numeric($code)))
{
if (isset($_SERVER['SERVER_PROTOCOL'], $_SERVER['REQUEST_METHOD']) amp;amp; $_SERVER['SERVER_PROTOCOL'] === 'HTTP/1.1')
{
$code = ($_SERVER['REQUEST_METHOD'] !== 'GET')
? 303 // reference: http://en.wikipedia.org/wiki/Post/Redirect/Get
: 307;
}
else
{
$code = 302;
}
}
switch ($method)
{
case 'refresh':
header('Refresh:0;url='.$uri);
break;
default:
header('Location: '.$uri, TRUE, $code);
break;
}
exit;
}}
bootstrap.php
$match = $router->match();
// call a closure
if( $match amp;amp; is_callable( $match['target'] ) ) {
call_user_func_array( $match['target'], $match['params'] );
}
// parse a string and call it
elseif($match amp;amp; is_string($match['target']))
{
$target = explode('#', $match['target']);
try {
$class = new $target[0];
call_user_func_array([$class, $target[1]], $match['params']);
} catch(Exception $e) {
var_dump($e);
throw_404();
}
}
// throw a 404 error
else
{
throw_404();
}
MyAccount.php
<?php class MyAccount extends Front {
var $customer;
public function __construct()
{
parent::__construct();
CI::load()->model(array('Locations'));
$this->customer = CI::Login()->customer();
}
public function index($offset=0)
{
//make sure they're logged in
CI::Login()->isLoggedIn('my-account');
$data['customer'] = (array)CI::Customers()->get_customer($this->customer->id);
$data['addresses'] = CI::Customers()->get_address_list($this->customer->id);
$data['customer_addresses'] = CI::Customers()->get_address_list($this->customer->id);
// load other page content
//CI::load()->model('banner_model');
CI::load()->helper('directory');
CI::load()->helper('date');
// paginate the orders
CI::load()->library('pagination');
$config['base_url'] = site_url('my_account');
$config['total_rows'] = CI::Orders()->countCustomerOrders($this->customer->id);
$config['per_page'] = '15';
$config['first_link'] = 'First';
$config['first_tag_open'] = '<li>';
$config['first_tag_close'] = '</li>';
$config['last_link'] = 'Last';
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';
$config['full_tag_open'] = '<div class="pagination"><ul>';
$config['full_tag_close'] = '</ul></div>';
$config['cur_tag_open'] = '<li class="active"><a href="#">';
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['prev_link'] = 'amp;laquo;';
$config['prev_tag_open'] = '<li>';
$config['prev_tag_close'] = '</li>';
$config['next_link'] = 'amp;raquo;';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';
CI::pagination()->initialize($config);
$data['orders_pagination'] = CI::pagination()->create_links();
$data['orders'] = CI::Orders()->getCustomerOrders($this->customer->id, $offset);
//print_r($offset);
CI::load()->library('form_validation');
CI::form_validation()->set_rules('company', 'lang:address_company', 'trim|max_length[128]');
CI::form_validation()->set_rules('firstname', 'lang:address_firstname', 'trim|required|max_length[32]');
CI::form_validation()->set_rules('lastname', 'lang:address_lastname', 'trim|required|max_length[32]');
CI::form_validation()->set_rules('email', 'lang:address_email', ['trim','required','valid_email','max_length[128]', ['check_email_callable', function($str){
return $this->check_email($str);
}]]);
CI::form_validation()->set_rules('phone', 'lang:address_phone', 'trim|required|max_length[32]');
CI::form_validation()->set_rules('email_subscribe', 'lang:account_newsletter_subscribe', 'trim|numeric|max_length[1]');
if(CI::input()->post('password') != '' || CI::input()->post('confirm') != '')
{
CI::form_validation()->set_rules('password', 'Password', 'required|min_length[6]|sha1');
CI::form_validation()->set_rules('confirm', 'Confirm Password', 'required|matches[password]');
}
else
{
CI::form_validation()->set_rules('password', 'Password');
CI::form_validation()->set_rules('confirm', 'Confirm Password');
}
if (CI::form_validation()->run() == FALSE)
{
$this->view('my_account', $data);
}
else
{
$customer = [];
$customer['id'] = $this->customer->id;
$customer['company'] = CI::input()->post('company');
$customer['firstname'] = CI::input()->post('firstname');
$customer['lastname'] = CI::input()->post('lastname');
$customer['email'] = CI::input()->post('email');
$customer['phone'] = CI::input()->post('phone');
$customer['email_subscribe'] = intval((bool)CI::input()->post('email_subscribe'));
if(CI::input()->post('password') != '')
{
$customer['password'] = CI::input()->post('password');
}
GC::save_customer($this->customer);
CI::Customers()->save($customer);
CI::session()->set_flashdata('message', lang('message_account_updated'));
redirect('my-account');
}
}
public function check_email($str)
{
if(!empty($this->customer->id))
{
$email = CI::Customers()->check_email($str, $this->customer->id);
}
else
{
$email = CI::Customers()->check_email($str);
}
if ($email)
{
CI::form_validation()->set_message('check_email_callable', lang('error_email'));
return FALSE;
}
else
{
return TRUE;
}
}
public function download($link)
{
$filedata = CI::DigitalProducts()->get_file_info_by_link($link);
// missing file (bad link)
if(!$filedata)
{
show_404();
}
// validate download counter
if($filedata->max_downloads > 0)
{
if(intval($filedata->downloads) >= intval($filedata->max_downloads))
{
show_404();
}
}
// increment downloads counter
CI::DigitalProducts()->touch_download($link);
// Deliver file
CI::load()->helper('download');
force_download('uploads/digital_uploads/', $filedata->filename);
}}
Комментарии:
1. Во-первых, chk debug
$redirect
что вы получаете при этом, во-вторых, с помощью site_url() вы загрузили библиотеку uri?2. Что это за версия codeigniter?
3. в bootstrap.php не пытаться, а поймать var_dam ($ e), все нормально, кроме регистрации! но данные о содержимом формы должны попасть в базу данных!
4. Я не знаю, сколько версий этого CodeIgniter, но этот CodeIgniter 2015