PHP filename parameter query - php

First of all I have checked the other suggested answers and I'm not certain whether they actually cover the question I've got. I'm very new to PHP so please forgive me if I am asking what sounds like a stupid question.
I have a php file which is called from another php file with a parameter
I understand how this works in the calling file.
I don't understand how to extract the parameter contents into a variable at the target end.
Let's say for a moment that in the address bar of the browser I get this:
targetfilename?parameter=Fred_hippy
I now want to pass "Fred" and "hippy" to a two-element array inside targetname.php. That's it, nothing else. (I said I was new to PHP.)
I think the way to do this is:
$file = substr($targetfilename, 13);
$name = explode("_", $file);
Is that correct please? If not could somebody tweak it please?
Thanks.

All parameters (everything after the ?) are returned as $_GET or $_POST array. If you are typing into the address bar (as opposed to using a FORM) then it is always GET. PHP makes it really easy:
$parameter = $_GET['parameter'];
$name = explode("_",$parameter);
That leaves $name[0] = 'Fred' and $name[1] = 'hippy'.
In older versions of PHP, the $_GET to variable assignment was done automagically, which was very useful but also opened a lot of possible security issues, so that has been deprecated.
Another note based on comments. An alternative to:
targetfilename?parameter=Fred_hippy
is
targetfilename?name=Fred&status=hippy
which would be read in PHP as:
$name = $_GET['name'];
$status = $_GET['status'];
with no explode() needed. Basically, PHP understands the standard protocol for sending parameters via GET & POST and takes care of a lot of the details for you.

Related

Laravel use string from MySQL as variable

Good night, I have a code that substitutes the data from the request and displays it, like this:
$client = User::find($data['$id']);
$execute = 'Send command ';
$execute .= $client->id;
dd($execute);
It return
^ "Send command 1"
Everything is working.
But I want that if I add a variable to the database, for example, like this
$client->id
, and call it, then I need the code to process it as a variable, and not as a string, how to do this, thanks)
Example:
(inside the variable $cliend in the database will be the following code:
$client->id
Code:
$client = DB::table('users')->where('id', $id)->value('id');
$execute = 'Send command ';
$execute .= $client;
dd($execute);
It is necessary that this variable be executed as a variable. and returned its value not from the database, but as in the first example
Having to store variable names into the database is extremely bad practice although PHP does natively support variables variable.
In your case, I do not see how you could implement this against an object without having to eval some additional code against, assumingly, untrusted user input.
I would first suggest redesigning your database logic to avoid this but if this is necessary or/and your data is controlled then here is a solution:
// Your object you want to access the value of
$client = (object) ['id' => 1];
// Data from your SQL statement that stores that variable name
$databaseValue = '$client->id';
// Eval and store result as variable
eval("\$value = {$databaseValue};");
// Result: Send command 1
echo "Send command {$value}";
See it working over at 3v4l.org
Some additional thoughts, you could potentially use regex to capture that the stored data is indeed a variable and only grab the first match.
^\$(?:[a-z]||[A-Z])\S+
You can see an example of this over on 3v4l.org where we remove any potential bad stuff from the data but this is a very blacklisted approach and you should always look to take a whitelisted approach. Just hoping this helps down the line somewhere else.
For some explanation, please checkout regex101 where I added some examples how this could be easily escaped and is no way the ultimate solution.
Update: Here is another regex you could potentially use to narrow down this even further.
(?:\s|^)\$(?:[^\s]+?)(?:[a-z])+(?:->|$)?(?:[a-z]|[A-Z])+
Example and explanation can be found over at Regex101. PHP example can be found over at 3v4l.org (which remember is still never perfect).

PHP Variables - same var, different values ok?

Basic PHP Question...
Is it okay to use the same variable name ($image) over and over again in the same php file, if you keep changing it's value? Or do you need to do $image1, $image2 and so on...?
It's working to do it with the same variable/different values, but I'm not sure if it's a bad practice? (I'm still learning, obviously.)
Here's a simplified example:
$image = get_field('image_3');
echo $image
...
$image = get_field('image_5');
echo $image
Also, I'm referring to what I assume are global variables. The variable is not set within an individual function. Do I need to unset the variable each time if I do it this way? Or is this ok?
Thanks!
Of course it's a bad practice, because it's hard to understand what is it currently inside the $image when reading the source code.
However, it's perfectly valid PHP code, variables in imperative languages like the Algol family of languages are meant to be changed.
By the way, you almost never need to unset() the value of a variable, only in clever tricks or when working with really large datasets.
You may use var_dump() for the best practice and also you may use unset() when it remains unhelpful
As PHP is not a typed language, you may do this.
Typed (Java):
float i = 3.563
string s = "3.563"
Non-Typed (PHP):
e.g on Line 10: i = 3.563;
Then, further down: i = "3.563";
In a non-typed programming language, it is up to you, to not having a chaos with your var-names. My advice is:
Basically, it is allowed, but...
If suddenly, you'll put a boolean or a float in previously stringed variable, I'd say, that's not clean programming.
You may encounter problems in bigger applications. Here's why:
For you as a programmer, it's cleaner to create another variable for other values, than e.g.
$image = get_field('image_3');
and further down you say: $image = true;
Will you remember on line 10'000 (or as commented: on line 42) what kind of value you had in the $image var?
But if you have an $image var and a $someThingIstrue var, you'll see by the name of the variable, what it's for.

