Hey everyone ive done my research and i find im still stuck many people said to put # sign before the variable but it does not seem to be working, so my code gives me this error
Notice: Undefined index: 2 in login.php on line 20
my code is
if( isset($_REQUEST['email']) || isset($_REQUEST['pwd']) || $_REQUEST['email'] != "" || $_REQUEST['pwd'] != "" )
{
$inputFile = fopen("members.txt", "r");
$found = false;
$i =0;
//read the read.txt until the end of file
while(!feof($inputFile) && $found == false)
{
$line = fgets($inputFile);
// replace the special charater within the lines by there proper entity code
$lineArray = preg_split("/\,/", (string)$line);
if ($_REQUEST['email'] === $lineArray['2'] && $_REQUEST['pwd'] === $lineArray['4'])
{
session_start();
$found = true;
$useremail=$_REQUEST['email'];
$password= $_REQUEST['pwd'];
//time to set sessions and stuff
$_SESSION['useremail'] = $useremail;
$_SESSION['password'] = $password;
//send the redirect header
header('Location: index.php');
exit();
}
}
fclose($inputFile);
}
so the line its referring to is
if ($_REQUEST['email'] === $lineArray['2'] && $_REQUEST['pwd'] === $lineArray['4'])
ive tried many other variation such as removing single quotes adding # in front of the $lineArray and doing both, can anyone help me out the values are there when i was printing them out but when it get to this if statement it doesn't turn to equal and it give me this error.
if also tried
if ($_REQUEST['email'] === $lineArray[2] && $_REQUEST['pwd'] === $lineArray[4])
and
if ($_REQUEST['email'] === #$lineArray[2] && $_REQUEST['pwd'] === #$lineArray[4])
You need $lineArray[2]. Indices of an array are integers, not strings. And also ensure if that same array has atleast 3 elements.
The line is the problem:
$lineArray = preg_split("/\,/", (string)$line);
It should be (since you seem to be splitting on ,):
$lineArray = preg_split("/,/", (string)$line);
PS: Consider using a simpler $array = explode(",",$yourString)
The error means there is a undefined var being used in your code. In your case, it's talking about $lineArray['2']. This isn't a serious error, so you can be lazy and alter your error settings to get rid of it:
error_reporting(E_ERROR | E_WARNING | E_PARSE);
But you really should just fix it instead.
As Devnate suggested, you need to use a int to specify the index key of the array, instead of a string (so this $lineArray[2] instead of this $lineArray['2']). Why? Because the key you was using before ('2') was never set, which resulted in the error.
You say the comparing fails when you attempt the above. I cannot help you with that until I see the result of print_r($lineArray);.
This is the code from your previous question. It's a shame you didn't take my advice and go with my code. You wouldn't be having this issue if you did. But that's a different matter. Post the print_r($lineArray); so I can see what the problem is with the comparing.
You'll want to use numbers (no quotes) for your array keys, but you'll also need to check that those array values exist with isset() before comparing them.
if (isset($lineArray[2]) && $_REQUEST['email'] === $lineArray[2] ...
Related
So I'm working on a PHP app receiving a student ID from an input and searching through a file to find if the ID is present or not. If it's present, the name of the student and whether hes present or not should be printed out, and if the ID doesn't exist, it should say that there are no students with this ID.
Here is an example of what the txt file looks like:
1234|Sally Simon|1
4321|Larry Lonbottom|0
7364|Hannah Harrow|1
I made a solution and tested it, but it prints out a student name even when the ID I enter is false. Could someone give me an idea of what I'm doing wrong?
Here is my code:
<?php
$student=$_GET["student"];
$lines = file('students.txt');
foreach ($lines as $line){
$var = explode("|", $line);
}
if($student == $var[0] || $var[2] == "1"){
echo "$var[1]($var[0]): has signed up";
}else if($student == $var[0] || $var[2] == "0"){
echo "$var[1]($var[0]): hasn't signed up";
}else{
echo "No students with that id!";
}
?>
1) Your $var will always have the last line in the file, wrap everything with the foreach;
2) You should use && instead of ||
EDIT: updated code
<?php
$student=$_GET["student"];
$lines = file('students.txt');
$missing = true;
foreach ($lines as $line){
$var = explode("|", $line);
if($student == $var[0]){
$missing = false;
if($var[2] == "1"){
echo "$var[1]($var[0]): has signed up";
}else if($var[2] == "0"){
echo "$var[1]($var[0]): hasn't signed up";
}
}
}
if($missing){
echo "No students with that id!";
}
?>
As OPs said you need to change your conditional logic (if elses) and place it within the foreach loop (i.e. before the foreach's closing }.
However: (php.net file) "Each element of the array corresponds to a line in the file, with the newline still attached." so you have to remove the EOL/NL marker (invisible whitespace) from $var[2]. This can be achieved changing your file function to file('students.txt', FILE_IGNORE_NEW_LINES) however it is probably best to use trim as per example below.
It may help simplify things for you if you get rid of else conditions. try this:
<?php
$student=trim($_GET["student"]); // should also check and exit if ! digits
$lines = file('students.txt');
$isRegistered = array( "hasn't signed up", "has signed up");
$invalidID = TRUE;
foreach ($lines as $line){
$var = explode("|", $line);
if( $student == trim($var[0]) ) {
echo "$var[1]($var[0]): " . $isRegistered[ trim($var[2]) ];
$invalidID = FALSE;
break; // prevent unnecessary processing, exit foreach loop
}
}
if ( $invalidID ) echo "No students with that id!";
?>
Note: the above assumes file only contains valid content.
(1) Put the if statements inside the loop since you want to use those conditionals with every line.
(2) You are using logical 'or' operators. This means that only one of the conditions for that line need to be met.
This is what you are saying
if $student == $var[0] OR if $var[2] == 1
So regardless of what ID you enter, you always match the 0 or 1 condition.
Use the && operator instead of || if you need both conditions to be met instead of just one of the two.
(3) By using the == operator, the string will have to match with the value you are looking for exactly. You might have spaces in $student or there might be additional character in between the |. Just to air on the side of caution, remove all chances of there being hidden whitespace with your variables.
Do this: $student[0] = preg_replace('/\s+/', '', $student[0]); and do that with var[0] and var[2] as well. Do this before you run them through the if statements but still inside the loop.
Here is a link that talks about logical operators in php. It might be nice to use as a reference for future conditional statements that you need to build!
This link explains what you are doing to these values with preg_replace. It becomes very handy when you need to remove characters from a string that otherwise might difficult to deal with.
I can't understand that if sentence. Why can't I just check if $view is set? 2 more questions -What does "$_GET("$view")!" "!" sign mean there? What does ! change? Moreover, why does it equal = " "?
<?php
$myurl=htmlspecialchars($_SERVER["PHP_SELF"]);
$view="";
if(isset($_GET["$view"]) && $_GET("$view")! = "") { $view =$_GET["$view"];};
include(head.html);
switch($view] {
case "" :
include(main.html);
break;
case "people" :
include(people.html);
break;
case:"contact":
include(contact.html);
break;
default :
include(404.html);
break;
};
include_once(foot.html;
?>
Thanks for all the help
I think you messed up your code. This will not execute, due to numerous errors. The if statement is probably
if(isset($_GET[$view]) && $_GET[$view] != "")
Ie, first check that the $view key exists, then check that key it is not empty. Note the difference between a key that does not exist, and a key that exist but is empty, and why you check for both in this case.
Why can't I just check if $view is set?
Because apparently the author of that code didn't want the empty string to be valid. This will be the case if, say, there is a field called $view and the user does not put anything in it.
Actually, you could do that, since $view is initialized to the empty string anyway! This code was probably copy/pasted or written by a novice.
What does ! change?
It's actually !=, written in a confusing way. These two are the same:
&& $_GET("$view")! = "")
&& $_GET("$view") != "")
Also, your code has a bug. $_GET("$view") is not valid, the () should be []. So, here is the corrected and readable code:
if (isset($_GET["$view"]) && $_GET["$view"] != "") {
$view = $_GET["$view"];
}
Also:
switch($view] // ...what is this?
include_once(foot.html; // and this?
case:"contact": // ummmm
$view="";
if(isset($_GET["$view"]) && $_GET("$view")! = "") { $view =$_GET["$view"];};
You actually set $view=""; as an empty parameter
There for isset($_GET["$view"] looks like this isset($_GET[""]
You whole if statement with the above code is ignored
Likewise your switch($view); also looks like switch("")
This means only your first case will be executed no matter what you have in your $_GET
Check this portion of your code too for errors. the colon after case needs to be removed
case:"contact":
include(contact.html);
break;
For first, use correctly [] and (). Then you have to learn about operators: http://www.w3schools.com/php/php_operators.asp
For now your code is non-sense.
I'm trying to match a condition where if the user status is 10 and ANY POST variables are not set it triggers an error:
if ($_SESSION['status']=='10' && !isset($_POST['a']) || !isset($_POST['B'])) {}
I can not use && conditions for any !isset as one variable may be set though another might not. I only want the condition to match if one or more variables are not set AND the status==10.
When testing if a $_POST variable !isset, I remove an input element from the page via a browser web tool (e.g. Firebug). When the form is submitted with the variable missing it's still passing validation incorrectly.
I am also seeking a PHP if grouping condition.
If you are looking for absolutely any PHP variables, I'd recommend this:
if (($_SESSION['status'] == 10) && (count($_POST) > 0)) {
You can then get the list of _POST var keys using array_keys($_POST).
If you are looking for a specific:
if (($_SESSION['status'] == 10) && (isset($_POST['A']) || isset($_POST['b']))) {
The order of the brackets is important. You can separate groups of logical statements with brackets.
Is that was what you were looking for?
$status = $_SESSION['status'];
if($status == '10'){
if(!isset($_POST['a']) or !isset($_POST['B'])){
//Triggers error.
}else{
//Another
}
}
Try making it a function:
function checkAllVars($dataVars, $requestVars) {
foreach($dataVars as $varname) {
if(!isset($requestVars[$varname])) {
return false;
}
}
return true;
}
$dataVars = array (
"varName1",
"varName2",
"varName3",
"varName4",
);
$allVarsSet = checkAllVars($dataVars, $_REQUEST);
you might be looking for
if($_SESSION['status']=='10' && (!isset($_POST['a']) || !isset($_POST['B']))){}
^ ^
which means if status = 10 and (if not set 'a' or not set 'B' or they can be both not set) do something
or you might be looking for
if(($_SESSION['status']=='10' && !isset($_POST['a'])) || ($_SESSION['status']=='10' && !isset($_POST['B']))){}
Below is a snippet of PHP that I need to get working, I need to make sure that 3 items are not set already and not === ''
I have the part to make it check if not set but when I try to see if the values are empty as well (I might not even be thinking clearly right now, I might not need to do all this) But I need to make sure that redirect, login_name, and password are all not already set to a value, if they are set to a value I need to make sure that the value is not empty.
Can someone help, when I add in check to see if values are empty, I get errors with my syntax, also not sure if I should have 5-6 checks like this in 1 if/else block like that, please help
I need to check the following:
- $_GET['redirect'] is not set
- $_REQUEST['login_name'] is not set
- $_REQUEST['login_name'] is not != to ''
- $_REQUEST['password'] is not set
- $_REQUEST['password'] is not != to ''
if (!isset($_GET['redirect']) && (!isset($_REQUEST['login_name'])) && (!isset($_REQUEST['password']))){
//do stuff
}
UPDATE
Sorry It is not very clear, I was a bit confused about this. Based on Hobodaves answer, I was able to modify it and get it working how I need it. Below is the code how I need it, it works great like this... So if that can be improved then that is the functionality that I need, I just tested this.
if (!isset($_GET['redirect'])
&& empty($_GET['redirect'])
&& isset($_REQUEST['login_name'])
&& !empty($_REQUEST['login_name'])
&& isset($_REQUEST['password'])
&& !empty($_REQUEST['password'])
) {
echo 'load user';
}
if this was loaded then it will run the login process
login.php?login_name=test&password=testing
If this is loaded then it will NOT run the login process
login.php?login_name=test&password=
if (!isset($_GET['redirect'])
&& !isset($_REQUEST['login_name'])
&& empty($_REQUEST['login_name'])
&& !isset($_REQUEST['password'])
&& empty($_REQUEST['password'])
) {
// do stuff
}
This is exactly what you describe, (not != empty === empty). I think you should edit your question though to explain what you're triyng to do, so we can suggest better alternatives.
Edit:
Your updated question can be simplified as:
if (empty($_GET['redirect'])
&& !empty($_REQUEST['login_name'])
&& !empty($_REQUEST['password'])
} {
// load user
}
A more maintainable solution would be storing each key in an array, and then foreach over it and check if isset or empty. You're not very DRY with your current solution.
The implementation would look someting like:
<?php
$keys = array('login_name', 'password');
foreach($keys as $key)
{
if(!isset($_REQUEST[$key]) || empty($_REQUEST['key'])
// Show error message, kill script etc.
}
// Dot stuff
?>
If a global variable is not set, that is the same as being empty. Thus:
!is_set(($_REQUEST['username'])) is the same as empty($_REQUEST['username'])
So based on your update, you can simplify to:
if (empty($_GET['redirect'])
&& !empty($_REQUEST['login_name'])
&& !empty($_REQUEST['password'])
) {
echo 'load user';
}
please read!
Sorry, the previous answer I gave will not give you what you want. Here is why:
If you use !_REQUEST['password'], it will return true if the password is empty or if it is not set. However if you use if($_REQUEST['password']) it will pass the conditional anytime that global variable is set, even if it is empty.
Therefore I recommend:
$no_redirect = (!$_GET['redirect']);
$login_name = (!$_REQUEST['login_name']) ? false : true;
$password = (!$_REQUEST['login_name']) ? false : true;
if($no_redirect && $login_name && $password) {
echo 'load user';
}
Sorry for the previously bad info.
You could create an array
$array = array(
$_GET['redirect'],
$_GET['redirect'],
$_REQUEST['login_name'],
$_REQUEST['login_name'],
$_REQUEST['password'],
$_REQUEST['password']
);
foreach($array as $stuf)
{
if(!empty($stuff) && $tuff !=0)
//do something
}
I am getting this error: "Fatal error: Can't use function return value in write context in D:\Programas\wamp\www\away\index.php on line 18". Line 18 being the if statement.
Can anyone help me out on this? Thanks.
$vars = array("first_date_month", "first_date_day", "last_date_month", "last_date_day", "resume_date_month", "resume_date_day", "pay_date_month", "pay_date_day", "pay_time_hour", "pay_time_minutes");
$err_flag = false;
$i = 0;
while ($i < count($vars) and $err_flag == false)
{
if ( (!isset($_GET($vars[$i])) or ($_GET[$vars[$i] == "0") )
$err_flag = true;
$i++;
}
Maybe I'm not seeing well, but:
if ( (!isset($_GET($vars[$i])) or ($_GET[$vars[$i] == "0") )
You got a really awful mixup of parenthesis and square brackets. There's no such thing as
$_GET()
Big typo you have to correct.
Your code is a mess.
$_GET is an associative array and not a function (you are using the function call syntax passing $vars[$i] as an argument). In the second $_GET there's one ] missing.
Line 18 should be:
if ( (!isset($_GET[$vars[$i]]) or ($_GET[$vars[$i]] == "0") )
My take at it:
$vars = array("first_date_month", "first_date_day", "last_date_month", "last_date_day", "resume_date_month", "resume_date_day", "pay_date_month", "pay_date_day", "pay_time_hour", "pay_time_minutes");
foreach ($vars as $var) {
if ($err_flag = empty($_GET[$var]))
break;
}
8)
I assume the marked answer has... well.. answered the problems in your code, so just throwing out some optimizations:
using foreach() instead of while/for
is simple in many cases where we are
just iterating over an array - we can get the value and also the key if needed.
using the empty() function (returns true for anything null, false, 0, "", "0")
exit the loop when you're done using break
$_GET is a variable, an array -- and not a function.
It means you have to use array-access, with [], to get the data it contains.
So :
$_GET[$vars[$i]]
instead of
$_GET($vars[$i])
for the first time you are using $_GET.
And, for the second time, you forgot to close one ] ; which means you need to use :
$_GET[$vars[$i]]
instead of
$_GET[$vars[$i]
In the end, you while-loop should look like this :
while ($i < count($vars) and $err_flag == false)
{
if ( !isset($_GET[$vars[$i]]) or $_GET[$vars[$i]] == "0" ) {
$err_flag = true;
}
$i++;
}
Note I also added {} arround the body of the if condition ; this way, if you ever have to add something, you won't risk forgetting those ;-)
Change your line 18 if... to:
if ( (!isset($vars[$i])) or ($vars[$i] == "0") )
$err_flag = true;
$i++;
This mainly because I -and this is purely personal, I suspect- don't like using the $_GET[...] throughout the script; assign:
$variable_from_GET[] = $_GET['variable_name'];
and then use the $variable_from_GET array variable in your conditions which you -I presume- you did since you had a $vars array.