• 0

[PHP] Extracting Key and Data from $_POST and making them variables


Question

Hey guys.

I'm trying to take the key from $_POST and turn it into a variable with the data assigned so a shorter way of doing this:

$_POST['username'] = $username;
$_POST['password'] = $password;

and so on.

I've tried a simple foreach loop without much success

  foreach($_POST as $key=>$value){
            if (function_exists("mysql_real_escape_string")){
                if (get_magic_quotes_gpc()){
                  $key = stripslashes($value);
                }
                $key = mysql_escape_string($value);
            }
           print_r($key);
     }

but this doesn't quite work how I thought it would :<

Whilst it does escape the data I can't then grab the individual key I want. This is probably a stupidly simple thing I'm missing but I can't get it :<

I want to use this to clean up data before its entered into the mySQL database any ideas?

7 answers to this question

Recommended Posts

  • 0

Are you trying to replicate the PHP4 register_globals functionality, except only with $_POST?

Something like this should do what you want. It uses a simple foreach loop and variable variables:

foreach ($_POST as $key =&gt; $value) {
    $$key = $value;
}

BUT, I highly recommend you DON'T to this.

Instead, test for the variables you want to exist in the request, validate them, escape them and use them in your query / output. DON'T blindly accept any and all variables and especially don't turn them into new variables like this. It might seem easier this way, but you're potentially opening up a huge can of worms for yourself if you do. Even if your SQL queries are safe, there are many other things they can done to cause problems for your script. For example you might have some otherwise inert HTML stored in a variable called $html which could be replace with something of my choosing, or your database connection resource as $db, which could be replaced with something else and cause your query to fail. They might not seem too impressive, but they might help to reveal further attack vectors which could be used to compromise your script or they might be used to infect your visitors or your site.

  • 0

PHP has a built in extract function which does that; http://uk3.php.net/extract but like it mentions on the page (and mentioned here) I wouldn't recommend using it on $_POST/$_GET.

Edit: ah sorry didn't see you wanted it to automatically escape the variables, extract wouldn't fit your needs anyway then :p

  • 0

$username = $_POST['username'];
$password = $_POST['password'];

is actually the correct way of doing this. You also aren't escaping the variables, so it could lead to problems, and you aren't encrypting the password, another big no no.

  • 0
&lt;?php
$whitelist = array(
  'username',
  'password'
);

foreach($_POST as $key =&gt; $value){
  if(in_array($value, $whitelist)){
    $$key = mysql_real_escape_string(
      get_magic_quotes_gpc() ? stripslashes($value) : $value
    );
  }
}

  • 0
  On 20/02/2011 at 16:35, Andrew Lyle said:

$username = $_POST['username'];
$password = $_POST['password'];

is actually the correct way of doing this. You also aren't escaping the variables, so it could lead to problems, and you aren't encrypting the password, another big no no.

I wasn't escaping them in that part, I shouldn't have put that as my example :p. That was just to help show what I wanted from the foreach loop. The escaping data would have been part of the foreach but it wasn't the question. Sorry for the confusion :(

