John Rand
John Rand

Reputation: 1034

CodeIgniter Disallowed Key Characters

CodeIgniter is giving me a Disallowed Key Characters error. I've narrowed it down to the name attribute of a form field: name='prod[50-4121.5]' but I'm not sure what to do about it.

Upvotes: 34

Views: 115716

Answers (22)

Divyesh
Divyesh

Reputation: 161

Go to project_folder/system/core/Input.php and find function _clean_input_keys($str) and put below code

function _clean_input_keys($str)
{
    //if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str)) //comment this code
    if (!preg_match("/^[a-z0-9:._\/%-]+$/i", $str) || preg_match("/%[^\da-fA-F]{2}/", $str))
    {
        exit('Disallowed Key Characters.');
    }

    // Clean UTF-8 if supported
    if (UTF8_ENABLED === TRUE)
    {
        $str = $this->uni->clean_string($str);
    }

    return $str;
}

Upvotes: 0

Tuxton
Tuxton

Reputation: 1

In most of the cases when you have a existing software and you are trying to deploy in a new enviroment this kind of error should be caused by the PHP property

short_open_tag

Check if you have enabled in your new enviroment. In other words PHP couldn't read the tags in your code.

Upvotes: 0

ganesh sekaran
ganesh sekaran

Reputation: 1

Replace the below Code in the _clean_input_keys function

    if ( ! preg_match("/^[a-z0-9:_\/-]+$|/i", $str))
    {
        exit('Disallowed Key Characters.\n');
    }
    if (UTF8_ENABLED === TRUE)
    {
        $str = $this->uni->clean_string($str);
    }

    return $str;

Upvotes: 0

Tyler Wall
Tyler Wall

Reputation: 3788

The problem is you are using characters not included in the standard Regex. Use this:

!preg_match("/^[a-z0-9\x{4e00}-\x{9fa5}\:\;\.\,\?\!\@\#\$%\^\*\"\~\'+=\\\ &_\/\.\[\]-\}\{]+$/iu", $str)

As per the comments (and personal experience) you should not modify they Input.php file — rather, you should create/use your own MY_Input.php as follows:

<?php

class MY_Input extends CI_Input {

    /**
     * Clean Keys
     *
     * This is a helper function. To prevent malicious users
     * from trying to exploit keys we make sure that keys are
     * only named with alpha-numeric text and a few other items.
     * 
     * Extended to allow: 
     *      - '.' (dot), 
     *      - '[' (open bracket),
     *      - ']' (close bracket)
     * 
     * @access  private
     * @param   string
     * @return  string
     */
    function _clean_input_keys($str) {
        // UPDATE: Now includes comprehensive Regex that can process escaped JSON
        if (!preg_match("/^[a-z0-9\:\;\.\,\?\!\@\#\$%\^\*\"\~\'+=\\\ &_\/\.\[\]-\}\{]+$/iu", $str)) {
            /**
             * Check for Development enviroment - Non-descriptive 
             * error so show me the string that caused the problem 
             */
            if (getenv('ENVIRONMENT') && getenv('ENVIRONMENT') == 'DEVELOPMENT') {
                var_dump($str);
            }
            exit('Disallowed Key Characters.');
        }

        // Clean UTF-8 if supported
        if (UTF8_ENABLED === TRUE) {
            $str = $this->uni->clean_string($str);
        }

        return $str;
    }

}

// /?/> /* Should never close php file - if you have a space after code, it can mess your life up */

++Chinese Character Support

