PHP下划线在filename变量?

Why is there an underscore for data_?

Is there a simpler way of writing this, so that it makes more sense in terms of code readability?

My analysis:

data_ is supposed to take whatever data_ is, request a message via the variable postmessage from the form and make sure it's text and concatenate all this:

 $filename = 'data_'.$_REQUEST['postmessage'].'.txt';

I am a beginner and my analysis of this code could be wrong, but I am willing to learn from my mistakes.

Let's break it down a bit:

  1. $filename = - assigning a value into a variable called $filename.
  2. data_ - just a string.
  3. $_REQUEST['postmessage'] - the value of the postmessage request parameter (could be either POST, GET or a COOKIE parameter. Try not using $_REQUEST too often, unless you absolutely have to. Use $_GET or $_POST instead). This would come from your form (as you've mentioned).
  4. .'.txt' - just a string.

A dot between the elements above is used to concatenate the strings.

About your comment "and make sure it's text" - wrong. It doesn't make sure it's text. You need to make sure of that yourself and you probably should (for security reasons).

It depends on what you want. Let's say $_REQUEST['postmessage'] contains "foo". The first example will produce $filename = 'data_foo.txt', while the second one will produce $filename = 'data.txtfoo'. (OP removed second example from question)

I'd guess the first one is the desired outcome, but that depends on your needs. It's just string concatenation, that's all.

It looks like you're just sequencing a string in this code.

The . is a concatenation operator.

So $filename would contain

data_somethingorother.txt

The underscore is part of the string you're constructing.

It's part of the filename. Don't ask us why the name of the file contains it...
Just take care, it's not safe not to validate what comes in $_REQUEST['postmessage'] before using its value.

With regard to readability, I'd suggest to surround the string concatenation operator . with spaces. Thus, something like:

$filename = 'data_' . $_REQUEST['postmessage'] . '.txt';

Using a text editor / IDE with PHP-targeted syntax highlighting may also help a lot. A basic PHP tutorial will also do so.

As others have said, it's just constructing a filename from a GET/POST variable. As far as readability, I think it's fine.

However, you need to be very careful when using GET/POST variables, or anything that a user can change, to construct file paths. I would almost always say you shouldn't do it at all. If you're going to, at least make sure they can't do things like postmessage=../../filename.

Ditto,

However, I'd define a variable to store the request variable. It makes your code easier to read, therefore easier to debug. It will also make performing sanitization cleaner.

$postMessage = $_REQUEST['postmessage']; $filename = 'data_' . $postMessage . '.txt';