PHP initializing variables [duplicate] - php

This question already has answers here:
How to set PHP not to check undefind index for $_GET when E_NOTICE is on?
(3 answers)
Closed 9 years ago.
Im watching several php tutorials, and many of them start something like that:
<?php
if(!$_POST['username']){
..
..
};
?>
or
<?php
$username = $_POST['username'];
..
..
?>
but everytime I visit the page for the first time, it prints an error because $_POST['username'] was not initialize.
How can I I fix this?
thank u

There are four main HTTP methods you can use when making a request to a webserver: GET, POST, DELETE, and PUT. With each of these, you can pass variables with your request that PHP allows you to access. For GET and POST, you can access the variables with the corresponding arrays: $_GET & $_POST, respectively.
If you've never dealt with HTTP methods before, that's because you don't need to really think about it. This is because of the fact that when you type a URL into your browser and hit go, it uses the GET method by default.
So, in this case, what's probably going on is that you're just not making a POST request at all when you load your page. And even if you were, you'd need to have the proper POST variable defined to access it, which in this example would be username.
Since one of the above isn't true, the value of the variable is null. And when you try to access a null value in PHP, the script throws an error (as you've seen). You can change this, but I wouldn't recommend it. I like to know that I'm properly handling my null variables when I write code. But maybe that's just me.
The solution that I recommend, and that others have suggested, is to use the isset() function to see if the variable is defined. This will prevent your code from breaking. Check out the isset documentation for more.

<?php
if(isset($_POST['username'])){
..
..
}
?>

You can set error_reporting to E_ALL ~E_NOTICE
See the documentation on this: http://php.net/manual/en/function.error-reporting.php
or disable it globally in the php.ini file.

use isset($_POST['username'])
if(isset($_POST['username']))
{
.
.
.
}

$_POST['username'] is trying to get the 'username' variable which included the the POST http request to your page (think submitting a form). Normal browsing to a page is an http GET request.
Try using this to avoid issues:
<?php
if(isset($_POST['username'])) {
... if POST and includes a username value, do this ...
} else {
... otherwise do this stuff ...
}
Read me for more info on types HTTP requests: http://techforum4u.com/content.php/229-HTTP-Request-GET-HEAD-POST-PUT-DELETE-OPTION-TRACE

That's because you didn't recieve a value via POST (like from a form post). Add an isset() validation as others are suggesting. Take a look at http://php.net/manual/es/function.isset.php

Related

GET POST errors