And yeah I put them the wrong way round :( I was kind of in a hurry :(

Don't worry I am escaping and hashing passwords :D

  • 0

A similar question was recently posted here, have a quick look at this thread about the security concerns and possible solutions.

Here's a possible solution using array functions on $_POST to produce a filtered array which is then extracted. (Note: code not thoroughly tested)

&lt;?php

// White list of allowed fields.
$allowed = array( 'username', 'password' );
// Make an array with these fields as keys, all values are null.
$allowed_keys = array_combine( $allowed, null );

// Compute the intersection based on the array keys
// of the unfiltered $_POST with the white list.
// The result is a filtered array which should be safe to extract.
// Note that $_POST is passed as the first parameter, as this array
// should be used for the values. (see PHP documentation)
$filtered = array_intersect_key( $_POST, $allowed_keys );

// Before extracting, we can escape all values in the array.
$filtered = array_map( "mysql_real_escape_string", $filtered );

// If an allowed field was not passed through POST, it won't
// be in the filtered array and the accompanying variable would
// not be set when extracting. We can assign nulls to all unset
// fields by merging the filtered array with the white list again.
// Note that $filtered is passed as the last parameter, as array_merge
// uses the last value in the resulting array.
$filtered = array_merge( $allowed_keys, $filtered );

// Now we can extract.
extract($filtered);

?&gt;

A few remarks:

  • It may not always be convenient to have all post variables escaped. For example, when echo'ing a username, you don't want those extra backslashes in your output. I suggest you to think about why you want this, perhaps there's a better solution.
  • I'm not using any magic quotes related checks, I'll leave that for you to implement when necessary. Basically, you just need to make your own filter function and use that as callback for array_map.

Just remember to always use white lists (not black lists). :)

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I know I will get shot down for this, but I prefer Windows 8, take the start screen away and use a third party start menu and Windows 8 was a pretty good OS for Microsoft. It was stable and ran very smoothly on my AMD bulldozer based computer, Windows 10 ran like a dog. When I changed to a Ryzen 7 17090 CPU, I tried to keep Windows 8 on it, but MS made that difficult with pop-ups all the time to get me to change to Windows 10 and the hacks to stop it, did not work that well. I have seen for a few years now the way Windows is going, and I don't like it and with Windows 11, what I saw was happening with Windows 10 have got worse with 11, certainly now with this AI rubbish. When I was looking at updating my PC a couple of years ago, I was looking at what CPUs were available, price and if it was going to make a lot of difference to what I use the machine for. To update my Pc to would have cost me £700 or more, that is just for the CPU, memory and board, maybe get a new case, the GPU is fine for what I use it for. I waited to see what AMD was bringing out and I thought I would look at what Apple was doing with their machines, and they launched the M2 machine at around the same time as AMD launched a new gen version of their Ryzen chip. A Mac mini m2 pro was £1,300, I had saved the money up over 12 months and yes the mini was over £600 more than the parts to update the PC, but it was a complete computer. I had the money, so I thought stick it, let's go for it. I don't regret it, what I do regret is not going for Mac years ago. Saying that Apple used Intel chips and I hate intel. I will have to update the PC at some point, but I will go for a R5 and not R7 and have less memory and a cheaper motherboard as the machine is only used for a few games these days.
    • Gemini CLI brings AI smarts to your Firebase terminal experience by Paul Hill Google has added its Gemini AI model directly into the command-line interface of Firebase Studio, its cloud-based IDE that uses AI to help with projects. The Gemini Command Line Interface (CLI) means that developers can expand past using AI for code, they can now also use AI for content generation and research without leaving the IDE. Gemini CLI comes with free usage tiers (60 model requests per minute, 1,000 requests per day with a Google login), it offers advanced AI features, and includes integrated Google Search for real-time content. Gemini CLI is also open source so it can be customized and accepts contributions. Accessing the Gemini CLI within Firebase Studio is straightforward, just press “Code view” in the top-right. From there, open up the terminal from the burger menu then select Terminal and New Terminal. Then in the terminal, type gemini and go through the setup, you can just press enter twice to get started. Out of the box, you’ll be able to get started with Gemini 2.5 Pro by just typing a query and pressing enter. There is also a non-interactive mode that’s useful for scripting and automation. To use it you use the –prompt or -p flags followed by your query wrapped in quotes, for example: gemini -p “What is the capital of France?” In this mode, Gemini CLI automatically closes after completing the request. During setup, there was the option to choose a theme. If you ever want to change it or look at other settings such as usage states, tool access, or checkpointing, you can edit them via .gemini/settings.json. You can also add API keys or choose different models in .env and you can using GEMINI.md to provide project-specific context, instructions, and coding styles in Gemini for a more tailored response. With Gemini CLI, you can have it explain code, refactor code, debug errors, and summarize information. It’s as simple as typing explain [file], refactor , debug “Error message”, or summarize “topic”. There are also built-in commands for managing the session such as /help for a command list, /chat to save and resume conversations, /tools to see available tools, and /restore to undo tool-made file edits. Firebase Studio, in true Google fashion, is a cloud-based IDE used in your web browser, making it excellent for weaker computers. To get started, you can head to the Firebase website. From there, tap Studio in the top-right.
    • I would prefer local ai over online ai on some tasks . They are good enough for tasks like artificial voice , image editing , text corrections , tagging etc . Local AI on Windows Photo editor is impressive for example . There are probably many other Ai that we could run on simple pc with GPUs .
    • oh look, we are under the control of the U.S again, is it not about time we as a country did this ourselves if they want it, not rely on greedy U.S. tech companies? We are capable of doing so as a country. I hate how the U.K have gone with no industry like we used to have and relying on other countries. Maybe we should follow Trump words, and make Britain great again and stop bending over to please Trump and other countries. Our government is Trumps puppet. I know we need to co-operate on some things, but come on.
  • Recent Achievements

    • Week One Done
      MIghty Haul earned a badge
      Week One Done
    • One Month Later
      MIghty Haul earned a badge
      One Month Later
    • Collaborator
      KD2004 earned a badge
      Collaborator
    • One Month Later
      ataho31016 earned a badge
      One Month Later
    • One Month Later
      Delahenty Machinery earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      592
    2. 2
      Michael Scrip
      200
    3. 3
      ATLien_0
      192
    4. 4
      +FloatingFatMan
      140
    5. 5
      Xenon
      127
  • Tell a friend

    Love Neowin? Tell a friend!