Variable doesn't get defined/updated after function processes? - php

I have coded some alerting system.
But let's not look at the system itself, Let's look at how will the system know that the system really did sent the alert/error to the browsing user.
I have made something so when you randomly go to ?alert=name, without doing any error, it will say 'No errors'.
But if the system makes you go to ?alert=name, it will echo the error.
How I handle posts
function postComment() {
if (!empty($_POST['name']) || !empty($_POST['comment'])) {
$comment = mysql_real_escape_string(htmlentities($_POST['comment']));
$guest = mysql_real_escape_string(htmlentities($_POST['name']));
}
$guestId = 1;
if (empty($guest)) {
$alert = 1;
return header('location: index.php?alert=name');
}
if (empty($comment)) {
$alert = 2;
return header('location: index.php?alert=comment');
}
if (!isset($_COOKIE['alreadyPosted'])) {
mysql_query("INSERT INTO `comments` (`comment_guest`, `guest_id`, `comment`, `comment_date`, `comment_time`) VALUES ('$guest', '$guestId', '$comment', CURDATE(), CURTIME())") or die(mysql_error());
header('Location: index.php?action=sucess');
setcookie(alreadyPosted, $cookieId+1, time() + 60);
} else {
$alert = 3;
header('location: index.php?alert=delay');
}
}
As you see, to check if user really getting that error, I will set $alert to whatever error number it is.
And to check if hes getting the error I will use this:
if (isset($_GET['alert']) == 'name') {
if ($alert == 1) {
echo 'hai';
} else {
echo 'No errors';
}
}
You will probably wonder why I am doing it this way.., well because I use 1 function for post, and my post function goes under the form, and i want the alerts to display up to the form.
Problem:
The variable either doesn't get set to the number that it is supposed to when running the function,
or.. something is blocking it from it.. I don't know..
My guess: Because the check for errors is located up to the postComment function before the variables even get set?
<?php
if (isset($_GET['alert']) == 'name') {
if ($alert == 1) {
echo 'hai';
} else {
echo 'No errors';
}
}
?>
<form action="index.php" method="POST">
<input type="text" name="name" placeholder="Your name here" class="field">
<textarea class="textarea" name="comment" placeholder="Your comment here..."></textarea>
<input type="submit" name="send" class="blue_button" value="Post Comment">
</form><input type="submit" name="" id="margin" class="blue_button" value="See all messages">
<br />
<?php
//Show the comments
showComments();
if (isset($_POST['send'])) {
postComment();
}
if (isset($_GET['delete']) == "comment"){
deleteComment();
}
echo '<br />';
?>
If it is, what is the solution?
Thanks!
Please don't start with the story about mysql_ function, I understood & I will use PDO instead, but I am using mysql_ at the moment for testing purposes

The problem is that you're redirecting on an error, and so the $alert variable does not get carried over.
To fix the problem add the alert type to the $_GET parameters:
function postComment()
{
// ...
if (empty($guest))
{
header('location: index.php?alert=name&alert_type=1');
exit;
}
// ...
}
And then when you check for the error:
if (isset($_GET['alert']) && 'name' == $_GET['alert'])
{
if (isset($_GET['alert_type']) && '1' == $_GET['alert_type'])
{
echo 'hai';
}
else
{
echo 'No errors';
}
}
Note also that I fixed the error here:
isset($_GET['alert']) == 'name'
That doesn't do what I think you think it does. What you want is:
isset($_GET['alert']) && 'name' == $_GET['alert']
(Excuse the order of the comparison; I prefer to have variables on the right for comparisons as it will cause a parse error if you miss a = -- much better than having it run but not do what you expect)

if you are a newbie, you better consider using client side scripting (viz javascript) for validation as using server side validation will simple make the process longer. but as you are facing problems, this might give you the solution.
as you are redirecting the page to index.php?alert=name', so $alert is never set initially when the page loads itself. when you call the function postcomment(), $alert is initiated but immediately destroyed when the system redirects. And as $alert never holds a value when you randomly visit the page, it shows no error.

Related

PHP check for errors in input, if no errors execute and upload

