I have been working on a Timesheet Management website. I have my home page as index.php
//index.php (only relevant portion shown)
<?php
session_start();
if($_SESSION['logged']=='set')
{
$x=$_SESSION['username'];
echo '<div align="right">';
echo 'Welcome ' .$x.'<br/>';
echo' <b><u>Logout</u></b>' ;
}
else if($_SESSION['logged']='unset')
{
echo'<form id="searchform" method="post" action="processing.php">
<div>
<div align="right">
Username <input type="text" name="username" id="s" size="15" value="" />
Password <input type="password" name="pass" id="s" size="15" value="" />
<input type="submit" name="submit" value="submit" />
</div>
<br />
</div>
</form> ';
}
?>
The problem I am facing is that during the first run of this script I get an error Notice: Undefined index: logged in C:\wamp\www\ps\index.php but after refreshing the page the error vanishes.
How can I correct this problem? logged is a variable which helps determine whether the user is logged in or not. When the user is logged in $_SESSION['logged'] is set, otherwise unset. I want the default value of $_SESSION['logged'] to be unset prior to the execution of the script. How can I solve this problem?
When the session is initially started, $_SESSION is an empty array and $_SESSION['logged'] does not exist. And read access to uninitialized variables or array indexes throw a notice (given that the error reporting level covers notices):
echo $undefinedVariable;
$emptyArray = array();
echo $emptyArray['undefined index'];
To tackle this you should test if the variable or array index you want to read actually exists. For variables there is isset and for array indices you can either use isset too or array_key_exists.
you can also prevent a function from throwing an error if you use the '#' symbol, e.g. #function_call();.
do you really want to do "if($_SESSION['logged']='unset')" ? if you want to make an assignment, consider taking out the "if" to make your code more legible. otherwise, you probably wanted to use the equality operator. :-)
Related
EDIT: Thanks for all the helpful answers, I got it solved.
I can't really seem to find an answer to this question, and it's probably really simple.
I was just creating a page for fun where you can guess a number from 1-10. Person 1 enters a secret number, that person 2 will guess. However, I have had a lot of problems storing the $_POST from the secret number.
TL;DR I can't store the information of secretNumber into guessnumber_guessed.php file. For example look in guessnumber_guessed. First part of the if statement, if the inputNumber equals the secretNumber, it should say correct. Problem is, the variblae is undefined, how to a 'transfer the info'?
Hope you guys get my point, help is really appreciated
Here's the code:
guessnumber_welcome:
<form method="post" action="guessnumber.php">
<input type="text" name="secretNumber" placeholder="Type the secret number">
<input type="submit" name="submit" value="Send">
</form>
guessnumber.php:
<form method="post" action="guessnumber_guessed.php">
<input type="text" name="inputNumber" placeholder="Guess the secret number">
<input type="submit" name="submit" value="Guess!">
</form>
<?php
$secretNumber = $_POST["secretNumber"]
?>
guessnumber_guessed.php:
<form method="post" action="">
<input type="text" name="inputNumber" placeholder="Guess the secret number">
<input type="submit" name="submit" value="Guess!">
</form>
<?php
$inputNumber = $_POST["inputNumber"];
if ($inputNumber == $secretNumber) {
echo "<p id=\"correctAnsw\"> CORRECT! </p>";
}
else if ($inputNumber == 2) {
echo "<p id=\"wrongAnsw\">You're very close. Go up a little!</p>";
}
else if ($inputNumber==4) {
echo "<p id=\"wrongAnsw\">You're very close. Go down a little!</p>";
}
else if ($inputNumber > 10) {
echo "<p id=\"wrongAnsw\">The number is you guessed is too high. Stay within the borders!</p>";
}
else if ($inputNumber < 1) {
echo "<p id=\"wrongAnsw\">The number is you guessed is too low. Stay within the borders!</p>";
}
else {
echo "<p id=\"wrongAnsw\">This is not the number. Try a new one!</p>";
}
?>
The sessions will not help. They're user oriented. If the first person is using the page to enter a number and the second person comes after that, in the same session, on the same browser, you can use the sessions mechanism.
If you're trying to make a multi-user "game" and the two persons are with separate browsers, it means you must:
Pair the two persons somewhat (maybe a room mechanism)
Use some kind of server storage or cache (you can even use memcached for in-memory storage) to match the two persons and their answers.
I faced a similar problem trying to pass beetween two scripts some url strings for a "two-step" uploader.
In my opinion there is two solutions, depends on the level of security you want to have:
In guessnumber.php put the $_POST['secretNumber'] value in an input type="hidden"
<input type="hidden" value="<?php echo $_POST['secretNumber']; ?>">
In this way the value will be passed to the second script via POST and will be available in the $_POST array.
This method, is not safe for sensible datas, because everybody who can access the html source simply through the browser devtool can read or modify it!!
The second, and more safe, solution is to use the php session
In guessnumber.php start the php session and save the value in this way:
if ( !session_id() ) {
session_start();
}
$_SESSION['secretNumber'] = $_POST['secretNumber'];
then in guessnumber_guessed.php recover the session and get the value from there
if ( !session_id() ) {
session_start();
}
$secretNumber = $_SESSION['secretNumber'];
I strongly recommend the second solution.
Hope it helps :)
Currently I have the following form:
<form id="new_account_form" action="php/new-account.php" method="post">
<span>name</span>
</br>
<input type="text" name="main_name" required></input>
<br><br>
<span>email adres</span>
</br>
<input type="text" name="main_email" required value="<?php echo $email; ?>" disabled></input>
<br><br>
<span>user</span>
</br>
<input type="text" name="main_username" required value="<?php echo $username; ?>" disabled></input>
<br><br>
</form>
As you can see both the email input field and the username input have PHP values in them that are echoed. The input field aren't empty.
The problem I am facing right now is when I submit the form and try to $_POST the input fields in the other page I keep getting the following error:
Notice: Undefined index: main_email
Notice: Undefined index: main_username
Am I echoing the variables in the wrong place or something?
The new-account.php file contains the following code:
<?php
//get data from form
$main_name = $_POST['main_name'];
$main_email = $_POST['main_email'];
$main_username = $_POST['main_username'];
echo $main_name;
echo "</br>";
echo $main_email;
echo "</br>";
echo $main_username;
echo "</br>";
?>
after a little googling, disabled forms don't post to the action page. replace disabled with readonly and you should be fine.
Replace:
<input type="text" name="main_email" required value="<?php echo $email; ?>" disabled></input>
with:
<input type="text" name="main_email" required value="<?php echo $email; ?>" readonly></input>
The disabled field values of forms are not posted.So always use readonly where you want to post the value as well as want that the value remains unchanged.
Original answer:
The reason why you're getting those notices, is because the variables have not been set in the inputs' values of your form.
I was 50% right and 50% wrong.
(Consult my edit below)
Use a ternary operator
Change: value="<?php echo $email; ?>"
to
value="<?php $email=!empty($_POST['main_email']) ? $_POST['main_email'] : ''; ?>"
or
value="<?php echo !empty($_POST['main_email']) ? $_POST['main_email'] : ''; ?>"
and do the same for the other input.
Use a conditional !empty() for the other inputs in the other file also.
Sidenote: </input> is an invalid closing tag. </br> is also invalid, it should read as <br/>
Edit: - which is now a supplemental answer:
Upon seeing the other answer about disabled I agree on that point and they were right.
However, you will get undefined index notices in your form inputs, since those variables have not yet been set/defined.
View your HTML source (with error reporting enabled) and you will see something similar to the following:
<input type="text" name="main_email" required value="<br />
<b>Notice</b>: Undefined variable: email in <b>/path/to/your/file.php</b> on line <b>xxx</b><br />
" disabled></input>
and a similar notice for the other input.
The notices will appear in the inputs themselves.
Even though the input fields are disabled, PHP will still throw undefined notices for the variables.
Additional edit(s)
You stand at also getting Notice: Undefined variable: email in... and for the username after submission. Least, that's what my test revealed. Again; use a ternary operator for your inputs and it will solve the problem completely.
It is presently unknown as to why you're echoing the values for the inputs. If those are populated from elsewhere (a database, a file, other), either remove the variables, use a ternary operator as I already said, or use "Email" and "Username" as the default values.
Use a ternary operator as shown above.
http://php.net/manual/en/language.operators.comparison.php
Add error reporting to the top of your file(s) which will indicate errors, if any.
<?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.
if(isset($main_email))
{
echo $main_email;
}
you can use isset() function...
http://php.net/manual/en/function.isset.php
I have two pages that i like to exchange variable. in the first page i have form like this:
<form method='post' action='rehabCreate2.php' onsubmit='return validateForm();'>
<input class="textbox" type='text' id='txt_stuNum' name='txt_stuNum'/ required>
<input type="submit" value="NEXT" id="btnNext">
</form>
then i set the session variable like this:
if ( isset( $_POST['btnNext'])){
$stuId=$_POST['txt_stuNum'];
$_SESSION["stuId"]=$stuId;
}
then in my page2 i want to it:
<?php
session_start();
$stuId=$_SESSION["stuId"];
echo $stuId;
?>
but it gives me error:
Notice: Undefined index: stuId in...
what am i missing?
and another thing, how can i make a "back button" and the values are still in there?
EDIT:
originally my "session_start()" was place at the top of the page1, but when i transfer it below my ""
this error message show:
Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\cerecare\portal\somepage.php:176) in C:\xampp\htdocs\cerecare\portal\rehabCreate.php on line 16
by the way: the line 176 of somepage is the end of the script tag and nothing else follows
First replace (give a name attr to submit button to get on POST)
<input class="textbox" type='text' id='txt_stuNum' name='txt_stuNum'/ required>
<input type="submit" value="NEXT" id="btnNext">
to
<input class="textbox" type='text' id='txt_stuNum' name='txt_stuNum' required />
<input type="submit" value="NEXT" id="btnNext" name="btnNext">
Add a session_start() on page1
session_start();
if (isset( $_POST['btnNext'])){
$stuId=$_POST['txt_stuNum'];
$_SESSION["stuId"] = $stuId;
}
Then Add a check for session value exist or not on page2
$stuId=(isset($_SESSION["stuId"]) ? $_SESSION["stuId"] :'');
You forgot to add name for submit button but in addition whenever you are using any variable whether session or local variable just make sure it exists or not. so to save yourself from this problem always use this style of code given by #Rakesh Sharma.
$var = isset($_SESSION['any_var']) ? $_SESSION['any_var'] : '';
or the better way to perform check and reduce calculation mistake use like this
$var = ( isset($_SESSION['any_var']) && !empty($_SESSION['any_var']) ? $_SESSION['any_var'] : '';
In statements also always use this style
if ( isset($_SESSION['any_var']) && !empty($_SESSION['any_var'])){
/// code in statement
}
use this style of code always in your code and fee free at least from undefined index error and some calculation mistakes if value is empty.
I'm building a website in PHP and I'm trying to implement asynchonous behaviour on some occasions, in this case to load an HTML form into an overlay and making it visible. This works as intended, however I'm now testing everything considering existing data.
So I basically created a variables.php file that sets values to the $_SESSION global and was working from there. Everything was working as expected on index.php, but as soon as I click the overlay I notice the values aren't passing through to populate the form that was added.
I already poked google for a few hours to no avail. I've added echo var_dump($_SESSION); on the index.php file and the values are all there. However on the overlay it returns NULL. I've even include_once("loginForm.php") right in the middle of index.php and that gave me the values. So there's something I'm missing in order to get the values to apply to .load() elements.
Here's some code:
variables.php
//added values to the $_SESSION global for testing purposes
$_SESSION['email'] = 'john#john.com';
$_SESSION['password'] = 'johnny';
$_SESSION['name'] = 'John';
$_SESSION['surname'] = 'Smith';
$_SESSION['country'] = 'UK';
$_SESSION['phoneOption'] = 'Mobile';
$_SESSION['phone'] = '987654321';
header-login.php
//this form accepts an email to check ifExists() and decide what's next
//the input #preLoginEmail assumes the value correctly
<form action="header-login.php" name="preLoginForm" id="preLoginForm" method="post">
<div id="login-part2">
<table id="preLoginTable">
<tr>
<td colspan="2">
<input type="text" id="preLoginEmail" title="Email" name="test-email" tabindex="1" size="10" maxlength="60" placeholder="Email" value="'. $email .'" />
</td>
</tr>
<tr>
<td><a title="forgotten password" href="header-login.php" id="preLoginForgot">forgot password?</a></td>
<td><input type="submit" class="btn1" name="preLoginRegisterButton" id="preLoginRegisterButton" tabindex="1" value="Login / Register" /></td>
</tr>
</table>
</div>
echo var_dump($_SESSION);//works
</form>
onClickEvents.js
//this call retrieves the HTML correctly although the variables dont get assigned to the input's value
$( "#preLoginForm" ).submit(function( event ) {
event.preventDefault();
var $form = $( this ),
term = $form.find( "input[name='test-email']" ).val(),
url = $form.attr( "action" );
verifiedEmail = validateEmail(term);
if(verifiedEmail){
// Put the results in a div
$('#olContainer').load("../inc/loginForm.php");
overlayOn();
}
else {
$('.session-stat').css({ "background-color": "#A60000" });
}
});
loginForm.php
//when this form is loaded there are no values in the inputs and var_dump($_SESSION) returns NULL
<form id="loginForm" name="loginForm" method="post" action="booking.php">
//some blocks are static and created in plain html
<input name="email" type="text" class="dDown12" id="agentuser" size="20" maxlength="20" value="<?php echo $email; ?>" />
//others are php variables to make the if/else statement more readable
$countryBlock ='<input name="agentuser" type="text" class="dDown12" id="agentuser" size="20" maxlength="20" value="'. $country .'" />';
echo var_dump($_SESSION); //NULL
I kinda ran out of ways to figure out what's going wrong, and I just started learning about AJAX this week. If u need anything else just let me know in comments I'll try to be quick to edit. Thanks in advance.
#Fernando - I didn't know which way you decided to go, but if you have to use $_SESSION for this, include:
session_start();
at the beginning of each file you plan to use sessions on, before any content is rendered. Also, be careful to have a means for your users to overwrite their values, ie. with a post, so that once a value gets put in session, there is a way to change it and it doesn't keep overwriting the (new) value. I usually clear out my sessions on Page one of the form. You can do a
unset($_SESSION['test-email']);
...to unset the values. You can use a foreach loop here too.
A great site to compare the speed of loops in PHP is http://www.phpbench.com/ also.
Best of luck!
I can't set a variable from a post array.
I have a simple form with a hidden field in it:
<input name="sid" type="hidden" id="sid" value="<?=$sid?>">
This hidden field gets sent off to a second file (exec.php) where I have the following code:
$sid = $_POST['sid'];
For some reason, when trying to set $sid, it gets a NULL value. For haha's, I ran the following:
foreach($_POST as $var => $value)
{
echo $var . ' : ' . $value . "<br>";
}
This provided a correct value of 1938 for sid. I've looked at this for 3 hours and can't find what is happening. I expect something extremely stupid...any thoughts?
Here is the form on enter.php
<form name="form1" method="post" action="exec.php">
<input name="sid" type="hidden" id="sid" value="<? echo($sid); ?>">
<input name="ticket_totals" type="hidden" id="ticket_totals" value="<?=$ticket_totals?>">
<input name="emp" type="hidden" id="emp" value="<?=$emp?>">
<input name="submit" type="submit" id="submit" value="Submit">
<input type="submit" name="submit" id="submit" value="Close">
</form>
Here is the POST output on exec.php:
type : Other
ticket_totals : 0
emp : 105
sid : 1939
submit : Submit
Okay - this was poor syntax on my part but now I'm curious as to why.
I left out quotation marks - the solution is as simple as this:
$sid = $_POST["sid"]
Now it works like a champ.
Any takers on why? I'd guess there is a setting in the php.ini that requires the quotes. Strangely enough, I have other variables called from the POST array that i'm not using quotes for and they're working fine...
Use Console in FireBug to inspect the POST request to see what is the sid value that is being sent.
If the sid value in request is ok, use var_dump($_POST["sid"]); to see the results on the server.
EDIT: it's considered good PHP style to use the quotes when accessing the associative array because quote-less keys are indistinguishable from constants:
define('myVar',3);
echo $array[myVar]; // retrieves $array[3], not $array['myVar'];
Try to echo the $sid instead of the <?=:
// Change that
<input name="sid" type="hidden" id="sid" value="<?=$sid?>">
// With that
<input name="sid" type="hidden" id="sid" value="<?php echo $sid; ?>">
also for the test time try to change the input type from hidden to text in order to be 100% sure the $sid contains a value.
Using quotes for associative array keys is mandatory, and while it may work without them, it's incorrect and erratic behavior is expected.
I had this same problem, trying to use $_POST[sid] as a variable. I'm am thinking that "sid" is a reserved or restricted variable name, because I changed my variable to $_POST[snid] and it worked just fine. This was my code
$sid = $_POST[sid];
$recipient = "($sid) ($_POST[sid])";
if ($_POST[sid] > 0)
{
$recipient = "It Worked";
}
print $recipient;
When I posted "&sid=15", the result was:
() (15)
Unbelievable. Impossible, right? All I did was change from using "sid" as the index to "snid", and it worked no problem.
So, don't ever use $_POST[sid].