简体   繁体   中英

Turning a form's GET into a PHP variable?

I'm trying to make the following form's GET function to be part of a predefined variable.

Any ideas? Thanks in advance!


Let me explain a little more of what I'm really trying to do. I currently run a website concentrating on the US stock market. I've created an HTML form with a method=GET. This form is used like a search box to look up stock ticker symbols. With the GET method, it places the ticker symbol at the end of the URL, and I created a quotes.php page that captures this information and displays a stock chart based on what ticker symbol is keyed into the box. For the company names, I've created a page called company.php that declares all of the variables for the company names (which happens to be a $ followed by the ticker symbol). The file, company.php, is the only file included in quotes.php.

This is where this came in: ' . $$_GET["symbol"] . '

The above code changes the GET into the variable based on what was typed into the form. I've used "die" to display an error message if someone types something into the box that doesn't match a variable in the company.php page.

I've also added into the company.php page variables for each company that will display which stock exchange each stock is listed on. These variables begin with "$ex_". So, what I was trying to do was have the symbol keyed into the box appended to "$ex_" so that it would display the corresponding stock exchange.

My questions are:

  1. Is there a way to have what is typed into the form added to "$ex_"?
  2. Is this an insecure way to code something like this (can it be hacked)?

Thank you all!

Rather than prefixing your variables and using variable variables (that are potentially insecure especially with user input), try this:

$ex = array(
    "foo" => "bar",
    ...
);
if( !isset($ex[$_GET['symbol']])) die("Error: That symbol doesn't exist!");
$chosen = $ex[$_GET['symbol']];

Here's another approach:

extract($_GET, EXTR_PREFIX_ALL, "ex");

Although it's better to use it like this just to make sure there is no security issues.

extract($_GET, EXTR_SKIP);

PHP's extract() does what exactly what you want, and you should specify "ex_" as the prefix you want.

However, there are security issues and unintended consequences to using such a function blindly, so read up on the additional paragraphs following the function parameters.

Will the below achieve what you need?

$myGetVariable = $_GET['symbol'];
$ex_{$myGetVariable} = "Something";
$_GET['symbol'] = 'APPL';

if (!empty($_GET)) {
  foreach ($_GET as $k => $v) {
   $var = 'ex_'.$k ;
    $$var=$v;
  }
}

var_dump($ex_symbol);

APPL

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