Variable either not getting passed to or from the function - php

The point of the code is to edit a specific user which is determinded by which edit button has been pressed.
I'm getting the following error:
Undefined variable: user_id in EditUser.php on line 15.
No this in not an undefined variable issue. If I remove $user_id when calling the function it complains that the function calling has no arguments.
I only want the return of the function, but it doesn't want to get called.
EditUser.php:
<?php
session_start();
include_once 'Functions.php';
$user = new User();
?>
<html>
<head>
<title></title>
</head>
<body>
<?php
if (isset($_SESSION['EditUser']))
{
$result = User::Edit_User($user_id); //The line which gives me the error
while(list($user_id, $username, $password, $emailadres, $admin) = mysql_fetch_array($result ))
{
$urid = $user_id;
$urnm = $username;
$pw = $password;
$eml = $emailadres;
$an = $admin;
echo "It worked"; //Just aline for debugging. Will remove later
}
}
else
{
echo "error";
}
?>
<form method="post" action="EditUserDef.php">
user_id: </br>
<input readonly="readonly" name="user_id" value=<?php echo $urid ?>></br>
username: </br>
<input type="input" name="username" value=<?php echo $urnm ?>></br>
password: </br>
<input type="input" name="password" value=<?php echo $pw ?>></br>
emailadres: </br>
<input type="input" name="emailadres" value=<?php echo $eml ?>></br>
admin: </br>
<input type="input" name="admin" value=<?php echo $an ?>></br>
<input type="submit" name = "submit" value="edit data">
<input type="button" value="back" onClick="history.go(-1);return true;"></br>
</br>
</form>
</body>
</html>
The file with the class and funcitons, Functions.php:
<?php
include_once 'Config.php'; //Class to connect with database, not really important for this question
class User
{
public function Edit_User($user_id)
{
$query = mysql_query("SELECT * FROM useraccounts WHERE user_id = '$user_id'");
$rows = mysql_num_rows($query);
if (!$rows == 0)
{
$_SESSION['EditUser'] = true;
return $query;
}
}
public function Edit_DataSession()
{
return (isset($_SESSION['EditUser']));
}
And as last, the file from where the "user_id" gets send to Functions.php, Administration.php:
<?php
session_start();
include_once 'Functions.php';
$user= new User();
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$user_id = $_POST['hidden'];
$editing = $user->Edit_User($user_id);
if ($editing)
{
header("location:EditUser.php");
}
else
{
echo 'User doesn't exist anymore';
}
}
?>
<html>
<header>
<style>
table, td, th
{
border-style: solid;
border-width: 3px;
border-color: black;
}
</style>
</header>
<body>
<h1>overzicht gebruikers</h1>
<table border = 1>
<tr>
<td>user_id</td>
<td>username</td>
<td>password</td>
<td>emailadres</td>
<td>admin</td>
</tr>
<?php
if (isset($_SESSION['GetUser'])) //function not included in the code of the question, didn't seem necesarry
{
$result = user::get_user();
while(list($user_id, $username, $password, $emailadres, $admin) = mysql_fetch_array($resultaat))
{
echo "<tr><td>$user_id</td>";
echo "<td>$username</td>";
echo "<td>$password</td>";
echo "<td>$emailadres</td>";
echo "<td>$admin</td>";
echo "<td><form action='EditUser.php' method='post'><input type='hidden' name='hidden' value=$user_id><input type='submit' name='edit' value='edit'></form></td>";
echo "<td><form action='DeleteUser.php' method='post'><input type='hidden' name='hidden' value=$user_id><input type='submit' name='delete' value='delete'></form></td></tr>";
}
}
?>
</body>
</html>
Does anyone know how to fix this?

