I am trying to create a page to allow users to edit their details using PHP, which validates the content before being submitted.
I want to allow users to update their username, first and second name and email address.
The validation consists of:
<?php
if(preg_match("/^[0-9a-zA-Z_]{3,}$/", $_POST["username"]) == 0)
$error_username = '<li>Usernames may contain only digits, upper and lower case letters and underscores</li>';
if(preg_match("/^[A-Za-z]+$/", $_POST["fname"]) == 0)
$error_fname = '<li>First Name may contain upper and lower case letters</li>';
if(preg_match("/^[A-Za-z]+$/", $_POST["sname"]) == 0)
$error_sname = '<li>Second Name may contain upper and lower case letters</li>';
if(preg_match("/^[a-zA-Z]\w+(\.\w+)*\#\w+(\.[0-9a-zA-Z]+)*\.[a-zA-Z]{2,4}$/", $_POST["email"]) == 0)
$error_email = '<li>Email Addresses must have a valid email address format</li>';
else header("Location: edit.php");
?>
And to display the errors:
<ul>
<?php if(isset($error_username)) echo $error_username; ?>
<?php if(isset($error_fname)) echo $error_fname; ?>
<?php if(isset($error_sname)) echo $error_sname; ?>
<?php if(isset($error_email)) echo $error_email; ?>
</ul>
The form that I have is:
<form name="edit_account" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input class="form_field" name="username" type="text" value="<?php echo $_POST["username"]; ?>" placeholder="Username">
<input class="form_field" name="fname" type="text" value="<?php echo $_POST["fname"]; ?>" placeholder="First Name">
<input class="form_field" name="sname" type="text" value="<?php echo $_POST["sname"]; ?>" placeholder="Second Name">
<input class="form_field" name="email" type="text" value="<?php echo $_POST["email"]; ?>" placeholder="Email Address">
<input type="submit" name="Submit" value="Update Account">
</form>
Providing that all requirements of the validation are met, the user is taken to edit.php and then redirected to a success page:
<?php
$sql = $mysqli;
$id = htmlentities($_SESSION['user_id']);
$username = $sql->real_escape_string($_POST['username']);
$fname = $sql->real_escape_string($_POST['fname']);
$sname = $sql->real_escape_string($_POST['sname']);
$email = $sql->real_escape_string($_POST['email']);
$query = ("
UPDATE users
SET
username='$username',
fname='$fname',
sname='$sname',
email='$email'
WHERE id='$id'") ;
$sql->query($query) or die($query.'<br />'.$sql->error);
header ('Location: success.php');
?>
When I attempt to run this code, the updating fields are submitted into the database as blanks - However, without the validation, the users submitted details are successfully entered.
Can someone please point out what is causing the form to submit as a blank. Thanks.
It looks like you are redirecting to edit.php (which contains database insertion code) from the validation script. The issue is that the $_POST variable is reset when you redirect.
I would include('path/to/edit.php') the edit.php script rather than redirect to it. If that isn't possible, I would save the $_POST data in a $_SESSION variable.
Hope this helps
You're posting them to the validation page, but losing them when you redirect to the edit.php page. Store the information in session variables before going to edit.php, like this:
$_SESSION['username'] = $_POST["username"];
// other variables also
On the edit.php, instead of pulling from $_POST, pull from $_SESSION.
Side Notes
Don't forget session_start() at the top of each page. Also, you should look into prepared statements when using user input.
Related
I need to pass the sessions user name (that they have logged in with) which is an email! I need to pass this to a separate page and output it in a table to represent a review submitted
$_SESSION['name'] = $_POST['name']; - sends page to login in when refreshed
$name = ['name'] - sends page back to login
<!-- logged in user information -->
<?php if (isset($_SESSION['email'])) : ?>
<p>Welcome you are logged in as: <strong><?php echo $_SESSION['email']; ?></strong></p>
the 'email' needs passing across from the code above 'index.php' to the code below 'reviews.php'
<p>
<input name="product_id" value="<?php echo "$var" ?>" readonly> <!-- get value from previous page-->
<input name="track_name" value="<?php echo "$var_value" ?>" readonly> <!-- get value from previous page-->
<input name="track_name" value="<?php echo "EMAIL_HERE" ?>" readonly> <!-- get value from previous page-->
<!-- get value from previous page-->
<input type="Submit" name="Submit" value="Submit"></p>
As this is an assignment I can only use PHP MYSQL HTML CSS
I would like the user name (email) to be echo out in a table as $var and $var_value is, they should then all print out beside each other in a form
UPDATE
using this code I have managed to now get the variable value across but cannot insert it to the DB
$email = $_SESSION['email'];
$sql = "INSERT INTO reviews (rating, review, track_name, product_id, email) values('$rate', '$text', '$track', '$artist', '$email')";
``" readonly>```
so the update is how can I now get this inserted to my database?
did you try to use $_SESSION['email'] variable in reviews.php page?
I hope that u are using CSRF tokens too
FINALLY THANK YOU FOR YOUR HELP ALL
$email = $_SESSION['email']; Get the email from session
$email = (isset($_POST['email']) ? $_POST['email'] : null); Remove index error
<input name="email" value="<?php echo "$email" ?>" readonly> <!-- get value from previous page--> Display the value
$review_query = mysqli_query($result,"SELECT rating, review, email FROM reviews WHERE track_name = '$var_value' AND product_id = '$var'"); Grab it from the DB
<td class='col-4 col-s-4' name='email'><?php echo $email ?></td> Output its value
I have two pages page one and page_two, in page_one the user enter some information which will be inserted in the database and when the he press enter he should be directed to page_two and inside this page there are the same information that he entered in page_one. and the problem is every time the user refresh page_two the data is inserted in the database again. I tried to fix this issue by using header to a new page, it worked but in page_two the information that was entered in page_one is lost.
page_one
<form action="page_one.php" method="post" name="info" >
<input name="userName" type="text" />
<input name="userEmail" type="text" />
<input name="userPass" type="text" />
<input name="submit" type="submit" />
</form>
<?php
include('db.php');
if(isset($_POST['Login']))
{
$user_name = $_POST['userName'];
$user_email = $_POST['userEmail'];
$password = $_POST['userPass'];
mysql_query("INSERT INTO users VALUES ('$user_name',' $user_email',' $password')");
header("Location:page_two.php.php");
exit;
}
?>
page_two
<?php
$user_name = $_POST['userName'];
$user_email = $_POST['userEmail'];
$password = $_POST['userPass'];
echo 'your user name: '.$user_name;
echo 'your email: '.$user_email;
echo 'your password: '.$password;
<input name="userName" type="hidden" value="<?php echo $user_name; ?>" />
<input name="userEmail" type="hidden" value="<?php echo$user_email; ?>" />
<input name="userPass" type="hidden" value="<?php echo $password; ?>" />
when I try this code it gives me this error message from page_two:
notice undefined index userName
notice undefined index userEmail
notice undefined index userPass
Pass the variables via url to page_two.
So your header will be
header("Location:page_two.php.php?userName=user_name&userEmail=user_email&userPass=password");
Now catch these variables using $_GET on page_two
<?php
$user_name = $_GET ['userName'];
$user_email = $_GET ['userEmail'];
$password = $_GET ['userPass'];
echo 'your user name: '.$user_name;
echo 'your email: '.$user_email;
echo 'your password: '.$password;
You have the correct approach, but on page_2, instead of retrieving the values from the $_POST array, you should retrieve them from the database, as they now exist there. This will remove your undefined index problem.
Redirect using header to some safe page after inserting the data. You can rather use id of the inserted row to get data on page_2.
Hope this helps.
Since you're building a multi-page web-app. I suggest you have to use SESSION to save the posted information of the 1st page, then use the SESSION variable for the 2nd page.
I hope the link below helps.
http://www.html-form-guide.com/php-form/php-order-form.html
On page two you should include a Select statement which will select all the values that are stored in your table.
mysql_query("SELECT * FROM users ");
( Just a fun little experiment for my first website )
So this part works fine, it receives the information that is inputted from the form on another page. It adds to the "user" table in which consists of 'user', 'pass' (which are added from this given php code) and also 'ID' which auto increments upon adding to the table and then
'screen_name' and 'email' which I want to further add to the given table via another form.
<?
session_start();
include('dbconn.php');
$username = $_POST['user'];
$password = $_POST['pass'];
$sql = "INSERT INTO `user`(`user`, `pass`) VALUES ('".$username."','".$password."')";
$run = mysql_query($sql);
if($run){
$_SESSION['username'] = $username;
}
?>
This part of the code asks for an email address and a screen name which will be then further stored within the database, however I would like it to add to the specific user's information. As 'user' and 'pass' are already saved, the idea is to further then add 'screen_name' and 'email' to that specific user. Not sure what i've done wrong here. Also each time I refresh the page a blank user is added to a field in the database.
<form id="contact-form" method="post">
<div>
<label>
<span>Userame/Screen Name:</span>
<input placeholder="Please enter your name" name="screen_name" type="text" tabindex="1" required autofocus>
</label>
</div>
<div>
<label>
<span>Email:</span>
<input placeholder="Please enter your email address" name="email" type="email" tabindex="2" required>
</label>
</div>
<div>
<button name="submit" type="submit" id="contact-submit" data-text="...Sending">Submit</button>
</div>
<input type="hidden" name="user" value="<?php echo $_POST['user']; ?> />
</form>
Here is the code which is connected to the above form, it is on the same page and for some reason I am having trouble getting it to even add to any fields within the database let alone the one that is already active for the new user.
<?php
session_start();
include('dbconn.php');
$screen_name = $_POST['screen_name'];
$email = $_POST['email'];
$sql = "UPDATE `user` SET `screen_name` = '$screen_name', `email` = '$email' WHERE user = $username";
$run = mysql_query($sql);
?>
Any help would be more than appreciated. Not usually a guy who asks for help but as being stuck on this problem for ages and looking through multiple Stackoverflow posts, thought I'd add my own question!
It seems that in your second php script you don't initialize $username.
You should probably add $username = $_SESSION['username'];
Also you need to put quotes around it in your query.
About the blank users being inserted on page refresh, my guess would be that the first php script gets executed, but the $_POST variable isn't set.
Finally you should read up on SQL injection http://php.net/manual/en/security.database.sql-injection.php
Basically I want to create a cookie in PHP that remembers what a user has entered into a form (that directs to a separate page), so that anytime they come back to the page, the form is already prepopulated with whatever information they put into it the first time around.
I've looked everywhere and can't really find a good answer for how to do this. This is how my code is configured right now (which isn't working).
PHP:
$fname = $_POST['fname'];
$lname = $_POST['lname'];
setcookie( "fname", $fname, time() + 36000 );
setcookie( "lname", $lname, time() + 36000 );
HTML:
<form method="post" action="hidden.php">
<p>
First Name: <input type="text" maxlength="40" name="fname" id="fname" value="
<?php
if(isset($_COOKIE['fname']))
{
echo $_COOKIE['fname'];
}
else
{
echo "";
}
?>"/>
</p>
<p>
Last Name: <input type="text" maxlength="40" name="lname" id="lname" value="
<?php
if(isset($_COOKIE['lname']))
{
echo $_COOKIE['lname'];
}
else
{
echo "";
}
?>"/>
</p>
Any mind telling me what I'm doing wrong and how I can fix it? Thank you!
You're close, however $fname in your HTML is empty (presuming you've submitted all relevant code). You need to either set $fname to the value of $_COOKIE['fname'], or just echo the cookie value directly. For instance:
echo $_COOKIE['fname']; // Be sure to sanitize this!
every time i am refreshing the page and i am getting the same value stored in the post array.
i want execution of echo statement only after submit and after refreshing no echo results..
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "User name : <b> $name </b>";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
From just a form, you won't be able to check if it was a refresh, or a first submit, regardless of using GET or POST method.
To ensure a single message, you need to:
a. redirect the user to somewhere else after you processed the request.
if(isset($_POST['submit'])) {
// process data
header("Location: new-url");
}
And display the message on the other URL.
b. set a cookie / session variable, which tells you the form was already processed.
if(isset($_POST['submit']) && !isset($_SESSION['form_processed'])) {
$_SESSION['form_processed'] = true;
}
This second approach will kill your form until the user closes the browser, so you should do something more complex - like storing another hidden field in the form, and storing that in the session.
If you submit a form and then refresh the resulting page, the browser will re-post the form (usually prompts first). That is why the POST data is always present.
An option would be to store a session variable and have it sent in the form, then check if it matches in the form processing code - to determine if it is a re-post or not.
Within the form:
<input type="hidden" name="time" value="<?php echo $time; ?>" />
In the PHP:
session_start();
if(isset($_POST['submit']))
{
if(isset($_SESSION['time']) && $_SESSION['time'] == $_POST['time'])
{
echo "User name : <b> $name </b>";
}
}
$time = $_SESSION['time'] = time();
Another option is to redirect after processing the post data:
if(isset($_POST['submit']))
{
...
...
header('Location: ' . basename($_SERVER['PHP_SELF']));
exit();
}
You need to maintain a state as to whether $name has already been displayed or not. The easiest way is probably to maintain that state in a browser cookie.
<?php
$nonce = $_COOKIE['nonce'];
$new_nonce = mt_rand();
setcookie('nonce', $new_nonce);
if(isset($_POST['submit']) && $_POST['nonce'] == $nonce)
{
$name = $_POST['name'];
echo "User name : <b> $name </b>";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="nonce" value="<?php echo $new_nonce ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
Problems
you are polluting the user “session” with stale variable.
this will break if your user opens several windows (or tabs) to the same page. To fix this you would have to change the nonce cookie into an array of nonces, and update it accordingly.
if you want refresh page after submit use
<form method="get"
sure if your form hasn't a lot of data and also need to use $_GET instead of $_POST variable:)
correct way for you, but this logic is not good, need to refactor this script:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "User name : <b> $name </b>";
unset($_POST['submit']);
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>