How to addslashes automatically using Codeigniter? - php

I want to apply addslashes() to all the post elements got through
$this->input->post('my_var');
How can I do that ? Is there any feature like filters under wordpress for this ?

I think you want something global. My idea is to edit the global post function in the codeigniter to use addslashes on everything. You can find that function in:
/yourfolder/system/core/Input.php
You can escape it by setting it global.
function post($index = NULL, $xss_clean = FALSE)
{
// Check if a field has been provided
if ($index === NULL AND ! empty($_POST))
{
$post = array();
// Loop through the full _POST array and return it
foreach (array_keys($_POST) as $key)
{
$post[$key] = addslashes($this->_fetch_from_array($_POST, $key, $xss_clean));
}
return $post;
}
return addslashes($this->_fetch_from_array($_POST, $index, $xss_clean));
}
Although I don't really find it as good solution to modify the global functions this should do the trick in your case.
Edit: I see that input->post already does that and you would not need to add that function additionally.

Related

PHP OOP newbie - Need to get $_POST data into a variable

I was basically playing around with OOP and was creating a way to validate and sanitise input when I started to run into problems sanitising and then performing further validation. What I'm looking for is to take the posted $_POST['name'] data, sanitise the input to remove any numbers and validate that the data left is neither null or numeric characters.
But I cant get the sanitised input saved to $sanitised, It seems to be empty, but when I replace
$sanitised=$fv->noNumbers($_POST['name']);
with
$sanitised=preg_replace('/[0-9]/', '', $_POST['name']);
everything works fine, so I think I'm messing up something in this $sanitised variable.
I wanna learn so either a solution to this or a "you're an idiot and doing it all wrong" would be much appreciated.
<?php
class formSanitise {
public function noNumbers($value) {
$value = preg_replace('/[0-9]/', '', $value);
}
public function isEmpty($value) {
return (!isset($value) || trim($value) == '') ? true : false;
}
public function isAlpha($value) {
return preg_match('/[^a-z]/i', $value) ? false : true;
}
?>
processor.php
<?php
include('class.formSanitise.php');
$fv = new formSanitise();
$sanitised= $fv->noNumbers($_POST['name']);
if ($fv->isEmpty($sanitised)) {
$fv->addError('Name', 'Please enter something');
}
if (!$fv->isAlpha($sanitised)) {
$fv->addError('Name', 'Please enter your name');
}
?>
You'll either need to create a return in noNumbers or pass $value by reference.
Return method:
public function noNumbers($value) {
return preg_replace('/[0-9]/', '', $value);
}
Reference
public function noNumbers(&$value) {
$value = preg_replace('/[0-9]/', '', $value);
}
returning a value means that $value is an entirely different variable, and will be assigned to $sanitized when it's returned from the function. Passing by reference means that $value is the exact same variable as the one you passed to noNumbers and as such, anything that happens to the variable inside the function will happen to the variable that has been passed in.
In the above code snippet the function noNumbers does not return any value.The argument passed to the function has a scope within that function only and in order to make that value available to calling function there must be a return statement within function which will return the value to the calling function .Alternatively you can pass the value to function by reference .

Can $_GET['foo'] param be simulated?

I have a function that uses its own params but also checks if any get/post values are avaliabe for different behavior.
I'd like to be able to do that in the home page, which url is: domain.com/
For example:
function simulate_get($name,$val){
// do it
}
And then, in code
..
simulate('foo','last_posts');
show_user_posts($user,$bla,$ble);
..
I know that I should add an extra paramerter to the function but still wondering if is actually posible in PHP to do that.
Just write to it:
function simulate_get($name, $val)
{
$_GET[$name] = $val;
}
As $_GET is a superglobal you can just do:
$_GET['foo'] = 'last_posts';
and then directly use it in your code:
$_GET['foo'] = 'last_posts';
show_user_posts($user,$bla,$ble);
or if you want to use a function to set it:
function simulate_get ($key, $value) {
$_GET[$key] = $value;
}
simulate_get('foo','last_posts');
show_user_posts($user,$bla,$ble);
Just change the contents of $_GET, that's no problem at all.
$_GET['foo'] = 'last_posts';

is it possible to foreach $this->input->post(); in codeigniter?

I am writing a library for CI and I have a method I call to gather all possible post variables. I would somehow like to leverage the xss and security classes built into the codeigniter input class.
Is that possible?
Here is the working method without any use of the CI input class.
private function parse_options()
{
foreach($_POST as $key => $val)
{
$options[$key] = $val;
}
return $options;
}
Why not then:
private function parse_options()
{
foreach($_POST as $key => $val)
{
$options[$key] = $this->input->post($key);
}
return $options;
}
Some 8 years later..
The documentation (https://www.codeigniter.com/user_guide/libraries/input.html) says this:
$this->input->post(NULL, TRUE); // returns all POST items with XSS filter
$this->input->post(NULL, FALSE); // returns all POST items without XSS filter
The reason for trying to only do it the ci-way and not bypassing ci is to keep things uniform. Likely.

PHP: call_user_func_array: pass by reference issue

The below function generates error when a function contains referenced arguments eg:
function test(&$arg, &$arg2)
{
// some code
}
Now I can not use call_user_func_array for above function, it will generate an error.
How to solve this problem?
I do need to use call_user_func_array.
Also assume that i don't know beforehand whether they are passed by reference or passed by value.
Thanks
When storing your parameters in the array, make sure you are storing a reference to those parameters, it should work fine.
Ie:
call_user_func_array("test", array(&param1, &param2));
A great workaround was posted on http://www.php.net/manual/de/function.call-user-func-array.php#91503
function executeHook($name, $type='hooks'){
$args = func_get_args();
array_shift($args);
array_shift($args);
//Rather stupid Hack for the call_user_func_array();
$Args = array();
foreach($args as $k => &$arg){
$Args[$k] = &$arg;
}
//End Hack
$hooks = &$this->$type;
if(!isset($hooks[$name])) return false;
$hook = $hooks[$name];
call_user_func_array($hook, $Args);
}
The actual hack is surrounded by comments.

Is there a better way to check POSTed variables in PHP?

I find in my PHP pages I end up with lines and lines of code that look like this:
$my_id = isset($_REQUEST['my_id']) ? $_REQUEST['my_id'] : '';
$another_var = isset($_REQUEST['another_var']) ? $_REQUEST['another_var'] : 42;
...
Is there a better, more concise, or more readable way to check this array and assign them to a local variable if they exist or apply a default if they don't?
EDIT: I don't want to use register_globals() - I'd still have the isset problem anyway.
How about wrapping it in a function?
<?php
function getPost($name, $default = null) {
return isset($_POST[$name]) ? $_POST[$name] : $default;
}
a better method might be to create a singleton/static class to abstract away the details of checking the request data.
Something like:
class Request {
private $defaults = array();
private static $_instance = false;
function getInstance () {
if (!self::$_instance) {
$c = __CLASS__;
self::$_instance = new $c;
}
return self::$_instance;
}
function setDefaults($defaults) {
$this->defaults = $defaults;
}
public function __get($field) {
if (isset($_REQUEST[$field]) && !empty($_REQUEST[$field])) {
return $_REQUEST['field'];
} elseif (isset($this->defaults[$field])) {
return $this->defaults[$field];
} else {
return ''; # define a default value here.
}
}
}
you can then do:
# get an instance of the request
$request = Request::getInstance();
# pass in defaults.
$request->setDefaults(array('name'=>'Please Specify'));
# access properties
echo $request->name;
echo $request->email;
I think this makes your individual scripts loads cleaner and abstracts away the validation etc. Plus loads of scope with this design to extend it/add alternate behaviours, add more complicated default handling etc etc.
First, use $_POST for POSTed variables. $_REQUEST is a mashup of many different incoming variables, not just $_POST and could cause problems.
One solution for your question would be to create a function that handles the isset() logic.
function ForceIncomingValue($Key, $Default) {
if (!isset($_POST[$Key]))
return $Default;
else return $_POST[$Key];
}
first of all, NEVER use the $_REQUEST variable, it'll lead to bugs and other problems during development
function getPOST($key) {
if(isset($_POST[$key])) {
return $_POST[$key];
}
}
note that this code leaves the variable empty when $_POST[$key] was not set
you could also adapt that code to enable you to instead provide you with a (sensible) default when the value could not be loaded.
function getPOST($key, $default = NULL) {
if(isset($_POST[$key])) {
return $_POST[$key];
} else {
return $default;
}
}
Is the set of variables you're expecting known at the time of the script's writing, or do you want to do this for an arbitrary set of values? If the former is true, you could do something like this:
# This array would hold the names of all the variables you're expecting
# and a default value for that variable name
$variableNames = array (...);
foreach ($variableNames as $key => $default) {
if (isset ($_REQUEST[$key])) $$key = $_REQUEST[$key];
else $$key = $default;
}
Basically, this takes advantage of PHP's ability to evaluate variables to create other variables (hence the double-dollar for $$key--this means create a new variable whose name is the value of $key).
I haven't yet come up with a good solution to the latter situation.
PHP's null coalescing operator!
$username = $_GET['user'] ?? 'nobody';
For a lot of variables, with a requirement check, anyone is free to use my expect function.

Categories