No this in not an undefined variable issue.
Um, yes it is. Error messages are pretty good at telling you the error:
Undefined variable: user_id in EditUser.php on line 15
So let's look at line 15:
$result = User::Edit_User($user_id);
You're trying to use a variable called $user_id. Looking above that line, I don't see that variable defined anywhere. You define a variable called $user:
$user = new User();
But where do you define a variable called $user_id? According to your code, and according to the PHP runtime, you don't. Hence the error.
You do define a similarly named variable on a completely different page, but variables don't persist across page contexts. You need to re-define it with each page request where you want to use it.
You need to define variables before you can use them. Maybe you meant to use a member of $user instead of $user_id? Maybe you meant to use $user itself? The code isn't going to be able to know what you mean, you have to explicitly define things.

Related

PHP Insert into MySQL Database doesn't work

I'm trying to input data into MySQL Database. I can log into database. However, whenever I run, the error "Error Querying Database 2" keeps appearing.
I'm suspecting my SQL Query having problems. However, I have checked my SQL query several times but I can't find any errors. (not yet)
Any help is appreciated!
<!DOCTYPE HTML>
<html>
<head>
<title>Create Events</title>
<link rel="stylesheet" href="RegisterLogin.css">
</head>
<?php
session_start();
if (isset($_SESSION['Username'])) {
$Username=$_SESSION['Username'];
}
?>
<body>
<?php
//define variables and set to empty values
$EventNameErr = $MembersAttending_Err = $EventDateErr = $LocationErr = $websiteErr = "";
$EventName = $MembersAttending = $EventDate = $Location = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["EventName"])) {
$EventNameErr = "A name for the event is required";
} else {
$EventName = test_input($_POST["EventName"]);
}
if (empty($_POST["MembersAttending"])) {
$MembersAttendingErr = "How many members are attending";
} else {
$MembersAttending = test_input($_POST["MembersAttending"]);
}
if (empty($_POST["EventDate"])) {
$EventDateErr = "The date of the event is required";
} else {
$EventDate = test_input($_POST["EventDate"]);
}
if (empty($_POST["Location"])) {
$LocationErr = "Location of the event is required";
} else {
$Location = test_input($_POST["Location"]);
}
//continues to target page if all validation is passed
if ( $EventNameErr ==""&& $MembersAttendingErr ==""&& $EventDateErr ==""&& $LocationErr == ""){
// check if exists in database
$dbc=mysqli_connect('localhost','testuser','password','Project')
or die("Could not Connect!\n");
$sql="SELECT * from Events WHERE EventName ='$EventName';";
$result =mysqli_Query($dbc,$sql) or die (" Error querying database 1");
$a=mysqli_num_rows($result);
if ($a>0){
$EventNameErr="Event Name already exists".$a;
} else {
$sql1="INSERT INTO Events VALUES(NULL,'$EventName','$MembersAttending','$EventDate','$Location');";
$result =mysqli_Query($dbc,$sql1) or die (" Error querying database 2");
mysqli_close();
header('Location: /EventCreated.php');
}
}
}
// clears spaces etc to prep data for testing
function test_input($data){
$data=trim ($data); // gets rid of extra spaces befor and after
$data=stripslashes($data); //gets rid of any slashes
$data=htmlspecialchars($data); //converts any symbols usch as < and > to special characters
return $data;
}
?>
<h2 style="color:yellow" align="center"> Event Creation </h2>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" align="center" style="color:#40ff00">
EventName:
<input type="text" name="EventName" value="<?php echo $EventName;?>"/>
<span class="error">* <?php echo $EventNameErr;?></span>
<br/><br/>
Members:
<input type="text" name="MembersAttending" value="<?php echo $MembersAttending;?>"/>
<span class="error">* <?php echo $MembersAttendingErr;?></span>
<br/><br/>
Date:
<input type="text" name="EventDate" value="<?php echo $EventDate;?>"/>
<span class="error">* <?php echo $EventDateErr;?></span>
<br/><br/>
Location:
<input type="text" name="Location" value="<?php echo $Location;?>"/>
<span class="error">* <?php echo $LocationErr;?></span>
<br/><br/>
<input type="Reset" name="Reset" value="Reset">
<input type="submit" name="submit" value="Submit"/> 
</form>
</body>
</html>
I'm not sure what are the column name available in your table, but try with the following query,
I got the column name form your code, I'm not sure it's right or wrong. just try it.
$sql1="INSERT INTO Events (EventName,MembersAttending,EventDate,Location)
VALUES('$EventName','$MembersAttending','$EventDate','$Location');";

