Codeigniter custom url string - php

I am new to codeigniter and i am working on making a doctors site and need to allow users to search for doctors using simple url like http://www.mywebsite.com/newyork .so this url doesn't have any class as there can be many states and cant have class for each state. Should i change 404 override in routes script? Or there is a better way to achieve it
$route['(:any)']='search/check_state';
if i use above routing then other page like /login doesnt work.Please help

Make database that contains all states and do it this way
Inside search/check_state
// Get state from URL
$state = $this->uri->segment(1, "");
// Make sure state is not null and its found in database
if($state <> "" && $this->validateState($state)){
// Valid state, continue
}else{
// Give error message / redirect to 404 page
}
Add new function to controller
function validateState($state){
// If database contains $state then return true else return false
}
UPDATE
You can also do it with POST form.
Make form into page where user gives input details
echo form_open(base_url().'path_to_post_validation');
// make form here that sends "state" into page that handles validation
echo form_close();
Handle POST validation
// Make sure user has send POST request
if($this->input->post()){
// Set form validation rules
$this->form_validation->set_rules('state', 'state', 'required|trim|xss_clean');
// Run form validation
if ($this->form_validation->run() == TRUE){
// Store state into variable
$state = $this->input->post('state');
// Check database that it contains $state and then continue or give error message
}
}

got it try
$route['search/check_state/:any'] ='search/check_state';

Related

best practice to post data on codeigniter controller with same url?

hello i have two route in codeigniter:
$route['register'] = 'Login/Register';
$route['login'] = 'Login/index';
for displaying login/register form
and form post routes:
$route['loginprocess'] = 'Login/LoginProcess';
$route['registerprocess'] = 'Login/RegisterProcess';
it's ok, but while using form_validation class in
$this->form_validation->set_error_delimiters('<span class="help-block">', '</span>');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('pwd', 'Password', 'required');
if ($this->form_validation->run() == FALSE){
$this->load->view('login');
} else {
validation success
}
problem is when i get error in form validation it goes in
http://localhost/logincode/loginprocess
is so it's not url friendly. it should post in same controller method where form already display :
http://localhost/logincode/login
so is there any way to post form in same url. with form validation error comes together
Posting to Same URL in CodeIgniter
You've described a common scenario. You want to load a page with a form, perform a POST request, validate the request, then show errors if there is a problem. There are some potential issues to be aware of if you're doing this:
After a successful post, what happens if the browser performs a page refresh?
After a successful post, what happens if the user navigates away to another page, but then travels backwards in history?
Both of these issues present a duplicate post issue, and that's never desirable. The way to solve this is to use a form token. A form token is generated during the loading of the page where the form is present. The value is commonly a random string of characters, and it is put in two places:
In the form as a hidden form field.
In a session or cookie.
When the form is posted, the token value in the hidden form field is passed along with the rest of the posted data. Since there is a session or cookie containing the same value, the controller/method being posted to can check if they match, and if they do then validation can be performed, and errors or success message output. In any case, a new form token is generated, so two posts will never contain the same form token.
Summary of The Basic Concept
// You of course have to start the
// session for this to work.
$this->load->library('session');
if(
isset( $_POST['token'] ) &&
isset( $_SESSION['token'] ) &&
$_POST['token'] == $_SESSION['token']
){
// Do validation ...
// ...
// If validation passes
if( $this->form_validation->run() ){
$valid = TRUE;
}
// If there were validation errors
else{
$errors = validation_errors();
}
}
if( isset( $errors ) )
{
// Display the errors
}
if( isset( $valid ) )
{
// Display a thank you message
}
// Always refresh the token
$token = substr(md5(uniqid() . microtime() . rand()), 0, 8);
$_SESSION['token'] = $token;
?>
<form method="POST">
<input type="text" name="x" />
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="submit" value="submit" />
</form>
In practice this concept of tokens can be much more elaborate. For instance, you may choose to encrypt the token values and then decrypt them when checking if they match. You might also create an array of tokens in your session/cookie, and check your posted token against the array of tokens. You may have other ideas on how to customize form tokens, but the basics have been presented here, and I hope it helps you achieve your goal of posting to the same URL in CodeIgniter.

Unable to change value with codeIgniter validation