How can I get all submitted form values in PHP and automatically assign them to variables?

I'm trying to migrate a website from one host to another. On the first host, when you submit a form, all of the form values are automatically stuck into variables with the input name (this is PHP). On the new host, these values are all null unless I do this:
$data = $_GET['data'];
Is there a PHP configuration setting that is causing this? If there isn't, is there an easy way to loop through all of the $_GET variables and automatically assign their values to a variable with the same name?
Thanks!
The setting is register_globals, but it is now deprecated and strongly advised against using it because it is a security risk. Anyone can set variables in your script which might interact in a negative or unexpected way with your code.
If you absolutely must, you can do it like this:
foreach ($_GET as $key=>$value) {
$$key = $value;
}
or, more simply:
import_request_variables("g");
or, to make it a little safer:
import_request_variables("g", "myprefix_"); // This way forces you to use "myprefix_"
// in front of the variables, better ensuring you are not unaware
// of the fact that this can come from a user
extract($_GET) could also work, as someone else pointed out, and it also allows specification (via extra arguments) of adding a prefix or what to do if your extraction conflicts with an already existing variable (e.g., if you extracted after you defined some other variables).
Look at the extract function : http://www.php.net/manual/en/function.extract.php
You could do something like this:
foreach ($_GET["data"] as $name => $value){
$$name = $value;
}
The issue with this is that it makes it easy for people to fiddle with the variables in your script. I could visit http://yoursite.com/?sql=DELETE+FROM...
I'd advise against doing this and just sticking to using $_GET.
Your question infers you are not doing any filtering or validation when assigning $_GET['data'] to $data, unless you are doing these kind of checks further down your script.
From what I have seen most programmers would do this first, in an effort to fail early if expected data did not match expectations, so that the above assignment in the case of expecting a positive int would become something like:
if( isset($_GET['data']) && (int)$_GET['data'] === 0){
//fail
}else{
$data = $_GET['data'];
}
So seeing just plain
$data = $_GET['data']
makes me wince.

Easiest and most efficient way to get data from URL using php?

