Reputation: 1120
I know finding alternatives to eval()
is a common topic, but I'm trying to do something I've not done before. I am processing known-format CSV files, and I have built rules for how the data will be handled depending on the source columns available.
Here is a simplified example of what I'm doing. In this example, $linedata
represents a single row of data from the CSV file. $key["type"]
points to the column I need the data from. If this column holds the value of "IN", I want $newcol
set to "individual", else "organization".
$key["type"] = 12;
$linedata[12] = 'IN';
$rule = '($linedata[($key["type"])] == "IN" ? "individual" : "organization");';
eval ('$newcol = ' . $rule);
So $rule
stores the logic. I can run a filter on the $linedata
array to try and protect from malicious code coming from the CSV files, but I wonder if there is a better way to store and process rules like this?
Upvotes: 0
Views: 1783
Reputation: 9428
I was wrong.
I can be wrong, however create_function
may be good enough.
http://www.php.net/manual/en/function.create-function.php
Upvotes: 0
Reputation: 98459
You cannot store arbitrary PHP in a CSV file and then expect it to work without calling eval
(or similar functionality).
The safe way to do what you're asking for is to treat the file as data, not code.
This is why languages like BBCode exist: you can't have an inert language trigger active features directly, so you create an easy-to-interpret mini-scripting-language that lets you achieve what you want.
In other words, you cannot store active "rules" in the file without interpreting them somehow, and you cannot simultaneously allow them to contain arbitrary PHP and be "safe". So you can either attempt to parse and restrict PHP (don't, it's tough!) or you can give them a nice easy little language, and interpret that. Or, better yet, don't store logic in data files.
Upvotes: 2