Whenever I declare a variable inside a library like:
$Money="123";
The variable carries over to my other libraries like print page and export pdf.
However when I declare a variable using Post like:
$Money=$Post_["moneyNumber"];
My other libraries pull a null value. What can I do to carry on the variable? I need to be able to send the variable from a form input.
$Money=$Post_("moneyNumber");
is incorrect. You're using camel case for Post which should be all uppercase (see note about superglobals) and round brackets which should be square brackets, and you've a misplaced underscore also.
use
$Money=$_POST["moneyNumber"];
Also make sure your form is using a POST method, along with its element having a name attribute of name="moneyNumber"
Sidenote: "moneyNumber" is not the same as "moneynumber". Variables are case-sensitive, should that be the case in the rest of your unshown code. Same thing goes for $Money. So, if you're using $money elsewhere, then that is a probability.
$_POST is a superglobal:
http://php.net/manual/en/language.variables.superglobals.php
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Edit:
If you're trying to carry variables over more than two pages via POST, then that won't work. You will need to use sessions for this.
http://php.net/manual/en/reserved.variables.session.php
http://php.about.com/od/advancedphp/ss/php_sessions_2.htm
Related
I'm stuck with a php/mySQL thing..
I have a dynamically created form and I want to parse the $_POST variables it generates. To be specific,I have a query in SQL which generates the fields in my form. Then, I need to process these variables in the php file, where the action of the form goes.
However, I cannot parse the dynamically created $_POST variables. Below is my code:
$sql="just-a-query";
$result = mysql_query($sql);
while ($data = mysql_fetch_array($result)) {
${''.$data['parameterName']}=$_POST[$data['parameterName']];
}
For example, if I have 3 variables that got through the form the values:
house=1
tree=3
car=2
I would like to save them via php like this:
$house=$_POST['house'];
$tree=$_POST['tree'];
$car=$_POST['car'];
However I can't get through it. It returns Undefined index error. Any thoughts?
If you want to find if a variable is defined before using it, it's as simple as using isset():
if( isset($_POST[$data['parameterName']]) ) {
${''.$data['parameterName']}=$_POST[$data['parameterName']];
}
If on the other hand, it's supposed to be defined (you see the form element), but then it's not getting defined in the postback. First check to make sure that your form submission type is post, then check to make sure you are using the name attribute in the form elements.
thank you for your time. My problem was that I was parsing wrong parameters from the HTML.
Yes, I'm an idiot and yes, var_dump() helped me to figure my error.
Thanks again!
btw, my code was working perfectly. Ha!
Lets say I have an index.php file and some $_GET variables. After a few hundred lines of code I call a method, with the variables as parameters.
Should I validate the variables on top of everything, or should I validate them inside the class/method I call?
2 things in mind:
Avoiding to validate the variables multiple times, everywhere..
Having multiple sources, not only $_GET, and multiple calls to such a method from different files.
Some code:
<?php
function do_something($string) {
// Validate $string here?
}
// ...or here, before using it?
$result = do_something($_GET['some_string']);
This is a question where's no standard solution possible.
You could write yourself a helper class (i recommend this since this is a solution with less maintanance and best flexibility) which is called at the very first beginning of your index.php file, as some kind as a "contract" which is like:
<?
require_once "validator.php";
$validator = new Validator();
$validated = $validator->validateGet($_GET);
// all the remaining site's php code goes here
?>
this class could return anything you want, such like a boolean indicating whether every variable is okay or not, or an array containing the values with removed tags, etc.
Another barrier for cross site scripting and/or SQL injection should be prepared statements: http://php.net/manual/de/pdo.prepared-statements.php
All your SQL queries should also be contained in a external utilities class called ProductDataAccessObject (ProductDAO) or ProductQuerier, etc., which is also for structural/maintanance reasons.
But there's no rule that says "you must validate your variables at the very first beginning or at time of use"
Validate at the very first point when you are receiving $_GET at the entry level so that you are sure for the below code at later stage as well-
// Validate $_GET['some_string'] HERE
$result = do_something($_GET['some_string']);
If you validate here -
function do_something($string) {
// Validate $string here?
}
then there is a possibility that u miss the validation and it will open a loop hole in the code as validation is available only to the method this time.
If you are setting some values for the database, it is a good practice to double check the data and make it safe from code injections.
You can validate on top of the page your every single variable with a one line
$_GET = array_map("mysqli_real_escape_string",$_GET);
Array_map applies one function over every value of an array which in our case is applying mysqli_real_escape_string to the array $_GET
IMPORTANT:
Please do note this is only for sanitization and not validation
You need to validate every variable by your own, for example if what is being sent in an integer, make sure to use intval to validate it
Refer to this question for more information: Sanitization and Validation
I'm not satisfied with your answers yet, I did not ask HOW to validate, I did ask WHERE to do it.
Here is my own suggestion:
As I think the times for procedural coding in PHP are finally over (!!), I dont have any logic inside of my index.php, all logic goes into controller classes.
So you have a data Sender, and data Reciever.
As a Reciever (not only in PHP, it's something very common in realife, too), I have to validate the information sent by the Sender. The Reciever does not trust anybody (this is important in APIs for example). Therefore, validation has to be inside the methods you create, not at the top of index.php files or outside of a class. Imagine someone else using your method, is he going to validate the arguments, or has it been YOUR task? I think it's up to you, so you (the Reciever!) can throw Exceptions.
I also like to keep my data ($_GET, $_POST, ...) as raw as possible outside of the controller. Imagine you have a method which needs validated data at line 100, and a method at line 200 which needs raw data. Now on liee 5 you changed the raw into sanitized. => You have to keep two variables, $data and $data_raw, which is unnecassary overhead.
Think about it
So I am using the following style of code if(array_key_exists('some_value', $_POST)){echo 'hi';}
For PHP 5.2.17 I am getting a warning from this style of code. This is the warning:
WARNING: argument 2 for array_key_exists() is not either an array or an object on line: 123
This seems strange to me because I believe that the $_POST array should always be defined. Is that not the case? I'm not sure what would cause the $_POST array to not be considered an array. I am not resetting $_POST to anything so it should exist as an array at all times. Does anyone have any idea what is wrong. Please let me know if more information is needed and thank you for the help.
Edit: I should note that this only happens on the production server. My local environment does not have this problem.
The Superglobals $_POST and $_GET are only populated if the script is POSTed to or GET from. In your example, the reason that you'd get that error is if there was not post action to the script. Before checking for a certain post value, you should check to make sure there was a post:
if(isset($_POST)) {
//The form was posted
}
In that fashion. From there, you can check for certain values using array_key_exist, or you can further check isset($_POST['myKey']).
Use if(isset($_POST['some_value'])) { echo 'hi'; } instead. Never had a problem with it.
Also check if you are not overriding or unsetting $_POST (or some framework you are using is doing it for you). I avoid to do so with superglobal variables since I think it is a bad practice and might give headaches like this one.
I'm debugging some client PHP code that has me stumped. As this pseudo-example illustrates, there is code on the receiving end of a form submission that processes the form values, but without ever apparently assigning those values:
(On form submission, where form has fields 'name' and 'position'):
echo "The name is = ". $name;
echo "The position is = ". $position;
This code is part of a large app, and code from other files is called before this. BUT the crucial point is that if I do a search for '$name = ' across the entire codebase it never shows up. How then is it possible that the request variable gets assigned to $name? Is there another way to assign value to a variable in PHP other than $var = value??
My only other clue is that this project uses Smarty, which I don't know anything about.
It may be that the person that created the code was working on a server with register_globals on. What that does, for example, is create regular global variables as the result of a form submission rather than populating the $_POST or $_GET arrays.
If the register_globals directive has been set to true in php.ini, then all POST attributes will also show up as individual variables, in the way you describe. Note that this directive is false by default, and that use of this directive is deprecated.
When you look at the smarty documentation you can see that variables are assigned like this (copied from the linked page):
<?php
$smarty = new Smarty();
$smarty->assign('firstname', 'Doug');
$smarty->assign('lastname', 'Evans');
$smarty->assign('meetingPlace', 'New York');
$smarty->display('index.tpl');
?>
Technically yes there is.
$x = 'name';
$$x = 'harry';
echo 'Yer a wizard '.$name;
(I would be surprised if this was the reason)
I guess your server has register_globals setting on, which automatically generates variables from posted items:
$_POST['foo'] === $foo
Maybe this is another outbreak of the register_globals disease?
This has been thought to have died out, but surfaces again and again!
Sounds to me like someone included those variables with the intention of doing more with them, but never got around to doing so. Unless an include php page is assigning values to those variables, nothing will go in them.
Try turning your error reporting level up, if these variables are being used but haven't been initialised, a warning will be shown
There is a php file (current.php) with some variables, like:
function do() {
$var = 'something';
}
And one more php file (retrieve.php), which is loaded to current.php with jQuery ajax .load().
The problem is - retrieve.php doesn't see $var.
Tryed this (inside retrieve.php, shows nothing):
global $var;
echo $var;
How to fix?
Thanks.
Some things you must be aware of:
When you use PHP, you do not download a file: you execute a script and retrieve its output.
PHP variables are destroyed when the script ends. You cannot share variables between two scripts unless you store them somewhere (e.g., in a database or session file).
PHP variables are local to the function where you define them, unless you issue a global $foo; statement inside the function.
jQuery is a JavaScript library. JavaScript and PHP are different languages: they cannot see each other variables.
Said that, I suggest you reconsider your question and try to explain what you need to accomplish rather that how you want to implement it.
The problem is - retrieve.php doesn't see $var.
Sure it is!
all current.php variables are long dead along with current.php itself, which was run, print some HTML and die.
you have to pass required value using standard HTTP mechanisms. you know - GET, POST etc.
If you want the script you load through AJAX get the value of the vars from the page initiating the AJAX load then you either have to pass the values when loading the AJAX script or store them somewhere temporarily (in DB linked by session ID, or in a session var) so you can retrieve them easily.