PHP writing variables and string to text file

I'm trying to write to file like this:
<?php
date_default_timezone_set('Europe/Budapest');
if(isset($_POST['user'])) {
global $user;
$user = $_POST['user'];
} else {
die("Nincs user beállítva!");
}
if(isset($_POST['pass'])) {
global $pass;
$pass = $_POST['pass'];
} else {
die("Nincs pass beállítva!");
}
if(!isset($_POST['msg'])) {
die("Nincs üzenet!");
} else {
global $msg;
$msg = $_POST['msg'];
}
if(!file_exists("logfile.txt")) {
die("Nem létezik a logfile.txt!");
}
$cont = file_get_contents("logfile.txt");
file_put_contents("logfile.txt","{$user}: {$msg}\n{$cont}"); //<-- Tried this one so many ways
?>
And it gives me this in the txt file:
<? global $user; echo $user; ?>: test
No matter what i change in the file_put_contents, it always give something similar to this.
Thanks for the help in advance.
EDIT: I made the edit that #Barmar suggested, but it is still doing the same thing:
<form name="send" action="chat_send.php" method="post">
<input type="text" name="msg" autocomplete="off" value="">
<?php
global $user;
echo '<input type="hidden" name="user" value="' . $user . '">';
...
</form>
There's nothing wrong with how you're writing to the file. The problem is most likely with how you're setting $_POST['user']. It looks to me like the script that created the form did something like:
echo '<input type="hidden" name="user" value="<?php global $user; echo $user; ?>">';
You can't use <?php ... ?> in the middle of a string to execute PHP code;
That's used when you're outputing normal HTML after ?>, to get back into PHP execution mode temporarily. So your form just contains the literal string ?php global $user; echo $user; ?> in the hidden input value.
In a string, you use concatenation, so it should be:
global $user;
echo '<input type="hidden" name="user" value="' . $user . '">';
Or you can return to HTML mode first:
?>
<form name="send" action="chat_send.php" method="post">
<input type="text" name="msg" autocomplete="off" value="">
<input type="hidden" name="user" value="<?php global $user; echo $user; ?>">
...
</form>
<?php

csrf Token class

