-1

I have a data file that my users upload with a section comprising of keys and values separated by tabs and line breaks:

key     value
city    London
year    1984

I import this into a script, then assign PHP variables with the names equal to the value:

$key = 'value';
$city = 'London';
$year = 1984;

This is used to populate templates that they've also uploaded.

This is my script that assigns to keys and values:

$userdata = explode("\n", $file);
foreach($userdata as &$line){
    list($key, $value) = explode("\t", $line);
    $$key = $value;}

I'm wondering if this is the best way to assign keys to values, if there are any security precautions I should take such as prevent certain key names, and if there would be a way to make a key equal to an array if the line has multiple tabs.

7
  • 1
    I'd just assign the key / value(s) to an array, eg $props[$key] = $value Commented Apr 6, 2017 at 0:52
  • You may want to look into variable variables. Commented Apr 6, 2017 at 1:06
  • "if there are any security precautions I should take such as prevent certain key names" - Counter-question: What do you foresee as being a security risk? If you're using this to store sensitive information, then you should consider using a database; or place it outside the public root area and safeguard it throuh .htaccess if you need to. Commented Apr 6, 2017 at 1:23
  • Plus, text files are a lot of work when it comes to managing them. Commented Apr 6, 2017 at 1:24
  • The security risk would be having that text file available to the public. Commented Apr 6, 2017 at 1:24

1 Answer 1

0

I think you should do this:

<?php
$filePointer = @fopen($file, 'r');
while($line = fgets($filePointer)){
  $a = preg_split('/\b\s+\b/', $line);
  ${$a[0]} = $a[1];
}
echo "key:$key; city:$city; year:$year;"
?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.