Here i have a list of contacts where user can add new contacts as well as edit them. Now at the add time i'm using server-side validation by codeIgniter for reduce redundancies. Also here i have a number of users that can add their contacts.
Suppose their are users named "John" and "Sara".
In this case, whenever "john" add new contact that are prevoiusly added by him, then it can't be add as duplicate contact number.
But whenever "john" add new contact that are previously added by "Sara", them it can be add . but its unable to add because CodeIgniter form_validation check unique value with entire table data.
Here is my Controller Code
$this->form_validation->set_rules('customer_email','Email', 'trim|check_email[customer.customer_email.' .$userId. ']', array('check_email' => 'Email must be unique.'));
$this->session->set_flashdata('check_email','Mobile must be unique');
$this->form_validation->set_rules('customer_mobile', 'Mobile', 'required|is_unique[customer.customer_mobile]');
$this->session->set_flashdata('contact_exists','Mobile must be unique');
if ($this->form_validation->run()) {
$userdata = $this->session->userdata();
$userId = $userdata['id'];
if (!$userId):
redirect(site_url());
endif;
I trying to many time but unable to fix this issue. I need your kind efforts. Thanks
Please find below solution.
First you need to remove unique check from customer_mobile.
$this->form_validation->set_rules('customer_mobile', 'Mobile', 'trim|required');
Once form_validation runs true then check customer_mobile with user in database and if it return row then return error else insert Contact.
if ($this->form_validation->run() == TRUE) {
// $check = Check here for customer_mobile with user in database
if($check):
return 'Contact already exist';
else:
// Insert Contact
endif;
}
Let me know if it not works.

Laravel returning to same page if popup clicked

I have three functionalities to be done only after logging in. Once they click the button, it checks for login. if not logged in, it show the popup and make them to login.
Am using that login popup for initial login. Same controller function and returning back.
Now my problem is, I had add leads popup. when they click add leads, it show login popup. After logging in, I have to show the same leads popup. But that should not affect other log in. This has to be implemented in four other functionalities.
how to find where the log in is done and return back accordingly?
Controller Code:
public function register(Request $request)
{
$this -> validate($request,[
'useremail' =>'required',
]);
$res = StandardUser::where('useremail', Input::get('useremail'))->first();
$email = $request->useremail;
if ($res) {
$userid = json_decode($res)->id;
$firstname = json_decode($res)->firstname;
$lastname = json_decode($res)->lastname;
$managerfirstname = json_decode($res)->manager_firstname;
$managerlastname = json_decode($res)->manager_lastname;
$manageremail = json_decode($res)->manager_email;
return back()
->withCookie(cookie('uemail', $email))
->cookie('uid', $userid)
->cookie('ufn', $firstname)
->cookie('uln', $lastname)
->cookie('mfn', $managerfirstname)
->cookie('mln', $managerlastname)
->cookie('memail', $manageremail);
}else{
$standarduser = StandardUser::create($request->all());
$userid = $standarduser->id;
return back()
->withCookie(cookie('uemail', $email))
->cookie('uid', $userid);
}
}
Do one thing, inside your ajax() login function pass a callback kind of parameter that contains the name of the function that is to be executes when login is successful.
By using this callback function you can decide whether it requires redirection or reload or to call a function that initiate some other popup kind of thing.
To do this with minor changes,
take a hidden field in you login for popup and print the redirect url here with a query string parameter named as 'ajax' like "/controller/action?data='ajax'".
Then in your login controller where you did the redirection, check the post data of the hidden field that if in the query string, data has the parameter 'ajax' then redirect to this hidden field url other wise redirect to other one which you want.

How to best implement dynamic url/controller name which is database driven?

I have a website that is written in PHP on codeigniter. The scenario I am looking to cope with is the following:
When a user signs up, Their personalised homepage should appear at www.mysite.com/username. Other urls are of the form www.mysite.com/username/pictures & www.mysite.com/username/videos.
So basically what I need is www.mysite.com/username/method (where username is database driven) should always hit the same controller, if the username exists in the database.
Currently, what I am doing is I am using the custom 404 controller to do this. If a URL reaches the custom 404 controller, I check if the controller name matches a username in the data base, then checking the method name and calling the required method. Like so:
$this->load->model('school_model');
$this->load->model('event_model');
$this->load->helper('apps_helper');
$controllerName = $this->uri->segment(CONTROLLER);
$controllerMatch = $this->school_model->findSchoolByUid($controllerName);
$this->data['controller'] = $controllerMatch;
if($controllerMatch != false){
$methodName = $this->uri->segment(METHOD);
if($methodName === "something"){
//Do something
}
if($methodName === "something else"){
//Do something else
}
if($methodName === "another thing"){
//Do another thing
}
if($methodName === "last thing"){
//Do last thing
}
...
}
else{
//Load 404 page
$this->output->set_status_header('404');
$data['content404'] = true;
$this->load->view("common/header", $data);
$this->load->view('frontend/index404', $this->data);
$this->load->view("common/footer");
}
My query is, is this the best way to go about what I need ? How can I improve this ? I have heard of the HMVC modular extension for codeiginiter which may be a good bet ? Just looking for some advice.
You can do this by writing this code in your config > routs.php file
$route['(:any)/pictures'] = 'yourcontrollername/functionName/$1';
now in this if any one write username/pictures url than it will automatically goes to your controller.

How to validate form post in the controller and also check if the product collection filter matched

I have created a simple product selector. In the phtml, I created a form that post data and these data are received by controller to be validated before registering to a registry.
I also have product collection that gets the data to be filter coming from the registry. I have several filters and if one fails, the system should display a message.
This is what I have done so far.
My Controller:
public function indexAction() {
if ($data = $this->getRequest()->getPost()) {
$data['ta'] = $this->getRequest()->getPost('torqueAction');
$data['tr'] = $this->getRequest()->getPost('torqueRequired');
$data['tm'] = $this->getRequest()->getPost('torqueMetric');
$data['tmax'] = $data['tr'] / 80 * 100;
if (validation is equal to true) {
Mage::register('t-action', $data['ta']);
Mage::register('t-req', $data['tr']);
Mage::register('t-metric', $data['tm']);
Mage::register('t-max', $data['tmax']);
$this->_redirect('productselector/index/result');
}else {
// Display message about the error
}
}
}
My Collection located in the phtml:
$collection = Mage::getModel('catalog/product')
->getCollection()
->addFieldTofilter($attr_name, array(
'eq' => Mage::getResourceModel('catalog/product')
->getAttribute($attr_name)
->getSource()
->getOptionId($attr_val)
))
->addAttributeToSelect('*')
->addFieldTofilter($metric, array('gteq' => $metric_val_min))
->addFieldTofilter($metric, array('lteq' => $metric_val_max))
->load();
if ($collection == NULL) { // not sure how to validate it if one filter fails
echo "sorry, no product available";
}else {
//Display some errors
}
QUESTIONS:
How to validate form post in the controller and checks if empty and no malicious code?
How to check product collection if one filter was not met?
How do I display these errors from controller and product collection?
Thanks
How to validate form post in the controller and checks if empty and no malicious code?
You can check an empty post like this.
if ($this->getRequest()->getPost('field_name', false)) {
//yes 'fiel_name' is not empty. do something with it.
}
This is because getPost() will accept two parameters. If the parameter-1 is not set, then it will return the default value that we specified as parameter-2. In this case, default value is false and hence condition fails if field_name is empty.
I didn't get the "malicious" part in the question. The answer for is, it depends from situation to situation.
How to check product collection if one filter was not met?
Honestly, question is not clear for me. However if the filters that you have applied using addFieldToFilter fails, then you will get an empty collection. You can check the count of a collection like this.
if ($collection->getSize() > 0) {
//do something with collection
} else {
//show some error
}
How do I display these errors from controller and product collection?
Errors, warning, success messages are setting on session variable and thus you can get the session in the redirecting page and show them in frontend.
These are the avaialble notifications in Magento.
$session = Mage::getSingleton('customer/session');
//use to show error
$session->addError('add some error message');
//use to show warning
$session->addWarning('add some warning message');
//use to show notice
$session->addNotice('add some notice message');
//use to show success message
$session->addSuccess('add some success message');
You can set them in controller. Now this is how you can grab all these items and show in frontend. Use them in the form template wisely.
$messages = Mage::getSingleton('customer/session')->getMessages();
foreach ($messages as $message) {
echo $message;
}
Hope that makes sense.

Categories