All, I posted a code in a forum before and no one was able to answer this.
The "Sign Up" and "logout" are both buttons with value types on other pages that are linked to this page code called login.php
The problem is that I keep getting an undefined index. Is there a way to call it better?
I have..
if ($_POST['submit']=="Sign Up") {
and..
if($_GET["logout"]==1 AND $_SESSION['id']) { session_destroy();
header("Location:logout.php");
}
As both POST and GET variables must not be send at all, always use a scheme similar to this one:
$var = isset($_POST['fieldname']) ? $_POST['fieldname'] : null;
if ( !isset($var) )
{
// errorhandling
}
else
{
// proceed ...
The error you get indicates that at least one of your POST and/or GET variables is either not set or misspelled.
As Axel points out, check if $_POST has the value for "submit" using isset() function, if it is set, the you can access the value the way you are doing. If $_POST does not have the value for that, it means that it is not being sent.
So, in your HTML, check that the button is indeed called that way and that it is inside a tag with the ACTION attribute and METHOD set to POST.
Also be careful with comparing with 1, since in PHP is also means true.

Get variables inside includes [duplicate]

This question already has answers here:
PHP include() with GET attributes (include file.php?q=1)
(7 answers)
Closed 8 years ago.
What are the security implications of passing a get variable through an include?
Example:
index.php:
$lastname = $pulleddatabasevalue;
include "../includes/header?lastname=$lastname";
header.php:
echo $_GET["lastname"];
As the variable is dynamic, I have struggled to make include() or sessions work to assign the variable $lastname with the database value within the php include. However, $_GET here has worked fine. It doesn't show up on the browser address bar, thus can't be manipulated in a hostile manner there. Is there another way someone with malicious intent could work this code? Assume that the include directory is locked and I'm only referring to index.php.
Sorry, no way to pass get parameters to included file... See:
PHP include() with GET attributes (include file.php?q=1).
Include is a strict let's name it "Physical function". To make a get request, you must make a request. Include just read the file from the server.
BTW. I'm curious, how it is possible, you made it work. I think there is some misunderstood in your code.
You should think about include, as a COPY PASTE function.
In that case:
$var = true;
include ('include.php');
include.php:
var_dump($var);
should echo bool(true).
Hope it helps.
When talking about security issues, as far as I'm concerned, include in the way I describe, should not create any new security holes. But you should check all the permissions of included files, to be 100% sure.
The security implications of outputting user supplied input is the same no matter how it is done: ESCAPING AND VALIDATION IS ESSENTIAL! Otherwise you are implementing big security holes.
Apart from that, there isn't any difference whether you directly access $_GET, or first stuff that value into another variable and access that inside your include.
The only difference is of general software maintenance: The former usually is considered bad because it is access to a global variable, while the latter might be part of a function call and might encapsulate the variable name better.
Your code, however, is wrong. You cannot pass query parameters as part of the filename. It works because $_GET is available as an array everywhere without any further code (read "superglobal variable" in the PHP documentation).
Keep it simple and don't confuse...
index.php
$lastname = $pulleddatabasevalue;
include "../includes/header.php";
header.php
echo $lastname;
External refs. and recommended read:
http://www.php.net/manual/en/function.include.php
http://www.php.net/manual/en/reserved.variables.get.php

Variables in URL won't work when not testing locally

I've been working on a project on my local server. The time has come to upload it so I did just that. I started to test it out online and my navigation isn't working.
The navigation works by doing this:
Add
The page then checks whether $p exists and if it does, it shows the relevant content. For some reason though my content isn't showing up when I click the links. I turned on error reporting, and I added this (line 39)
echo $p;
to the document. Now I get this error: Notice: Undefined variable: p in /home/silver/public_html/admin/index.php on line 39 but only when testing online and it works fine when I test it locally.
I can post my code if I need to, but there's a lot of it and I'm not sure which bit is the problem.
UPDATE:
Thanks for all the replies, but I'm confused as to how you use your suggestions as I'm used to doing things the way I was.
At the moment, I do this to check what the $p variable is
<?php if(!isset($p)) { // DEFAULT PAGE VIEWED AT INDEX.PHP ?>
And use this to link to the page:
Add New Item
You're relying upon register_globals, an outdated and deprecated feature of PHP. This feature automatically translates GET, POST, COOKIE, SERVER etc. variables and inserts them into the global scope. This means that file.php?p=blah would result in $p == 'blah'. This is a bad idea for lots of different scoping and security reasons outlined in the PHP manual.
Use the superglobals (e.g. $_GET, $_POST, $_SERVER) instead.
In response to your updated question, your code
<?php if(!isset($p)) { // DEFAULT PAGE VIEWED AT INDEX.PHP ?>
should become
<?php if(!isset($_GET['p'])) { // DEFAULT PAGE VIEWED AT INDEX.PHP ?>
You're relying on an old and very bad "feature" of PHP called register_globals that loads variables directly from GET. You need to do $p = $_GET['p'] if you want $p to be set via an HTTP GET.
Probably because 'register_globals' is ON on your dev system and OFF on your live system. Set it to OFF on your dev and use $_GET['p']
$p doesn't automatically get set from the parameter in the URL. You need to attach $p to the value coming from the URL by using the code $p = $_GET['p']; first.
Be weary though, you need to sanitize this GET parameter and/or create a whitelist to make sure it is a valid parameter.

php session variable not updating a 2 dimensional array after initializing

I'm almost embarrassed to ask because it seems so simple, but I can't get it to update.
When the user logs in I set the session vars like
array('users'=>array('timezone'=>'America/los Angeles'));
I can then retrieve the data as follows: $_SESSION['users']['timezone']
and it works fine.
However in the user profile page the user can change their timezone and when I try to update the $_SESSION as follows it doesn't work:
$_SESSION['users']['timezone'] = 'America/Denver';
What am I doing wrong?
--- More code as requested -------
I found that the session variables were being set by a function inside of a class
Here's the function:
function session_var_register($object_name, $var_value)
{
$_SESSION[$object_name]=$var_value;
}
Here's how the function got called:
$gf->session_var_register("users", $user_array)
Users Array looks like array('users'=>array('timezone'=>'America/los Angeles'));
I don't understand why this doesn't work. I was able to get around the problem though by bypassing the function call and just creating the array like:
$_SESSION['users'] = $user_array;
But for knowledge reasons and if anyone else comes along this post, could anyone explain what the function was doing different? There were no errors thrown, just would not allow me to assign anything to the session variable once it was registered via the function...almost acted like it became read_only once instantiated.
Make sure you session_start() on every page that accesses the $_SESSION variable.
Sounds like the code that updates it may not be getting executed. You might try putting some kind of debugging statement before this assignment like an echo to verify that the action is being taken.
Following on from Scott's reply, double checking your session is started is a good "start".
There's a good tip here which you may find useful in debugging.
re-initialize your session id. That way you are sure it has a new spanking id to store your variables.
Are you doing a redirect soon after this code?
Do a session_write_close() before doing a redirect so that session vars are stored again before redirecting.

Editing and creating things with address bar code?

How do I make it so that I can make a thing at the end of the address where the .php is and then tell it to do certain things. For example pull up a page like this:
sampardee.com/index.php?page=whatever
Help?
Anything else I could do with this?
This is generally achieved with the global php array $_GET. You can use it as an associative array to 'get' whatever variable you name in the url. For example your url above:
//this gives the $page variable the value 'whatever'
$page = $_GET['page'];
if($page == 'whatever'){
//do whatever
}
elseif($page == 'somethingelse'){
//do something else
}
Check out the php documentation for more information:
$_GET documentation
and there's a tutorial here:
Tutorial using QUERY_STRING and _GET
A small improvement over Brett's code:
if (array_key_exists('page', $_GET) === false)
{
$_GET['page'] = 'defaultPage';
}
$page = $_GET['page'];
// ... Brett Bender's code here
$_GET is usually used if you are sending the information to another page using the URL.
$_POST is usually used if you are sending the information from a form.
If you ever need to write your code so that it can accept information sent using both methods, you can use $_REQUEST. Make sure you check what information is being sent though, especially if you are using it with a database.
From your question it looks like you are using this to display different content on the page?
Perhaps you want to use something like a switch to allow only certain page names to be used?
i.e.
$pageName=$_REQUEST['page'];
switch($pageName){
case 'home':$include='home.php';break;
case 'about':$include='about.php';break;
case default:$include='error.php';break;
}
include($include);
This is a really simplified example, but unless the $page variable is either home or about, the website will display an error page.
Hope it helps!
I'm not quite sure what you're asking, but I think you're asking how to use GET requests.
Make GET requests against any PHP page as follows:
www.mysite.com/page.php?key1=value1&key2=value2
Now, from within PHP, you'll be able to see key1 -> value1, key2 -> value2.
Access the GET hash from within PHP as follows:
$myVal1 = $_GET['key1'] #resolves to "value1"
$myVal2 = $_GET['key2'] #resolves to "value2"
From here, play with your GET variables as you see fit.
The system of adding page parameters to a URL is know as HTTP GET (as distinct from HTTP POST, and some others less commonly used).
Take a look at this W3 schools page about GET in PHP and ahve a play about in getting parameters and using them in your PHP code.
Have fun!

Categories