// NOTE: \x{4e00}-\x{9fa5} = allow chinese characters
// NOTE: 'i' — case insensitive
// NOTE: 'u' — UTF-8 mode
if (!preg_match("/^[a-z0-9\x{4e00}-\x{9fa5}\:\;\.\,\?\!\@\#\$%\^\*\"\~\'+=\\\ &_\/\.\[\]-\}\{]+$/iu", $str) { ... }

// NOTE: When Chinese characters are provided in a URL, they are not 'really' there; the browser/OS
//   handles the copy/paste -> unicode conversion, eg:
//        一二三  -->  xn--4gqsa60b   
//   'punycode' converts these codes according to RFC 3492 and RFC 5891.
//   https://github.com/bestiejs/punycode.js ---  $ bower install punycode

Upvotes: 37

mas budi
mas budi

Reputation: 43

In my experience, it could be caused by uncompleted syntax, like :

$('#teks').val

instead of

$('#teks').val()

Upvotes: 0

Radenko Kosic
Radenko Kosic

Reputation: 13

I have the same problem and I've found it is in domain name of the email address which is somehow changed from . to _ like: name@domain_com instead [email protected]

Upvotes: 0

Waqleh
Waqleh

Reputation: 10161

I had this issue but my problem was that I by mistake added a space before the name of the input like so:

<input type="text" name=" evening_time_phone">

When it shpuld be like this:

<input type="text" name="evening_time_phone">

Upvotes: 1

heavyrick
heavyrick

Reputation: 394

i saw this error when i was trying to send a form, and in one of the fields' names, i let the word "endereço".

echo form_input(array('class' => 'form-control', 'name' => 'endereco', 'placeholder' => 'Endereço', 'value' => set_value('endereco')));

When i changed 'ç' for 'c', the error was gone.

Upvotes: 1

Ron raj
Ron raj

Reputation: 21

I had the same error after I posted a form of mine. they have a space in to my input name attributes. input name=' first_name'

Fixing that got rid of the error.

Upvotes: 2

Uttam Panara
Uttam Panara

Reputation: 549

Step1. Search for function _clean_input_keys on /system/core/Input.php

Step2. Modify this line

exit(‘Disallowed Key Characters.’);

to

exit(‘Disallowed Key Characters.’ . $str);

Step3. Refresh page to see the characters which generate the error

Step4. If you need to add those characters into the exception list, just add to this line

if ( ! preg_match(“/^[a-z0-9:_/-]+$|/i”, $str))

I add | (pipe) character on the example above

Upvotes: 3

Andrew Nguyen
Andrew Nguyen

Reputation: 37

Took a while to figure this one out. Seems most of us missed the obvious error…the last “-” is not escaped.

Adding the . and | as I’ve seen other suggest may work for you, but the regex was supposed to be:

if ( ! preg_match("/^[a-z0-9:_\/\-\.|]+$/i", $str))  

Upvotes: 1

Jamshid Hashimi
Jamshid Hashimi

Reputation: 7825

In Ubuntu, you can solve the problem by clearing the cookies of your browser. I had the same problem and solved it this way.

Upvotes: 1

Guidouil
Guidouil

Reputation: 1724

I had the same problem thanks to french specials characters. Here is my class in case anybody needs it. It has to be saved here : /application/core/MY_Input.php

(also this extension will report witch character is not allowed in the future)

class MY_Input extends CI_Input {

function __construct() { parent::__construct(); } /** * Clean Keys * * This is a helper function. To prevent malicious users * from trying to exploit keys we make sure that keys are * only named with alpha-numeric text and a few other items. * * @access private * @param string * @return string */ function _clean_input_keys($str) { if ( ! preg_match("/^[a-z0-9:_\/-àâçéèêëîôùû]+$/i", $str)) { exit('Disallowed Key Characters : '.$str); } // Clean UTF-8 if supported if (UTF8_ENABLED === TRUE) { $str = $this->uni->clean_string($str); } return $str; }

}

Read The Friendly Manual about core classes extension : http://ellislab.com/codeigniter/user-guide/general/core_classes.html

Upvotes: 2

Eugine Joseph
Eugine Joseph

Reputation: 1558

Open libraries/Input.php (system/core/Input.php in CI version 2.0+) and locate function _clean_input_keys($str){,

Modify if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str)) to if ( ! preg_match("/^[a-z0-9:_\-|]+$/i", $str))

Upvotes: 2

Keith Ritter
Keith Ritter

Reputation: 351

I had the same error after I posted a form of mine. I simply missed the opening quote in one of my input name attributes. I had:

<input name=first_name">

Fixing that got rid of the error.

Upvotes: 3

MortalViews
MortalViews

Reputation: 1260

In my case, i was serializing an input form using jquery serialize() and then urlencoding it using encodeURIComponent().

var datas = form.serialize();
encodeURIComponent(datas);
$.getJSON(url,datas,function(){});

and codeigniter was giving the disallowed character error.

i figured the issue here was, jquery serialize gives an encoded output and i was again encoding it with the encodeURIcomponent which was unnecessary, and when codeingiter decoded it it was not getting the actual string as some part was encoded twice. i will explain it with an example.

string: quantity[]=1&option=sell

urlencoded while serializing: quantity%5B%5D%3D1%26option%3Dsell

again urlencoded with encodedURICompontent(): quantity%255B%255D%253D1%2526option%253Dsell

---at codeigntier

urldecode: quantity%5B%5D=1&option=sell

which has disallowed charecters as per the input class regex.

note: this is not an answer to this question, but would help to check if one is encountering this error...thanks.

Upvotes: 1

richardwhitney
richardwhitney

Reputation: 532

function _clean_input_keys($str)
{
if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str))
{
exit('Disallowed Key Characters.');
}