I'm currently working on a registration system and ran into some problem.
I'll start with pasting a simplified version of the code before:
session_start();
if (isset($_SESSION['logged_in'])) {
header('Location: #notLoggedIn');
exit;
} else {
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if //if field is empty {
//display error
} else if //check if any unallowed characters {
//display another error
} else {
//give the checked input a string/variable, ex: $name= ($_POST["name"]);
}
// Like 4-5 other checks running in the same way as above
}
$query = $pdo->prepare('INSERT INTO table (a, b, c, d, e) VALUES (?,?,?,?,?)');
$query->bindValue(1, $1);
$query->bindValue(2, $2);
$query->bindValue(3, $3);
$query->bindValue(4, $4);
$query->bindValue(5, $5);
$query->execute();
header('Location: index.php');
exit;
}
The problem is the fact that it runs everything at once and just redirects me to index.php.
How do I make sure it first of all checks if the form has been submitted before running.
After that I want it to check for any errors in ALL fields. If there are errors, stop.
But if there are no errors, just continue on and upload to my database.
I do think that I'm on a goodway, but currently pretty stuck, any help or push in the correct direction would be awesome!
Thank you!
Your question isn't exactly clear, nor is your code which is also incomplete (where is the form?).
You seem to be at an early stage of learning the form handling, and likely would benefit from further reading and testing before you ask specific questions.
Here are some starters:
http://en.wikipedia.org/wiki/Post/Redirect/Get
What's the best method for sanitizing user input with PHP?
The definitive guide to form-based website authentication
I'll give some info anyway, as have some free time.
For example, your first if checks if session IS set, if TRUE redirect to notLoggedIn. Are you sure this is intentional? Either they're logged in, echo message to suit, or not and so show the reg page (most sites show a login and reg on the same page, for convenience for all scenarios).
As this is a registration form, surely you meant if IS logged in then redirect to YouAreAlreadyLoggedIn?
In fact, I'd just exit a message "You are already logged in" then stop the script.
The problem is the fact that it runs everything at once and just redirects me to index.php.
That's because it has no other option, as at the end of your script after XYZ it redirects to index.php.
If you do not want it to do this then change it. Either don't redirect, handle the entire process more constructively, or exit at some point you need it to (like form errors).
How do I make sure it first of all checks if the form has been submitted before running.
I don't see a form, so don't know exactly what you are doing to advise.
Ideally you'd use the PRG (Post Redirect Get).
http://en.wikipedia.org/wiki/Post/Redirect/Get
Your Script
I've edited your script to make this an answer to the question, and tidied it up a little.
e.g. in your script, specifically at the top, you don't need the else as there's an exit() in the if. When the if returns true, the script will stop, otherwise (with or without an else) it will continue.
The code:
session_start();
if (isset($_SESSION['logged_in']))
{
exit('You are already logged in');
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if ( strlen($POST['field_name']) < 4 )
{
exit('Minimum 4 chars required');
}
elseif ( strlen($POST['field_name']) > 20 )
{
exit('Max of 20 chars allowed');
}
elseif ( preg_match("/^[A-z0-9]+$/", $POST['field_name']) != 1 )
{
exit('Invalid chars - allowed A-z and 0-9 only');
}
else
{
// Not sure what you want here
// If all ok (no errors above)
// then sanatise the data and insert into DB
}
}
As for entering into the DB, you need much more checking and handling of the entire process before you just allow the DB stuff to run.
Not sure why you redirect to index.php. You'd then need to handle form submission results in index.php to tell user you are registered.
On the form page, tell them the errors they have in the fields, or echo out the success message and what happens next (i.e. go to your account page, or (hopefully) confirm the email you sent before logging in).
As for the validation checks in the POSTed form data, it's entirely up to you what you need. But I've given you some very basic to go on. Make sure your max set in the form matches the database column allowance, or if (eg) DB varchar is set to 15 and you allow users to enter 20, the data they enter will be truncated, and they'll register, but never be able to login (or some other data will be broken, their name/username etc).
got bored. this is not for internet points.
<?php
// create table user (userid int auto_increment primary key, username varchar(60), password varchar(60));
// alter table user add constraint uc_user_username unique (username);
var_dump($_POST);
$user = isset($_POST['username']) ? trim($_POST['username']) : '';
$pass = isset($_POST['password']) ? trim($_POST['password']) : '';
$pass2 = isset($_POST['confirm']) ? trim($_POST['password2']) : '';
$action = isset($_POST['action_type']) ? $_POST['action_type'] : '';
if (empty($_POST)) {
// nothing posted
}
else {
if (empty($user)) {
error('you did not provide a username');
}
elseif (empty($pass)) {
error('you did not provide a password');
}
else {
$mysqli = mysqli_connect('localhost','root','','test')
or die('Error ' . mysqli_error($link));
if ($action=='new_user') {
$userdata = get_user_info($mysqli,$user);
if ($userdata) {
error('user already exists');
}
else {
$validpass = validate_password($pass);
if ($validpass && $pass==$pass2){
if (make_new_user($mysqli,$user,$pass)) {
print "<br/>new user created<br/><br/>";
}
}
else error('passwords did not match');
}
}
elseif ($action=='login_user') {
$verified = verify_credentials($mysqli,$user,$pass);
if ($verified) {
print "<br/>user logged in<br/><br/>";
}
}
elseif ($action=='update_pass') {
$verified = verify_credentials($mysqli,$user,$pass);
$validpass = validate_password($pass);
if ($verified && $validpass && $pass!=$pass2) {
if (update_password($mysqli,$user,$pass,$pass2)) {
print "<br/>new user created<br/><br/>";
}
}
else error('cannot update to same password');
}
$mysqli->close();
}
}
function error($message) {
print "<br/>$message<br/><br/>";
}
function update_password($mysqli,$user,$pass,$pass2) {
$hash = password_hash($pass, PASSWORD_BCRYPT);
$stmt = $mysqli->prepare('update user set password = ? where username = ?');
$stmt->bind_param('ss',$user,$hash);
$stmt->execute();
$msql_error = $mysqli->error;
$updated = !(empty($msql_error));
error($msql_error); // for debugging only
return $updated;
}
function make_new_user($mysqli,$user,$pass) {
$userid = false;
$hash = password_hash($pass, PASSWORD_BCRYPT);
$stmt = $mysqli->prepare('insert into user (username,password) values (?,?)');
$stmt->bind_param('ss',$user,$hash);
$stmt->execute();
$msql_error = $mysqli->error;
if (empty($msql_error)) {
$userid = $mysqli->insert_id;
}
else error($msql_error); // for debugging only
return $userid;
}
// really, this should be done with javascript instantaneously
function validate_password($pass) {
$error = false;
if (strlen($pass) < 8) {
error('please enter a password with at least 8 characters');
}
elseif (!preg_match('`[A-Z]`', $pass)) {
error('please enter at least 1 capital letter');
}
else $error = true;
return $error;
}
function verify_credentials($mysqli,$user,$pass) {
$row = get_user_info($mysqli,$user);
$verified = false;
if ($row) {
if (password_verify($pass, $row['pass'])) {
$verified = true;
}
}
else error('username and password did not match');
return $verified;
}
function get_user_info($mysqli,$user) {
$row = array();
$stmt = $mysqli->prepare('select userid, username, password
from user
where username = ?');
$stmt->bind_param('s',$user);
$stmt->execute();
$stmt->bind_result($row['userid'],$row['user'],$row['pass']);
if (!$stmt->fetch()) $row = false;
$stmt->close();
return $row;
}
?>
<body>
<form action='?' method='post'>
<table id='input_table'>
<tr><td><span>username </span></td><td><input id='username' name='username' type='text' value='<?php echo $user ?>'></td></tr>
<tr><td><span>password </span></td><td><input id='password' name='password' type='text' value='<?php echo $pass ?>'></td></tr>
<tr><td><span>password2</span></td><td><input id='password2' name='password2' type='text' value='<?php echo $pass2 ?>'></td></tr>
<tr><td> </td><td> </td></tr>
<tr><td colspan=2>this just picks the action for testing... you wouldn't keep it around</td></tr>
<tr><td><input type='radio' name='action_type' value='new_user' <?php echo $action=='new_user'?'checked':'' ?>>New User</td></tr>
<tr><td><input type='radio' name='action_type' value='login_user' <?php echo $action=='login_user'?'checked':'' ?>>Logging In</td></tr>
<tr><td><input type='radio' name='action_type' value='update_pass' <?php echo $action=='update_pass'?'checked':'' ?>>New Password</td></tr>
<tr><td> </td><td> </td></tr>
<tr><td colspan=2><input id='submit' name='submit' type='submit'/></td></tr>
</form>
</body>
// error = 0 means no error found you can continue to upload...
if ($_FILES['file']['error'] == 0) {
}
Here are all of the errors explained: http://php.net/manual/en/features.file-upload.errors.php
UPLOAD_ERR_OK Value: 0; There is no error, the file uploaded with success.
UPLOAD_ERR_INI_SIZE Value: 1; The uploaded file exceeds the
upload_max_filesize directive in php.ini.
UPLOAD_ERR_FORM_SIZE Value: 2; The uploaded file exceeds the
MAX_FILE_SIZE directive that was specified in the HTML form.
UPLOAD_ERR_PARTIAL Value: 3; The uploaded file was only partially uploaded.
UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded.
UPLOAD_ERR_NO_TMP_DIR Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.
UPLOAD_ERR_CANT_WRITE Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
UPLOAD_ERR_EXTENSION Value: 8; A PHP extension stopped the file
upload. PHP does not provide a way to ascertain which extension caused
the file upload to stop; examining the list of loaded extensions with
phpinfo() may help. Introduced in PHP 5.2.0.
To validate input fields
if(empty($_POST['name'])&&empty($_POST['password'])){
//fields empty show error here
}else if (is_numeric($username[0])){
echo 'First character must be a letter';
}
else if (!preg_match('/^[a-zA-Z0-9]+$/', $username)) {
echo 'Only letters and numbers are allowed';
}else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo 'Invalid email address.';
}else if(!preg_match("/^[\pL\s,.'-]+$/u", $name)) {
echo 'Invalid name.';
}

