I don't remember where I read this: Passing data via the form action attribute is safer than passing it via a href attribute. Safer in terms of validatin开发者_StackOverflow社区g the segment because it's $_POST and you can compare tokens for csrf protection when a form is submitted unlike a direct link. Is this true?
If suppose I have the following action in a form,
<form method="post" action="/edit/pictures/delete/2235/">
Can I get the URI segment 2235
via $_POST?
Edit: Please assume that there is a URL rewrite. 2235
is a variable value. I'm not asking how to retrieve 2235
, just if I can retrieve it via $_POST
On your action page, explode $_SERVER['REQUEST_URI']
.
$parts = explode('/', $_SERVER['REQUEST_URI']);
foreach($parts as $slug)
{
echo htmlspecialchars($slug);
}
You should be able to extract that ID.
Another approach is just to put it as a hidden HTML field:
<input type="hidden" name="id" value="2235" />
When you POST a form to a php endpoint, $_POST only gets populated with data from the input elements. The request path is available in $_SERVER['REQUEST_URI']
. To get the id id out of the request path, you'll probably want to use a regular expression like this:
preg_match('/\/\d+\/?$/', $_SERVER['REQUEST_URI'], $matches);
$matches[0] // Contains '2235'
Regarding your question about safety -- the answer is POST is absolutely no safer than GET. They are different HTTP verbs, and carry data in a slightly different way, but either way the data your app receives cannot be trusted. It's just as easy to spoof a POST request (like a form) as it is to spoof a GET request (like an anchor link).
If you use such URLs, you'll probably have some .htaccess that translates it to query parameters accessed from $_GET - try something like this [writing from my mind, needs testing]:
RewriteRule ^/edit/pictures/delete/(.+)$ ?module=pictures&action=delete&id=$1
If not, you can always access $_SERVER['REQUEST_URI']
and extract necessary information from there.
精彩评论