return $str;
}

Please add .$str to exit('Disallowed Key Characters.'); Like: exit('Disallowed Key Characters. '.$str);

to help you in your search for rogue errors.

Upvotes: 3

RobertPitt
RobertPitt

Reputation: 57268

Open libraries/Input.php (system/core/Input.php in CI version 2.0+) and locate function _clean_input_keys($str){, The whole block should look like so:

function _clean_input_keys($str)
{
    if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str))
    {
        exit('Disallowed Key Characters.');
    }

    return $str;
}

Modify the PCRE sot that it allows the new chars.

Please not that the char thats missing is the .(dot) and you should always escape the .(dot) in Regular Expressions as they will otherwise allow any single char.

/^[a-z0-9:_\/-\.]+$/i

Upvotes: 27

Khairulnizam Dahari
Khairulnizam Dahari

Reputation: 297

To use CodeIgniter with jQuery Ajax, use "Object" as data instead of Query string as below:

$.ajax({
    url: site_url + "ajax/signup",
    data: ({'email': email, 'password': password}), //<--- Use Object
    type: "post",
    success: function(response, textStatus, jqXHR){
        $('#sign-up').html(response);
    },
    error: function(jqXHR, textStatus, errorThrown){
        console.log("The following error occured: "+
                    textStatus, errorThrown);
    }
});

Upvotes: 9

DavidHyogo
DavidHyogo

Reputation: 2898

I got this error when sending data from a rich text editor where I had included an ampersand. Replacing the ampersand with %26 - the URL encoding of ampersand - solved the problem. I also found that a jQuery ajax request configured like this magically solves the problem:

request = $.ajax({
        "url": url,
        type: "PUT",
        dataType: "json",
        data: json
    });

where the object json is, surprise, surprise, a JSON object containing a property with a value that contains an ampersand.

Upvotes: 2

John Rand
John Rand

Reputation: 1034

The error I referenced was generated in system/libraries/Input.php (about line 215 - look for function _clean_input_keys($str).

The regex there does not allow for the dot character in an index. I changed it so it would.

Upvotes: 0

Tilman Koester
Tilman Koester

Reputation: 1739

Php will evaluate what you wrote between the [] brackets.

$foo = array('eins', 'zwei', 'apples', 'oranges');
var_dump($foo[3-1]);

Will produce string(6) "apples", because it returns $foo[2].

If you want that as a string, put inverted commas around it.

Upvotes: 2

Related Questions