Codeigniter - Checking if a GET request is made - php

Im using CodeIgniter to write a site ... I understand $_GET requests are now used like so www.website.com/function/value .. and in the controller getting a url segment is written like so:
$userId = $this->uri->segment(3, 0);
Im just wondering, when a controller loads, i want to check if there is any uri segments, if there is then push to one view, else if there isnt a uri segment push to another.
Is that possible?
cheers.

You can use your controller arguments for that too.
When accessing /user/profile/1 your controller named User will call the method profile() and pass the number 1 as the first argument to your method. Like so:
class User extends CI_Controller {
{
public function index()
{
$this->load->view("user_index");
}
public function profile ( $userId = null )
{
if( (int)$userId > 0 )
$this->load->view("user_profile");
else
$this->load->view("another_view");
}
}
This is a very basic sample and I'm just trying to show the idea.

Seems like your asking two questions...
First, to check if the request is get
public function get_test()
{
if($_SERVER['REQUEST_METHOD'] == "GET")
{
//do something from get
echo "GET";
}
else
{
//do something not get
echo "NOT GET";
}
}
The next question seemed to be checking uri segments
public function get_test()
{
if($_SERVER['REQUEST_METHOD'] == "GET")
{
//do something from get
//echo "GET";
if($this->uri->segment(3)) //is true as is not empty
{
echo $this->uri->segment(3);
}
else
{
echo "I am nothing without my URI Segment";
}
}
else
{
//do something not get
echo "NOT GET";
}
}

As I understand you can use PHP default value.
function myFunction($var1 = NULL) {... if($var1 === NULL) ...}
Now if you do not pass the param you will get the NULL value.

I am still not using version 2 of codeigniter but this framework do not accept get requests; unless you mess with the configuration. Theres a function $this->input->get('myGet') you should look around at de the codeigniter.com/user_guide

Related

Getting the url where the request is redirected from in yii2?

Sorry for my English, but what I'm trying to say is explained below.
I have a controller say ControllerCard which has an action like this.
function actionScanCard()
{
...
$this->redirect('/transaction/redeem');
...
}
In other controllers, ControllerTransaction, I am trying to get that it comes/redirected from /card/scan-card
function actionRedeem()
{
$redirectFrom = ????;
if ($redirectFrom === '/card/scan-card')
{
// some actions
}
else
throw new ForbiddenHttpException('Must scan card!');
}
How do I get this $redirectFrom value with Yii2?
You could use the remember() & previous() methods in yii\helpers\BaseUrl.
function actionScanCard()
{
...
\yii\helpers\Url::remember();
$this->redirect('/transaction/redeem');
...
}
in TransactionController (or other)
function actionRedeem()
{
$url = \yii\helpers\Url::previous();
if($url === Url::to('card/scan-card')) {
// some actions
} else{}
}

Running _remap() once

When a user is logged in, I would like them to be able to visit http://website.com/user and be taken to http://website.com/1/johndoe, where 1 is their user ID, and johndoe is their user name.
I'm trying to use _remap() to catch all attempts at http://website.com/user/, so even incomplete URIs like http://website.com/user/1 or http://website.com/user/1/joh are redirected to http://website.com/user/1/johndoe.
Here's what I've tried:
class User extends CI_Controller {
function index($uID, $user) {
echo $uID;
echo $user;
}
function _remap() {
$uID = 3;
$user = 'johndoe';
//redirect('user/'.$uID.'/'.$user); // Updates URI, but redirect loop
//$this->index($uID, $user); Works, but doesn't update the URI
}
}
I could of course detect the method first, and do something like this:
function _remap($method = '') {
if ($method != 'view') {
$uID = 3;
$user = 'johndoe';
redirect('user/view/'.$uID.'/'.$user);
}
}
function view($uID, $user) {
echo $uID;
echo $user;
}
But then I think the URI would look like http://website.com/user/view/1/johndoe, and I'd rather view was excluded. How should I go about this problem?
If you have a _remap() method - it will always be called, so redirecting to user/anything will still call _remap() on the next request, so not only do you need to catch the router method and its parameters - you must do it if you want to use _remap() in a way that makes any sense:
public function _remap($method, $args)
{
if ($method === 'user' && (empty($args) OR ! ctype_digit($args[0])))
{
// determine and handle the user ID and name here
}
else
{
return call_user_func_array(array($this, $method), $args));
}
}
The solution I use is:
$route['user/(:num)/:any'] = 'user/view/$1';
$route['user/(:num)'] = 'user/view/$1';
Really, the username should only be for SEO purposes and in which case, should not be passed to the action. You will of course be able to access the username from the UserID when you look up the user anyway, so I feel it's redundant.
The above will match
/user/1/jdoe
/user/1
but will only pass 1 to your user/view action.
Edit: With your comment in mind:
$route['user/(:num)/(:any)'] = 'user/view/$1/$2';
$route['user/(:num)'] = 'user/view/$1';
function view($UserID, $UserName = null) {
// Load the model and get the user.
$this->model->load('user_model');
$User = $this->user_model->GetByUserID($UserID);
// If the user does not exist, 404!
if (empty($User)) {
show_404();
return;
}
// If the UserName does not exist, or is wrong,
// redirect to the correct page.
if($UserName === null || strtolower($User->UserName) != strtolower($UserName)) {
redirect("user/$UserID/{$User->UserName}");
return;
}
}
The above will accept the username as the parameter, however if it is not supplied or if it is not correct, it will redirect to the correct url and continue.
Hopefully this solves your problem?

