Zend Framework :: Is this code good for user login (Its begining- because that I want to know if its can be improve) - model-view-controller

I new in Zend.
Main Question:
Is this code good for user login (Its beginning- because that I want to know if its can be improve)?
Thanks
view index.phtml
<? echo $this->form
controller IndexAction.php
public function indexAction() {
$form=new Application_Form_Login();
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
echo " test value username: ".$form->getValue('username');
}
}
}
form Login.php
public function init() {
$this->setMethod('post');
$this->setName('user login');
$username = new Zend_Form_Element_Text('username');
$username->setLabel("username")
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$password = new Zend_Form_Element_Password('password');
$password->setLabel('password')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$submit = new Zend_Form_Element_Submit('submit');
$this->addElements(array($username, $password, $submit));
}

So far, so good. IMO there's nothing to improve on this further. It renders the form and if the request is POST it validates the form against the data in the POST array.

what is really special in your code? standart pattern.

Related

How to fetch session data in codeigniter?

I am trying to create a login process using codeigniter framework. Form validation is working but there is a problem in session. I can't fetch username after "Welcome-".
controller : Main.php
<?php
class Main extends CI_Controller
{
public function login()
{
$this->load->view('login');
}
public function login_validation()
{
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if ($this->form_validation->run())
{
$username = $this->input->post('username');
$password= $this->input->post('password');
//model
$this->load->model('myModel');
if ($this->myModel->can_login($username,$password))
{
$session_data = array('username' => $username);
$this->session->set_userdata('$session_data');
redirect(base_url().'main/enter');
}
else
{
$this->session->set_flashdata('error','Invalid Username Or Password');
redirect(base_url().'main/login');
}
}
else
{
$this->login();
}
}
function enter()
{
if ($this->session->userdata('username')!=' ')
{
echo '<h2> Welcome- '.$this->session->userdata('username').'</h2>';
echo 'Logout';
}
else
{
redirect(base_url().'main/login');
}
}
function logout()
{
$this->session->unset_userdata('username');
redirect(base_url().'main/login');
}
}
?>
Add session library in the constructor
<?php
class Main extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Load form helper library
$this->load->helper('form');
// Load form validation library
$this->load->library('form_validation');
// Load session library
$this->load->library('session');
$username = $this->session->userdata('username');
if (empty($username)) {
redirect('main/logout');
}
}
}
Another method you can load the session library in autoload.php file
File location: application/config/autoload.php
$autoload['libraries'] = array('database', 'email', 'session');
I suggest a slight code rearrangement for enter() that provides a better test for the user name using a tiny bit less code.
function enter()
{
if(empty($this->session->userdata('username')))
{
//base_url() accepts URI segments as a string.
redirect(base_url('main/login'));
}
// The following code will never execute if `redirect()` is called
// because `redirect()` does not return, it calls `exit` instead.
// So, you do not need an `else` block
echo '<h2> Welcome- '.$this->session->userdata('username').'</h2>';
echo 'Logout';
}
empty() will be true for an empty string, NULL, False and a couple of other things. In this case, you are most interested in an empty string or NULL. (empty() documentation HERE.)
You might want to consider adding 'trim' to your validation rules because it strips empty whitespace from the input string. That will remove the possibility of someone trying to input a username using only space characters.
Otherwise, your code should work. If it does not then it's very likely you do not have CodeIgniter sessions configured properly. There are many session setup questions answered here on Stack Overflow that will help you get it running.

Make an Ajax request in Symfony2