can someone explain me how to protect the profile page from the wrong user editing the URL to see some other users profile page. i am using a token class to generate a random number to protect against Cross Site Request Forgery. for some reason it doesn't work any suggestion or other way to do that
Also i get the following error : Undefined index: token in PhpProject22_CSRF\profile.php on line 12
<?php
session_start();
require_once 'Classes/Token.php';
$tk = new Token();
if(isset($_POST['username'],$_POST['product'],$_POST['token'])){
$username = $_POST['username'];
$product = $_POST['product'];
if(!empty($product) && !empty($username)){
if(Token::check($_POST['token'])){
echo $_POST['token'].'<br>';
$tk->get('username');
$_SESSION['user'] = $tk->name();
echo 'Process Order';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CSRF Protection</title>
</head>
<body>
<form action="" method="POST">
<div class="product">
<strong>Profile</strong>
<div class='field'>
Username: <input type='text' name='username'>
</div>
<input type='submit' value='Order'>
<input type='hidden' name='product' value='1'>
<input type='hidden' name='token' value='<?php echo Token::generate();?>'>
</div>
</form>
<?php
if(isset($_POST['username'])){
?>
<p>Hello <a href = 'profile.php?user=<?php echo $tk->name();?>'><?php echo $tk- >name();?></a>!</p>
<?php
}
?>
</body>
</html>
<?php
class Token{
private $_data;
public static function generate(){
return $_SESSION['token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
public static function check($token){
if(isset($_SESSION['token']) && $token === $_SESSION['token']){
unset($_SESSION['token']);
return true;
}
return false;
}
public function get($item){
if(isset($_POST[$item])){
$this->_data = $_POST[$item];
}
}
public function name(){
return $this->_data;
}
}
?>
<?php
require_once 'Classes/Token.php';
session_start();
?>
<form action="" method="POST">
<input type='hidden' name='token' value='<?php echo Token::generate();?>'>
</form>
<?php
echo 'Hello '.$_SESSION['user'].'!<br>';
if(isset($_GET['user'])){
if(Token::check($_POST['token'])){
echo $_GET['user'];
}
}
?>
When checking post you need to do the following:
if($_POST){
if(isset($_POST['token']) && Token::check($_POST['token']){
code
}else{
error
}
}
If someone spoof the post, and doesn't include the token, you're going to get an undefined index error, because $_POST['token'] doesn't exist and you are referencing it.

Form validation using PHP and showing entered username in place hiding form input field

I want to validate username and password using php and then to show username in place of hiding the whole div field set, with in the same page.
I have taken form input fields inside field set and this all inside a div.
PHP:
<?php //------------------------------------------------------------------------------>PHP VALIDATION
$user="";
$pass="";
$nameErr="";
$passErr="";`enter code here`
//$pattern='/^[a-zA-Z0-9#_ ]*$/';
if($_SERVER['REQUEST_METHOD']=='POST')
{
if(empty($_POST['uname']))
{
$nameErr='Enter Your Name!';
}
else
{
$user = test_input($_POST['uname']);
if(!preg_match('/^[a-zA-Z0-9#_]*$/',$user))
{
$nameErr=' Re-Enter Your Name! Format Inccorrect!( only alpha, numbers,#_ are allowed)';
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
HTML:
<div class='input'>
<fieldset>
<?php echo $user;?>
<form method='post' name='f1' action='<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>'>
<table>
<tr>
<td>
User Name:<input type='text' id='uname' name='uname' class='uname' placeholder='USERNAME' autocomplete='off' autofocus><span class='error'>*</span>
Password:<input type='password' id='pass' class='pass' placeholder='PASSWORD' autocomplete='off'><input type='submit' name='submit' id='loggin' value='LOGIN' class='login'>
</td>
</tr>
</table>
</form>
</fieldset>
<div class='errormsg' id='errmsg'><?php echo $nameErr;?></div>
</div>
It's a fairly easy construction. You'll need a form, a session (or some other container for the username) and some logic. See the sample code below. I think you can figure out the rest for yourself:
<?php
session_start();
if(isset($_POST['btn_Login'])) {
// validation code;
// if validation succeeded:
$_SESSION['LoggedIn'] = $_POST['Username'];
}
if(isset($_SESSION['LoggedIn'])) {
echo 'Welcome ' . $_SESSION['LoggedIn'];
?>
// display contents when logged in
<?php
} else {
?>
// display form (where the field for the username is named 'Username' and the submitbutton is named 'btn_Login')
<?php
}

Pass variable from one script to another on same page?

All,
I've been struggling with this and I don't know exactly what I'm doing wrong. I have a PHP file that has multiple scripts in it, including PHP and jquery sections. I'm trying to pass a PHP variable from the html Head section to the Body. Each are each in their own php script section because I have a jquery script in between, also in the Head. Below is the relevant code. How do I pass the $reset_question php variable from the top section to the bottom section?
I just added the button "submit 3" to bring up the form I'm having problems with. Maybe something in my syntax?
<head>
<?php
require_once('../connectvars.php');
session_start();
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Clear the error message
$error_msg = "";
// other code that I'm not having a problem with
if (!isset($_SESSION['email'])) {
if (isset($_POST['submit3'])) {
// Grab the user-entered log-in data
$email = mysqli_real_escape_string($dbc, trim($_POST['email']));
$first_name = mysqli_real_escape_string($dbc, trim($_POST['first_name']));
$last_name = mysqli_real_escape_string($dbc, trim($_POST['last_name']));
if (!empty($first_name) && !empty($last_name) && !empty($email) ) {
// Make sure someone isn't already registered using this username
$query = "SELECT * FROM user_database WHERE email = '$email' AND first_name = '$first_name' AND last_name = '$last_name'";
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 1) {
// The username exists
$query = "SELECT reset_question FROM user_database where email='$email'";
mysqli_query($dbc, $query);
// Confirm success with the user
while($row = mysqli_fetch_array($data)) {
$reset_question = $row['reset_question'];
}
exit();
}
else {
// An account doesn't exist for this e-mail
echo '<p class="error">All of your information was not recognized. Please complete the information correctly or sign-up to register.</p>';
$email = "";
}
}
else {
echo '<p class="error">You must enter all of the required data.</p>';
}
$_SESSION['reset_question'] = $reset_question;
}
}
// Insert the page header
require_once('../reference/header_sub.php');
// If the session var is empty, show any error message and the log-in form; otherwise confirm the log-in
if (empty($_SESSION['email'])) {
echo '<p class="error">' . $error_msg . '</p>';
// closing bracket is down below
?>
// other code that I'm not having a problem with
//jquery script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script>
// jquery isn't having any issues that I can see
</script>
</head>
<body>
<div id="allcontent" style="position:relative;top:-20px;">
<?php
// Insert the tabbed navigation
require_once('../reference/tabs_sub.php');
?>
<br />
<fieldset>
<!-- html forms that I've not having problems with -->
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table class="reset">
<tr><td colspan="2" ><legend style="font-weight:bold;font-size:15px;height:25px;">Reset your password</legend></td></tr>
<tr><td class="register" ><label for="first_name">First Name:</label></td>
<td><input style="width:200px;" type="text" name="first_name" value="<?php if (!empty($first_name)) echo $first_name; ?>" /><br /></td></tr>
<tr><td class="register" ><label for="last_name">Last Name:</label></td>
<td><input style="width:200px;" type="text" name="last_name" value="<?php if (!empty($last_name)) echo $last_name; ?>" /><br /></td></tr>
<tr><td class="register" ><label for="email">E-mail:</label></td>
<td><input style="width:200px;" type="text" name="email" value="<?php if (!empty($email)) echo $email; ?>" /><br /></td><td><input type="submit" value="Submit" name="submit3" class="submit3"/></td></tr>
</table>
</form>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<table class="answer">
<tr><td colspan="2" class="remember" >Please answer the following question!</td></tr>
<tr><td class="remember" >What is: <?php $_SESSION['reset_question']; ?>?</td></tr>
<tr><td ><input style="width:200px;" type="text" name="reset_answer" value="<?php if (!empty($reset_answer)) echo $reset_answer; ?>"/></td></tr>
</table>
</form>
</fieldset>
<?php
} // closing bracket from above opening bracket
else {
// Confirm the successful log-in
echo('<p class="login">You are logged in as ' . $_SESSION['email'] . '.</p>');
require_once('/download.php');
}
?>
<?php
// Insert the page footer
require_once('../reference/footer.php');
mysqli_close($dbc);
?>
</div>
</body>
it looks like your variable $reset_question only exists in the scope of the while loop
while($row = mysqli_fetch_array($data)) {
$reset_question = $row['reset_question'];
//....
}
Instead initialize the variable outside of the while loop.
$reset_question = '';
while($row = mysqli_fetch_array($data)) {
$reset_question = $row['reset_question'];
//....
}
Declare your variable out of any brackets. Just in php script scope and you will get it anywhere down in file, nothing else is needed to pass (access) it in lower script.
Best place to declare/initialize it is before
$reset_question = 'Defaut Question';
if (!empty($first_name) && !empty($last_name) && !empty($email) )
{
If you do not get anything in $reset_question in your conditions then you will get 'Defaut Question'
Upadte : One more try and i am sure you will get at least "What is Defaut Question?"
write $reset_question = 'Defaut Question'; just after $error_msg = ""; as
$error_msg = "";
$reset_question = 'Defaut Question';

Categories