简体   繁体   中英

Slim framework - php - how prevent injections?

As an android developer I would like prepare my server for request from android app. First aim was to create request link for adding items into database. So I have created something like that below in php file by Slim framwork.

My question is : is there any chance to inject "bad text" which would cause drop by database or do something less worse by calling /addEntry ? How could I prevent this?

ps I hope you follow me what I mean to say.

<?php

require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader(); 

$app = new \Slim\Slim();

$app->get(
    '/',
    function () {
        echo "working";
    }
);

ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);

$username = ;
$password = ;
$hostname = ;
$database = ;

$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");

if (!mysql_select_db($database)) {
    die("not connected");
}

//#addEntry
$app->post(
    '/addEntry',
    function () {
        $app = \Slim\Slim::getInstance();
        $cat_id = $app->request()->post('cat_id');
        $ent_name = $app->request()->post('ent_name');
        $ent_description = $app->request()->post('ent_description');

        if ($cat_id == NULL || $ent_name == NULL) {
            $app->halt(400);
        }

        mysql_query('SET CHARACTER SET utf8');
        mysql_query("insert into t_entries VALUES(NULL, '" . $ent_name . "', " 
                . (empty($ent_description) ? "NULL" : "'". $ent_description ."'")
                . "," . $cat_id . ", '0' );");

        return;
    }
);

$app->run();

$app->run();

I suggest you to use some existing ORM like Doctrine or Eloquent. Then you don't have to worry so much about user input as they are doing all hard work for you.

If you still want to use native php functions, don't use mysql_connect() as it's deprecated. Use mysqli_connect() instead. To prevent sql injections, use mysqli_prepare() to prepare SQL queries.

Also, you don't have to do this:

$app->post('/addEntry',function () {
    $app = \Slim\Slim::getInstance();

you can pass variables to closures with use keyword like this:

$app->post('/addEntry',function () use ($app) {

I suggest to use php function filter_var to sanitize input value. In Addition To this, I suggest to use ORM, such as RedBean or Eloquent or Doctrine. If you want to be more light try to use some librarym such as Dabble or Medoo . Finally, I suggest to don't use php native functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM