Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid "PHP injection"

Tags:

security

php

I have this script

<?php $number = %value%; ?>

The %value% token will be replaced by a value on a DB input by a user.

My concern is that someone inputs something like:

1; echo phpinfo()

The result of the replace will be:

<?php $number = 1; echo phpinfo(); ?>

This is obviously a security risk.

Is there a function to escape php scripting characters or something I can use?

Thanks in advance.

Context

This is a tool on a CMS I'm working on, usually tools generate HTML code added to some PHP file.

In this case this tool generates an HTML structure from an RSS channel. We ask the user to input the RSS URL and the number of feeds to display, we replace those values into the PHP script and use them to get the feeds and display them in a HTML structure.

like this:

<?php
  $url = "URL"; //comes from DB
  $number = N; //comes from DB
  $feeds = getFeeds($url, $number);
  ...
?>
like image 292
Sebastian Perez Avatar asked Feb 22 '26 07:02

Sebastian Perez


2 Answers

The mechanics you described above are flawed. PHP just doesn't work that way. No user input will be executed (or to be more precise, interpreted by PHP) unless:

  • You run it through an eval() call
  • You save a combination of your code and user input as a PHP file and later execute it

What you should be worried is SQL injection which is an entierly different thing.

If you are referring to a scenario simillar to bullet #2, there is a good chance you are doing something quite wrong from the design perspective and you should rethink your approach.

like image 94
code_burgar Avatar answered Feb 23 '26 20:02

code_burgar


As mentioned by code_burgar.. this design is totally flawed. There should be no reason to build a server executed file on the fly. You should pull your recordset from the db, loop through it and execute your getFeeds() function for each record. Doing that would not execute any of the db provided data unless.. once again as cod_burgar says.. you use the eval() function.

like image 32
Brian H Avatar answered Feb 23 '26 21:02

Brian H