Global error message in php

I have a problem with the understanding of variable scopes.
I've got a huge .php file with many $_POST validations (I know that isn't not good practise). Anyways I want a little html-part above all the code which outputs an error message. This message I want to change in every $_POST validation function.
Example:
if($ERR) {
echo '<div class="error-message">'.$ERR.'</div>';
}
Now my functions are following in the same file.
if(isset($_POST['test']) {
$ERR = 'Error!';
}
if(isset($_POST['test2'] {
$ERR = 'Error 2!';
}
But that doesn't work. I think there's a huge missunderstanding and i'm ashamed.
Can you help me?
I didnt catch your question but maybe this is your answer:
<body>
<p id="error_message">
<?php if(isset($ERR)){echo $ERR;} ?>
</p>
</body>
and I suggest you to learn how to work with sessions.
and you should know that $_Post will be empty on each refresh or F5
You can do put the errors in array make them dynamic.
<?php
$error = array();
if (!isset($_POST["test"]) || empty($_POST["test"])) {
$error['test'] = "test Field is required";
} else if (!isset($_POST["test1"]) || empty($_POST["test1"])) {
$error['test1'] = "test Field is required";
}else{
//do something else
}
?>
You can also use switch statement instead of elseif which is neater.

PHP failing checking variables

I have a problem with my PHP script, which checks 3 variables (code below):
$auth (The mail author)
$subj (The mail subject)
$text (The mail message)
FORM:
(NOTE: I used the "GET" method because for some strange reason the "POST" method didn't work)
<div id="contact_form">
<form method="get" name="contact" action="home.php">
<input type="hidden"
name="method"
value="send"/>
E-Mail:<br/>
<input type="text"
id="author"
name="author"
class="require input_field"
value=""/>
<br/>
Subject:<br/>
<input type="text"
id="subject"
name="subject"
class="require input_field"
value=""/>
<br/>
Message:<br/>
<textarea id="text"
name="text"
rows="0"
cols="0"
class="required"
value=""></textarea>
<br/>
<input type="submit"
class="submit_btn"
name="submit"
id="submit"
value="Submit" />
</form>
</div>
The form works just fine now.
PHP:
<?php // ||HOME.PHP||
$method = $_GET['method'];
$auth = $_GET['author'];
$subj = $_GET['subject'];
$text = $_GET['text'];
$recv = "mymail#stuff.com";
function redirect($location) {
if($location == "true") {
header("Location: http://mysite.com/home.php?method=result&status=true");
} else {
header("Location: http://mysite.com/home.php?method=result&status=false");
}
}
//...
//Other methods...
//...
//METHOD SEND
if($method == "send") {
//HERE IS THE PROBLEM
//These are apparently not working
//If i leave the form blank and submit it
//these won't redirect to "false" (mail not sent),
//and the script will just continue, send the empty mail
//and redirect to "true" (mail sent)
if(empty($auth)) { redirect(""); }
if(empty($subj)) { redirect(""); }
if(empty($text)) { redirect(""); }
if(!strstr($auth, '#')) { redirect(""); }
if(!strstr($auth, '.')) { redirect(""); }
if(strlen($auth) < 5) { redirect(""); }
if(strlen($subj) < 4) { redirect(""); }
if(strlen($text) < 4) { redirect(""); }
//From here it should work just fine
//As i'm not sure the "RESULT" method (below) is working fine, i
//posted it too.
$auth = "From: " . $auth;
mail($recv,$subj,$text,$auth);
redirect("true");
require("template/footer.html");
exit(0);
}
//METHOD RESULT
if($method == "result") {
$status = $_GET['status'];
if($status == "true") {
echo "mail sent";
} else {
echo "mail not sent";
}
?>
<script language="javascript">
setTimeout("location.href = 'http://adteam.altervista.org/home.php';", 5000);
</script>
<?php
exit(0);
} ?>
The problem is explained in the PHP code (in the comments below the "SEND" method).
Do you guys have any suggestion?
You need to stop the script execution after you've set the redirect headers. Otherwise it will just continue to sending the mail and set new redirect headers before any headers are sent to the browser.
function redirect($location) {
if($location) {
header("Location: http://mysite.com/home.php?method=result&status=true");
} else {
header("Location: http://mysite.com/home.php?method=result&status=false");
}
die();
}
Note that if( $location == "true" ) is kind of an anti-pattern; it's better to use boolean true and false instead of strings.
Should be easy. Your saying that "" is false. But it ain't: because "" is true, but empty which is true. false is not set or specified false. So you should do:
function redirect($location) {
if($location) {
header("Location: http://mysite.com/home.php?method=result&status=true");
exit();
} else {
header("Location: http://mysite.com/home.php?method=result&status=false");
exit();
}
}
And use: redirect(true) / redirect(false);
A string will always evaluate to true, even if it is empty. That's precisely the reason why we check strings using empty() as opposed to isset(). A few more things:
You should be using POST to submit the email.
You should probably check if the form was actually submitted before validating the input.
You should create and display specific error messages telling the user what required fields they did not complete.
You should run some careful validation routines on the input to avoid having your email form used to send spam and malware.
Simply add exit in false branch:
function redirect($location) {
if($location == "true") {
header("Location: http://mysite.com/home.php?method=result&status=true");
} else {
header("Location: http://mysite.com/home.php?method=result&status=false");
exit(0); //simply add it here
}
}
header function does not stop further execution by itself and you must stop doing anything else if do not want to send an email when something is wrong.
Actually, you may simply add exit after if statement.

PHP form validation on same page with external processing

I am trying to wrap up this contact/quote form which has same page validation but external processing. I have set up a variable to go in the form action and the variable/url changes from the same page to the processing page when the form validates. However, it is taking two clicks on the submit button to process the form after all the required fields have been filled in: All the required fields will be filled in, I click submit, the page reloads with the saved data variables and then when I hit submit agin, it finally goes through, sending the email and loading the thankyou page. I have searched the posts here and tried multiple things but have not found a solution. I am definitely not a php expert, still a newbie so this may not be the best way to accomplish this but I'd appreciate any ideas on how to finish this up. Here is what I have:
<?php
....
if (empty($Name) && empty($Company) && empty($Address1) && empty($City) && empty($State) && empty($Phone))
{
echo '<p class="tan">The fields marked with an * are required.</p>';
$Process = 'samepageurl';
}
/*else if (empty($Name) || is_numeric($Name))
{
echo '<p class="tan"><b>Please enter your name.</b></p>';
}*/
else if (empty($Company) || is_numeric($Company))
{
echo '<p class="tan"><b>Please enter your company name.</b></p>';
$Process = 'samepageurl';
}
else if (empty($Address1) || is_numeric($Address1))
{
echo '<p class="tan"><b>Please enter your address.</b></p>';
$Process = 'samepageurl';
}
else if (empty($City) || is_numeric($City))
{
echo '<p class="tan"><b>Please enter your city.</b></p>';
$Process = 'samepageurl';
}
else if (empty($State) || is_numeric($State))
{
echo '<p class="tan"><b>Please enter your state.</b></p>';
$Process = 'samepageurl';
}
else if (empty($Phone) || ctype_alpha($Phone))
{
echo '<p class="tan"><b>Please enter your phone number.</b></p>';
$Process = 'samepageurl';
}
else if (strlen($Phone) < 10 || strlen($Phone) > 12 || ctype_alpha($Phone) || ctype_space($Phone))
{
echo '<p class="tan"><b>Please enter a phone number with an area code.</b></p>';
$Process = 'samepageurl';
}
else if (isset($Name) && isset($Company) && isset($Address1) && isset($City) && isset($State) && isset($Phone))
{
$Process = 'processingurl';
}
?>
<form action="<?php echo $Process; ?>" method="post" class="print" >
<p><input type="hidden" name="recipient" value="responses#url.com"/>
<input type="hidden" name="subject" value="Web Site Response"/>
<input type="hidden" name="redirect" value="thankyou.html"/></p>
... form fields ...
</form>
Thank you in advance!
First check for missing variables, then extract and validate the variables, then serve content based on them.
<?php
function verifyPostContains(&$req) {
global $_POST;
$missing = array();
foreach($req as $var => $_) {
if(!isset($_POST[$var])) {
$missing[] = $var;
}
}
return $missing;
}
$requirements = array('name'=>'','city'=>'','state'=>'',...);
$missing = verifyPostContains($requirements);
if(count($missing)>0) {
$content = formErrorReport($missing);
sendHeaders();
echo $content;
exit();
}
// extract, making sure to sanitize
$name = sanitize($_POST["name"]);
...
$errorHtml = array();
// validate by reference. Effectively call testName($name).
if(failsValidation($name, "testName")) {
$errorHtml [] = generateError(NAME_ERROR, $name);
} else { $requirements["name"] = $name; }
if(failsValidation($city, "testCity")) {
$errorHtml [] = generateError(CITY_ERROR, $city);
} else { $requirements["city"] = $name; }
...
if(count($errorHTML)>0) {
generateErrorPage($requirements, $missing, $errorHTML);
} else { processForm($requirements); }
?>
this code assumes you have functions to do the various bits that need to be done, and has some string constants for generating error HTML.
As a newcomer you may want to google for some tutorials that explain doing form processing using PHP at the server, and JavaScript at the client. If you find a tutorial that gives you code that echos errors while it's testing the data, such as you code does, move along. It's not a good tutorial. If you find one that stops after it finds one error, move along too. If you find one that tells you to make sure the values are right in JavaScript, and then says "we already validated this at the client so we use the values directly in PHP", move along, too. Look for a tutorial that explains:
ensuring there's data in all the form fields, using JavaScript, so the submit button is disabled until there's data for all the fields.
ensuring the data matches your criteria, in PHP, so that people who just POST to your server without ever using your page don't get away with injecting all manner of fun stuff they weren't supposed to be able to do
you generate a page with all the errors explained, if there are any, and the form repopulated with the wrong data, but highlighted as wrong
you process the post request if there are no errors.
(Bonus points if the tutorial explains that a POST request is not required to actually ever generate page content as a response, other than a header that indicates whether or not the POST call was accepted or rejected.)

PHP Form must be submitted twice to update checkbox

I'm still relatively new to PHP. I'm trying to build a privacy settings page for members to opt out of automatic emails for triggered events (i.e. private message notification). I want the checkbox set automatically based on the database setting. As of now, the form does update the database correctly, but the checkbox status does not show the correct setting unless the Submit button is pressed twice, or the page is reloaded. Setting would be '0' for unchecked, '1' for checked. I'd love to use Ajax or jQuery to handle this, but I don't know those at all.
privacysettings.php
<?php
$id = "";
$pm_mail_able = "";
$pm_email = "";
if (isset($_GET['id'])) {
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers
} else if (isset($_SESSION['idx'])) {
$id = $logOptions_id;
} else {
header("location: index.php");
exit();
}
//query to get checkbox status
$sql = mysql_query("SELECT * FROM members WHERE id='$id'");
while($row = mysql_fetch_array($sql)){
$pm_mail_able = $row['pm_mail_able'];
}
switch ($pm_mail_able) {
case 0:
$pm_setting = NULL;
break;
case 1:
$pm_setting = "checked=\"checked\"";
break;
}
if(isset($_GET['pm_email']) && !empty($_GET['pm_email'])) {
$updateqry = mysql_query("UPDATE members SET pm_mail_able='1' WHERE id='$id'");
} else {
$updateqry = mysql_query("UPDATE members SET pm_mail_able='0' WHERE id='$id'");
}
?>
<html>
Email Notifications<br />
<form name="testform" method="get" action="PvResult.php">
When a friend sends me a private message
<input type="checkbox" name="pm_email" value="on"<?php echo $pm_setting;?> />
<br /><br />
<input type="submit" value="Submit" />
</form>
</html>
PvResult.php
<?php
$url = 'http://www.mywebsite.com';
//If the form isn't submitted, redirect to the form
if(!isset($_GET['Submit']))
header('Location: '.$url.'/privacysettings.php');
//Redirect to the correct location based on form input
$pm_email = $_GET['pm_email'];
$url .= '/privacysettings.php?pm_email='.$pm_email;
header('Location: '.$url);
?>
Okay, hopefully this won't just answer your question, but give you a few best practices you might want to consider.
You can combine these two scripts into one relatively easily. Also, I'd highly suggest using a POST instead of GET; GET is very limited and is not intended to submit data like you're using it. If you're going to be changing data in a back-end store, using GET will bite you. Maybe not today, maybe not tomorrow, but it will, trust me.
You really should consider moving to PDO instead of the mysql_ functions. PDO is a lot better in handling parameterized queries, which you really should have here for better security, and it's more portable if someday you want to move to a different database system.
I'm still a little hazy on how your app is getting the $id. Most apps get it from a $_SESSION variable, making sure that the user has successfully validated a login. If you're not doing that, please do. You might want to thoroughly digest this article, it's got a lot of juicy best practices regarding authentication and "remember me"-type functionality.
Here's a bit of a rewrite. I haven't actually tested it, but it should give you a pretty good idea on where to go with your immediate needs. If it throws any errors (remember the disclaimer: I haven't actually tested it!), let me know and I'll try to debug it.
<?php
$message = '';
$pm_setting = '';
$id = 0;
// Put your $id retrieval logic here. It should look something like:
if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
if (!preg_match('/^\\d{1,10}$/', $id) > 0) {
// Someone is trying to hack your site.
header("location: scum.php");
exit();
}
$id = intval($id);
}
// Quick security note: You might want to read up on a topic called
// session hijacking if you want to ensure your site is secure and
// this $id isn't spoofed.
if (isset($_POST['Submit'])) {
// The form is being submitted. We don't need to read the current
// pm_mail_able setting from the database because we're going to
// overwrite it anyway.
if ($id > 0) {
$pm_mail_able = 0;
if (isset($_POST['pm_email']) && $_POST['pm_email'] === 'on') {
$pm_mail_able = 1;
$pm_setting = 'checked ';
}
$query = 'UPDATE members SET pm_mail_able='.$pm_mail_able.
' WHERE id = '.$id;
mysql_query($query);
// Another quick security note: You REALLY need to consider
// updating to PDO so that you can bind these parameters
// instead. The mysql_ functions are probably going to be
// deprecated soon anyway.
if (mysql_affected_rows($query) > 0)
$message = '<p style="color: #00a000;">Settings saved!</p>';
else
$message = '<p style="color: #a00000;">User id not valid.</p>';
}
else
$message = '<p style="color: #a00000;">User id not valid.</p>';
}
else {
// This is the first load of the form, we need to just display it
// with the existing setting.
if ($id > 0) {
$query = mysql_query('SELECT * FROM members WHERE id = '.$id);
if (($row = mysql_fetch_array($query, MYSQL_ASSOC)) !== FALSE)
if ($row['pm_mail_able'] === 1) $pm_setting = 'checked ';
}
}
?>
<html>
<body>
<?= $message ?>
<!-- Without action parameter, form submitted to this script. -->
<form name="testform" method="post">
E-mail notifications<br />
<input type="checkbox" name="pm_email" value="on" <?= $pm_setting ?>/>
When a friend sends me a private message
<br /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Try to do these settings and see if it will work:
1) You need to add an space between "on" and "checked=checked"
<input type="checkbox" name="pm_email" value="on" <?php echo $pm_setting;?> />
2) You have to reference the submit button by its name, not its value
<input type="submit" name="Submit" value="Send" />
3) When the setting is "0", set $pm_setting as a empty string, instead of NULL
case 0:
$pm_setting = '';
4) Maybe there is some problem with $_GET['pm_email'] and the else is always being executed
5) If the things work when you press the Submit button twice, it means that the form is passing some GET var that make the code work, so try to discover what var is this

Categories