My problem is that the method doesn't return a true result.
I want to test if the email of input exists in my entity or not.
Here is the controller:
public function verificationAction(Request $request)
{
if ($this->container->get('request')->isXmlHttpRequest()) {
$email=$request->request->get('email');
$em=$this->getDoctrine()->getEntityManager();
$resp= $em->getRepository("CMSiteBundle:Prospect")->findBy(array('email'=>$email));
$response =new Response(json_encode($resp));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
You could try an old-trick. Since in Symfony Controller Actions, You must return a Response why not fake a DEAD RESPONSE like so:
<?php
class ABCController {
public function verificationAction(Request $request) {
if ($this->container->get('request')->isXmlHttpRequest()) {
$email = $request->request->get('email');
$em = $this->getDoctrine()->getEntityManager();
$resp = $em->getRepository("CMSiteBundle:Prospect")
->findBy(array('email' => $email));
//$response = new Response(json_encode($resp));
//$response->headers->set('Content-Type', 'application/json');
// THE TRICK IS THAT DIE RUNS FIRST
// THUS SENDS YOUR RESPONSE YOU THEREBY
// STOPPING THE RETURN FROM FIRING... ;-)
return die(json_encode($resp));
}
}
}
Perhaps this very Old Trick still works for you... ;-)

Access information from session in website with two different sessions

My website has two restrict areas, in the public website and admin area. I've tried to follow some instructions to make multiple sessions throughout the website, but I'm facing some problems about accessing and retrieving their information.
Below are the login methods from both pages. First from the administration area:
public function login()
{
if ($this->Admin_model->find_credentials()) {
$data['user_email'] = $this->input->post('email');
$this->session->set_userdata('auto', $data);
redirect('/admin/dashboard', 'refresh');
} else {
$this->session->set_flashdata('message', 'Desculpe, credenciais inválidas');
redirect('/admin/entrar');
}
}
And then, the admin area in the public website:
public function login()
{
if ($this->Usuarios_model->find_credentials()) {
$email = $this->input->post('email');
if ($this->Usuarios_model->is_active($email)) {
$data = array();
$data['nome'] = $this->Usuarios_model->find_col_by_email('nome_razao_social', $email);
$data['email'] = $email;
$data['tipo_usuario'] = $this->Usuarios_model->find_col_by_email('tipo_usuario', $email);
$data['id_usuario'] = $this->Usuarios_model->find_col_by_email('id', $email);
$this->session->set_userdata('auto', $data);
$this->session->set_flashdata('message', 'Bem-vindo!');
redirect('/usuario/painel');
} else {
$this->session->set_flashdata('message', 'Por favor, ative o seu cadastro');
redirect('/');
}
} else {
$this->session->set_flashdata('message', 'Desculpe, credenciais inválidas');
redirect('/');
}
}
For each new session, I am settling a name for it. Now, every point I call the session value, I must specify the name of which session I want, but I am having an error message after I try to log-in:
Message: Array to string conversion
This error points at line 161 of my model, which has the following code:
public function find_details($email = null, $id = null, $id_carro = null)
{
$this->db
->select(
'usuario.*,' .
'estado.nome_estado AS uf,' .
'cidade.nome_cidade AS cidade'
)
->join('cidade', 'cidade.id = usuario.id_cidade')
->join('estado', 'estado.id = usuario.id_estado');
if ($email) {$this->db->where('usuario.email', $email);} // 161
...
}
What do I need to do to make multiple sessions work correctly?
Alright. The solution for me was a different way to echo the value of a certain session:
$this->session->userdata('foo')['bar'].
Where foo is the session name, specified when creating a new session. In my case, a good example can be $this->session->userdata('auto')['email'];

codeigniter validate

Hello I have a forum and when a user creates a comment, I want that if he didn't type anything I want to show him an error that he must type something in :) but I dont know how to put him the the thread he is in.
I have this
if($this->_submit_validate_comment() == false) {
$this->post(); return;
}
function _submit_validate_comment() {
$this->form_validation->set_rules('kommentar', 'kommentar', 'required|min_length[4]');
return $this->form_validation->run();
}
You could do this with jquery but if that is not an option you could get the forum or topic id from the url (assuming your are using the url this way).
For example:
http://yoursite.com/forum/topic/12
if($this->_submit_validate_comment() == false)
{
$topic_id = $this->uri->segment(3);
redirect('/forum/topic/'. $topic_id);
}
Or
if($this->_submit_validate_comment() == false)
{
$topic_id = $this->uri->segment(3);
$this->topic($topic_id);
}
Hope this helps.
Thanks for helping i can see what you mean but it just dont work :b,
i have this
$topic_id = $this->uri->segment(3);
$this->post($topic_id);
return;
and my url is
localhost:8888/ci/index.php/forum/create_comment
it looks like it cant find the ID
my URL to the forum is
localhost:8888/ci/index.php/forum/post/33
this is my functions
function create_comment() {
if($this->_submit_validate_comment()
== false) { $id = $this->uri->segment(3);
$this->post($id); return;
//echo "validate fejl, kontakt lige
en admin!"; } else { $data =
array( 'fk_forum_traad' =>
$this->input->post('id'),
'brugernavn' =>
$this->session->userdata('username'),
'indhold' =>
$this->input->post('kommentar'),
'dato' => 'fejl' );
$this->load->model('forum_model');
$this->forum_model->create_comment($data);
redirect('/forum/post/'.
$this->input->post('id').'',
'refresh'); }
}
function post($id) {
$this->load->model('forum_model');
$data['query'] =
$this->forum_model->posts($this->uri->segment(3));
$this->load->model('forum_model');
$data['comments'] =
$this->forum_model->comments($this->uri->segment(3));
$data['content'] = 'forum_post_view';
$this->load->view('includes/template',
$data); }
Why not pass in the return uri in the form submission using a hidden input field? No additional work will be needed by the controller other than validation of the return uri before performing a redirect.
Place the validation error string in session class's flashdata for echoing out in the form, along with any other data used to pre-populate your form)

KO3 - Kohana 3 - How can I pass $_POST data from a controller/action back to the view/form that called it?

I am trying to validate a form submission in Kohana 3. I have the form::open point to my action_create in my controller which successfully validates the data posted to it from the form in my view. If the data passes validation, a new item is created as intended, and the user is redirected to the item that was just created. This works correctly. If the data fails validation, however, I would like the user to be directed back to the originating view/page while retaining a variable containing the data that was posted so that I can repopulate the form and display errors.
In short, how can I pass data from a view -> controller -> original view?
Thank you, everyone!
The user also posed this question on the Kohana forums.
Those seeking an answer to this should have look over there.
I assume you're using Controller_Template.
File views/form.php:
// Set default variables if variables not passed to this view
$username = isset($username) ? $username : '';
echo Form::open('login');
// Input: username
echo Form::label('username', 'Username');
echo Form::input('username', $username);
echo isset($errors['username']) ? $errors['username'] : '';
// Input: username
echo Form::label('password', 'Password');
echo Form::input('password', $password);
echo isset($errors['password']) ? $errors['password'] : '';
echo Form::close();
File views/template.php
<html>
<head><title>My Website</title></head>
<body>
<?php echo isset($content) ? $content : ''; ?>
</body>
</html>
File classes/controller/user.php
Class Controller_User extends Controller_Template {
public $template = 'template';
public function index()
{
$this->template->content = $this->display_form('form');
}
public function login()
{
// Setup validation & rules here
// Check validation, assume $validation is Validation object
if ($validation->check()
{
// Validation succeeded. Do anything you want here
}
else
{
// Validation failed. Display form with entered values
$form_vars = $_POST;
$form_vars['errors'] = $validation->errors();
// Display form
$this->template->content = $this->display_form('form', $form_vars);
}
}
// Displaying form
private function display_form($form_file, $form_vars=NULL)
{
$form = View::factory($form_file);
if ($form_vars != NULL)
{
foreach($form_vars as $key => $value)
{
$form->$key = $value;
}
}
return $form;
}
}
Hope that helps!

Resources