Codeigniter passing parameter to controller index

I'm building a tutorialsystem with codeigniter and would like to achieve the following URL structure:
/tutorials --> an introduction page with the list of all the categories
/tutorials/{a category as string} --> this will give a list of tutorials for the given category, e.g. /tutorials/php
/tutorials/{a category as string}/{an ID}/{tutorial slug} --> this will show the tutorial, e.g. /tutorials/php/123/how-to-use-functions
/tutorials/add --> page to add a new tutorial
The problem is that when I want to use the first two types of URLs, I'd need to pass parameters to the index function of the controller. The first parameter is the optional category, the second is the optional tutorial ID. I've did some research before I posted, so I found out that I could add a route like tutorials/(:any), but the problem is that this route would pass add as a parameter too when using the last URL (/tutorials/add).
Any ideas how I can make this happen?
Your routing rules could be in this order:
$route['tutorials/add'] = "tutorials/add"; //assuming you have an add() method
$route['tutorials/(:any)'] = "tutorials/index"; //this will comply with anything which is not tutorials/add
Then in your controller's index() method you should be able to work out whether it's the category or tutorial ID is being passed!
I do think that a remap must be of more use to your problem in case you want to add more methods to your controller, not just 'add'. This should do the task:
function _remap($method)
{
if (method_exists($this, $method))
{
$this->$method();
}
else {
$this->index($method);
}
}
A few minutes after posting, I think I've found a possible solution for this. (Shame on me).
In pseudo code:
public function index($cat = FALSE, $id = FALSE)
{
if($cat !== FALSE) {
if($cat === 'add') {
$this->add();
} else {
if($id !== FALSE) {
// Fetch the tutorial
} else {
// Fetch the tutorials for category $cat
}
}
} else {
// Show the overview
}
}
Feedback for this solution is welcome!

codeigniter form callback value

Im carrying out some form validation with codeigniter using a custom validation callback.
$this->form_validation->set_rules('testPost', 'test', 'callback_myTest');
The callback runs in a model and works as expected if the return value is TRUE or FALSE. However the docs also say you can return a string of your choice.
For example if I have a date which is validated, but then in the same function the format of the date is changed how would I return and retrieve this new formatted value back in my controller?
Thanks for reading and appreiate the help.
I'm not entirely sure I got what you were asking, but here's an attempt.
You could define a function within the constructor that serves as the callback, and from within that function use your model. Something like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Controllername extends CI_Controller {
private $processedValue;
public function index()
{
$this->form_validation->set_rules('testpost','test','callback');
if ($this->form_validation->run()) {
//validation successful
echo $this->processedValue; //outputs the value returned by the model
} else {
//validation failed
}
}
private function callback($input)
{
$this->load->model('yourmodel');
$return = $this->yourmodel->doStuff($input);
//now you have the user's input in $input
// and the returned value in $return
//do some checks and return true/false
$this->processedValue = $return;
}
}
public function myTest($data){ // as the callback made by "callback_myTest"
// Do your stuff here
if(condition failed)
{
$this->form_validation->set_message('myTest', "Your string message");
return false;
}
else
{
return true;
}
}
Please try this one.
I looked at function _execute in file Form_validation of codeigniter. It sets var $_field_data to the result of callback gets(If the result is not boolean). There is another function "set_value". Use it with the parameter which is name of your field e.g. set_value('testPost') and see if you can get the result.
The way Tank_Auth does this in a controller is like so
$this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
if ($this->form_validation->run()) {
// validation ok
$this->form_validation->set_value('login')
}
Using the set_value method of form_validation is undocumented however I believe this is how they get the processed value of login after it has been trimmed and cleaned.
I don't really like the idea of having to setup a new variable to store this value directly from the custom validation function.
edit: sorry, misunderstood the question. Use a custom callback, perhaps. Or use the php $_POST collection (skipping codeigniter)...apologies haven't tested, but I hope someone can build on this...
eg:
function _is_startdate_first($str)
{
$str= do something to $str;
or
$_POST['myinput'} = do something to $str;
}
================
This is how I rename my custom callbacks:
$this->form_validation->set_message('_is_startdate_first', 'The start date must be first');
.....
Separately, here's the callback function:
function _is_startdate_first($str)
{
$startdate = new DateTime($this->input->post('startdate'), new DateTimeZone($this->tank_auth->timezone()));
$enddate = new DateTime($this->input->post('enddate'), new DateTimeZone($this->tank_auth->timezone()));
if ($startdate>$enddate) {
return false;
} else {
return true;
}
}

How do you show a 404 when there are extra URL segments in CodeIgniter?

Basically, I have a CodeIgniter site that registers users through this url:
http://website.com/user/register/1
Unfortunately, when you pass extra arguments in the URL like this:
http://website.com/user/register/1/extraargs/extraargs
Here is my code:
<?php
class User extends CI_Controller
{
public function register($step = NULL)
{
if (($step!=NULL)&&($step == 1 || $step == 2 || $step == 3)) {
if ($step == 1){
$this->load->view('registration_step1');
}
} else {
show_404();
}
}
}
?>
It doesn't show a 404. It simply ignores the extra arguments. I want it so that the extra arguments wouldn't affect the URL. I want to show a 404 if there are extra URL arguments. How do you do this? Also, can the extra URL segments affect security? Thanks.
Not sure why you'd want to do that really, but you could use func_num_args() and validate from that, i.e.,
public function register($step = NULL)
{
if ( func_num_args() > 1 ) show_404();
}

Categories