Solution?
Apparently there isn't a faster way, I'm okay with that.
I am just learning php and I am trying to figure out some good tips and tricks so I don't get into a bad habit and waste time.
I am passing in values into a php script. I am using $_GET so the URL looks like this:
/poll_results.php?Sports=tennis&cat=Sports&question=Pick+your+favorite+sports
Now I know how to accept those values and place them into variables like so:
$sports = $_GET['Sports'];
$cat = $_GET['cat'];
$question = $_GET['question'];
Super simple yet if I am passing 5 - 6 things it can get bothersome and I don't like typing things out for every single variable, that's the only reason. I know there is a better way of doing this. I have tried list($var, $var, $var) = $_GET but that doesn't work with an associative array just indexed ones (i think).
I also tried variable variables like so:
foreach($_GET as $value) {
$$values = $value;
echo $$values;
}
But that gave me a Notice: Undefined variable: values in poll_results.php on line 14. Line 14 is the $$values = $value. I don't know if that's a big deal or not... but I'm not turning off error reporting as I am still in the process of building the script. It does do what I want it to do though...
Any answers will be copied and pasted into my question so the next person knows :D
Thanks guys!
Your second bit of code is wrong. It ought to be like
foreach ($_GET as $key => $value) {
$$key = $value;
}
if i understand your intent. However, you're basically reinventing register_globals, which....eh. That'll get ya hacked.
If you have certain variables you want to get, you could do like
foreach (array('Sports', 'cat', 'question') as $key)
{
$$key = $_GET[$key];
}
which is less likely to overwrite some important variable (whether by accident or because someone was messing around with URLs).
Use parse_url() to extract the query string from a URL you've got in a string, then parse_str() to extract the individual arguments of the query string.
If you want to pollute your script with the contents of the superglobals, then you can use extract(). however, be aware that this is basically replicating the hideous monstrosity known as "register_globals", and opens all kinds of security vulnerabilities.
For instant, what if one of the original query arguments was _GET=haha. You've now trashed the $_GET superglobal by overwriting it via extract().
I am just learning php and I am trying to figure out some good tips and tricks so I don't get into a bad habit and waste time.
If I am passing 5 - 6 things it can get bothersome and I don't like typing things out for every single variable, that's the only reason.
What you are trying to do will, unless curbed, become a bad habit and even before then is a waste of time.
Type out the variables: your digits like exercise and your brain can take it easy when it doesn't have to figure out which variables are available (or not, or maybe; which would be the case when you use variable variables).
You can use
foreach($_GET as $key => $value)
To preserve the key and value associativity.
Variable variables (the $$value) are a bad idea. With your loop above say you had a variable named $password that is already defined from some other source. Now I can send $_GET['password'] and overwrite your variable! All sorts of nastiness can result from this. It's the same reason why PHP abandoned register_globals which essentially does the same thing.
My advice: use $_POST when possible. It keeps your URLs much cleaner for one thing. Secondly there's no real reason to assign the array to variables anyway, just use them where you need them in the program.
One good reason for this, especially in a large program, is that you'll instantly know where they came from, and that their data should not be trusted.

What is the point of this line of code?

I found this line of code in the Virtuemart plugin for Joomla on line 2136 in administrator/components/com_virtuemart/classes/ps_product.php
eval ("\$text_including_tax = \"$text_including_tax\";");
Scrap my previous answer.
The reason this eval() is here is shown in the php eval docs
This is what's happening:
$text_including_tax = '$tax ...';
...
$tax = 10;
...
eval ("\$text_including_tax = \"$text_including_tax\";");
At the end of this $text_including_tax is equal to:
"10 ..."
The single quotes prevents $tax being included in the original definition of the string. By using eval() it forces it to re-evaluate the string and include the value for $tax in the string.
I'm not a fan of this particular method, but it is correct. An alternative could be to use sprintf()
This code seems to be a bad way of forcing $text_including_tax to be a string.
The reason it is bad is because if $text_including_tax can contain data entered by a user it is possible for them to execute arbitrary code.
For example if $text_include_tax was set to equal:
"\"; readfile('/etc/passwd'); $_dummy = \"";
The eval would become:
eval("$text_include_tax = \"\"; readfile('/etc/passwd'); $_dummy =\"\";");
Giving the malicious user a dump of the passwd file.
A more correct method for doing this would be to cast the variable to string:
$text_include_tax = (string) $text_include_tax;
or even just:
$text_include_tax = "$text_include_tax";
If the data $text_include_tax is only an internal variable or contains already validated content there isn't a security risk. But it's still a bad way to convert a variable to a string because there are more obvious and safer ways to do it.
I'm guessing that it's a funky way of forcing $text_including_tax to be a string and not a number.
Perhaps it's an attempt to cast the variable as a string? Just a guess.
You will need the eval to get the tax rate into the output. Just moved this to a new server and for some reason this line caused a server error. As a quick fix, I changed it to:
//eval ("\$text_including_tax = \"$text_including_tax\";");
$text_including_tax = str_replace('$tax', $tax, $text_including_tax);
It is evaluating the string as PHP code.
But it seems to be making a variable equal itself? Weird.
As others have pointed out, it's code written by someone who doesn't know what on earth they're doing.
I also had a quick browse of the code to find a total lack of text escaping when putting HTML/URIs/etc. together. There are probably many injection holes to be found here in addition to the eval issues, if you can be bothered to audit it properly.
I would not want this code running on my server.
I've looked through that codebase before. It's some of the worst PHP I have seen.
I imagine you'd do that kind of thing to cover up mistakes you made somewhere else.
No, it's doing this:
Say $text_including_tax = "flat". This code evaluates the line:
$flat = "flat";
It isn't necessarily good, but I did use a technique like this once to suck all the MySQL variables in an array like this:
while ($row = mysql_fetch_assoc($result)) {
$var = $row["Variable_name"];
$$var = $row["Value"];
}

Categories