my IF statements in this code are working, but the ELSE statement NEVER processes...and I am not sure why....in fact all of the code processes up until the ELSE statement, and the captua works properly too, if the captcha is right, the user gets a positive message and the data is posted to the database. If the captcha is wrong, no information is posted, but no message is given either..please help:
if(isset($_POST["captcha"]))
if($_SESSION["captcha"] == strtolower($_POST["captcha"]))
if(mysql_query($sql)) {
echo "<script type='text/javascript'>alert('submitted successfully, The records manager will provide you with your record within 3 days!')</script>";
//mail('joe.blow#idaho.com', 'SRRS - New Records Await Processing', 'SRRS - There are new records for processing in the SRRS System' );
//$to = 'joe.blow2#idaho.com' . ', ';
//$to .= $email;
$to = "joe.blow3#idaho.com";
$subject = "SRRS NOTIFICATION - New Student Record Await Processing";
$message = "New Student Record Requests have been submitted and Await Processing";
$from = "joe.blow#idaho.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "<script type='text/javascript'>alert('An Email Has to sent from the SRRS Records Management System to the Records Management Administrator for Processing.')</script>";
//Mail the user
$to = $email;
$subject = "SRRS NOTIFICATION - Your new record request has been submitted.";
$message = "SRRS - Your new record request for $givenname, $legname has been submitted, It will be procssed within 3 working days";
$from = "joe.blow#idaho.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
}
else
{
echo "<script type='text/javascript'>alert('Human Verification not entered properly!')</script>";
}
The problem is that your output for "human verification" being incorrect is the else statement for your SQL query rather than the if statement before that which does the captcha comparison.
Condensed version of what you're doing:
if(isset($_POST["captcha"]))
if($_SESSION["captcha"] == strtolower($_POST["captcha"]))
if(mysql_query($sql)) {
// do stuff
} else {
// output CAPTCHA ERROR! <-- wrong place
}
Change where your statement is:
if(isset($_POST["captcha"])) {
if($_SESSION["captcha"] == strtolower($_POST["captcha"])) {
if(mysql_query($sql)) {
// do stuff
} else {
// CAPTCHA was fine, but the SQL query failed.
}
} else {
echo "<script type='text/javascript'>alert('Human Verification not entered properly!')</script>";
}
}
Note: While using curly brackets for control structures are not necessary when you only have one statement following it (an if block counts as one statement), it's far better for readability if you include them (so I've added them for you).
Looking forward: there are better ways to write your code than lots of nested if statements. You should try working on a structure that catches and handles errors as they happen, instead of wrapping large blocks of code in if statements and dealing with the alternative at the end. Try something like this:
if(!isset($_POST['captcha']) || $_SESSION['captcha'] != strtolower($_POST['captcha'])) {
echo "<script type='text/javascript'>alert('Human Verification not entered properly!')</script>";
exit; // kill the rest of the execution
}
if(!mysql_query($sql)) {
// SQL query failed, output an error
exit; // kill the rest of the execution
}
// Everything's fine, do the rest of your stuff here.
This could be further optimised by using functions and returning false instead of exit from various levels of functions that you call whenever you find an error.
Lastly, I'd suggest that outputting Javascript like that with an alert is probably not the best way to be doing this. You should have a kind of structure where the script/function that performs the task returns a boolean result (true/false) representing whether everything has gone smoothly, perhaps with an accompanying error message to describe it, and you should have a separate script/function that deals with the presentation of that result. An simple example here would be setting the result and message to the session and redirecting the user with PHP to a page that presents the results, instead of using a script tag with an alert.
While I'm at it too - mysql_* functions are deprecated. You should use mysqli_* or PDO instead.
Related
I have a registration php file which is linked with a database I created in a user I created in phpmyadmin. But the issue is whenever I submit values into it the database is not being updated. I don't know what is the issue also I am beginner in this area so I m not fully aware of the functionalities. Links to some images are below. Just go through them you will get a better idea of my query
https://drive.google.com/file/d/1ZtiRxPpTT3NNCut345TSjXOAkIsVsZkK/view?usp=drivesdk
https://drive.google.com/file/d/1FZOEBq641DpmNWXeC3_LYy_FTK49Hm87/view?usp=drivesdk
https://drive.google.com/file/d/1PHbKSPVTnJvvJ-1vWVQwga61JDlpxBIK/view?usp=drivesdk
Try with the below code. Also, you are showing the success message even though you don't know if the query was executed with success.
if(isset($_POST['submit1']))
{
$number = $_POST['number'];
$name = $_POST['name'];
if(empty($number))
{
$errornumber = "Number empty !";
}
elseif(empty($name))
{
$errorname = "Name empty !";
}
else {
$query = "INSERT INTO `student` (`number`,`name`) VALUES('$number','$name')";
if (mysqli_query($link, $query)) {
$success = '<div class="alert alert-success col-lg-6 col-lg-push-3">
Registration successfully. You will receive an email when your account is approved.
</div>'
}
}
}
Now, all you have to do is use , and where you want them to show.
if this doesn't work, it means you have other issues, posting images with portions of code is never a good option to go about asking for help. Nobody will steal your code.
I'm a non-CIS major taking an intro programming classes for a minor through my university. I've been able to successfully code most of the PHP files I need but have been getting hung up over how to perform two functions within the same document. Hopefully you can help.
Within the website, I want to be able to first use MySQL to check a table, called User (where a user is initially registered by the site) to verify that they are in fact registered and that the credentials they provided are correct, and then execute an query to add them to another table.
I've tried mysqli_multi_query to no avail and am just generally inexperienced and unsure of my options as far as functions go.
I have included the code below but be aware that it is a mess as I've attempted several different things before I decided to get some help
<?php
session_start();
require_once("config.php");
$GroupDesc = $_GET["GroupDesc"];
$LeaderID = $_GET["LeaderID"];
$URL = $_GET["URL"];
$Email=$_GET["Email"];
$con = mysqli_connect("$SERVER","$USERID","$DBPASSWORD","$DATABASE");
$query2= "INSERT INTO FA15_1052_tuf02984.WebsiteGroups (ID, Description, LeaderID, URL, LeaderEmail) VALUES ('$GroupDesc', '$LeaderID', '$URL', '$Email');";
/* Here I want to perform the first query or $query1 which checks if the
user exists in MySQL and the info submitted in form is same */
$query1= "SELECT * from USER where LeaderID = '$ID' and Email = '$Email';";
if ($status = mysqli_query($con, $query1)) {
} else {
print "Some of the data you provided didn't match our records. Please contact the webmaster.".mysqli_error($con)." <br>";
$_SESSION["RegState"]= -11;
$_SESSION["ErrorMsg"]= "Database insertion failed due to inconsistent data: ".mysqli_error($con);
header("Location:../index.php");
die();
}
/* How do I tell the file to move onto the next query, which is $query2?
if ($query2) {
$query = "INSERT INTO FA15_1052_tuf02984.WebsiteGroups (ID, Description, LeaderID, URL, LeaderEmail)
VALUES ('$GroupDesc', '$LeaderUID', '$URL', '$Email');";
} */
} else {
print "Membership update failed. Please contact webmaster.".mysqli_error($con)." <br>";
$_SESSION["RegState"]= -11; // 0: Not Registered, 1: Register, -1: Error
$_SESSION["ErrorMsg"]= "Database Insert failed: ".mysqli_error($con);
header("Location:../index.php");
die();
}
There are a few points where your code can be rearranged to make the logic easier to follow. (Don't worry; this is just stuff that comes with experience.) I'll include some comments within the following code to explain what I've done.
<?php
session_start();
require_once("config.php");
$GroupDesc = $_GET["GroupDesc"];
$LeaderID = $_GET["LeaderID"];
$URL = $_GET["URL"];
$Email=$_GET["Email"];
// mysqli_connect is deprecated; the preferred syntax is
$con = new mysqli("$SERVER","$USERID","$DBPASSWORD","$DATABASE");
$query1= "SELECT * from USER where LeaderID = '$ID' and Email = '$Email';";
$result = mysqli_query($con, $query1);
// I personally prefer the following opening-brace style; I just find it
// easier to read. You can use the other style if you want; just do it
// consistently.
if ($result)
{
$row = mysqli_fetch_assoc($result);
if($row)
{
if (($row['ID'] != $LeaderID) or ($row['Email'] != $Email))
{
// Handle the error first, and exit immediately
print "Some of the data you provided didn't match our records. Please contact the webmaster.".mysqli_error($con)." <br>";
$_SESSION["RegState"]= -11;
$_SESSION["ErrorMsg"]= "Database Insert failed due to inconsistent data: ".mysqli_error($con);
header("Location:../index.php");
die();
}
else
{
// If the query succeeded, fall through to the code that processes it
$query = "INSERT INTO FA15_1052_tuf02984.WebsiteGroups (ID, Description, LeaderID, URL, LeaderEmail)
VALUES ('$GroupDesc', '$LeaderUID', '$URL', '$Email');";
$status = mysqli_query($con, $query);
if ($status)
{
// membership has been updated
$_SESSION["RegState"]=9.5; // 0: Not Registered, 1: Register, -1: Error
$message="This is confirmation that you the group you lead has been added to our database.
Your group's ID in our database is "$GID". Please keep this in your records as you will need it to make changes.
If this was done in error, please contact the webmaster at tuf02984webmaster#website.com";
$headers = 'From: tuf02984webmaster#example.com'."\r\n".
'Reply-To: tuf02984webmaster#example.com'. "\r\n".
'X-Mailer: PHP/' . phpversion();
mail($Email, "You are a group leader!", $message, $headers);
header("Location:../index.php");
// die();
// You only use die() to return from an error state.
// Calling die() creates an entry in the server's error log file.
// For a successful completion, use
return;
}
}
}
}
// If we get here, then something has gone wrong which we haven't already handled
print "Membership update failed. Please contact webmaster.".mysqli_error($con)." <br>";
$_SESSION["RegState"]= -11; // 0: Not Registered, 1: Register, -1: Error
$_SESSION["ErrorMsg"]= "Database Insert failed: ".mysqli_error($con);
header("Location:../index.php");
die();
?>
The basic idiom is: Do something, handle the specific error, handle success, do something else, etc., and finally handle any errors that can come from multiple points. If anything is unclear, just ask and I'll edit into my answer.
I haven't covered prepared statements here. Prepared statements are the preferred way to perform non-trivial queries; they help to resist SQL injection attacks as well as simplify type-matching, quoting and escaping of special characters.
I've got a page on my website where users can send me a message by giving their email, name, and a message. On the front end (JS) I do some basic verification, make sure the email is formatted like an email, make sure the other boxes aren't blank, and then I send it to PHP by GET.
Now I'm aware people can do some pretty sneaky stuff by injecting malicious code into PHP. What precautions should I be taking? When I was working with MySQL, I would escape it using the mysqli escape function. What should I be doing here?
Here's my script right now:
<?php
if(!isset($_GET["message"]) || !isset($_GET["name"]) || !isset($_GET["email"])){
echo "Check all the fields are correctly filled in and try again!";
die();
}
$email = $_GET["email"];
$message = $_GET["message"];
$name = $_GET["name"];
if($email == ""|| $message == "" || $name == ""){
echo "Check all the fields are correctly filled in and try again!";
die();
}
$message = wordwrap($message, 70);
mail("email#email.com","A Message From " . $name,$message,"From: $email\n");
echo "success";
?>
A very basic way is that you can declare a variable (for example $pattern)and store regular expressions (like patterns used commonly in attacks) in it, then use preg_match($pattern, $valueFromYourForm) method to see if any of the passed values matches any of those expressions and then you can stop the execution.
I understand this has been discussed before but since this post in late 2010 and other discussions around that time when issues were raised - Does FILTER_VALIDATE_EMAIL make a string safe for insertion in database? - I have tried some of the situations described, such as using single quotes and the ` characters in an email form where I am using FILTER_VALIDATE_EMAIL and it has blocked them from being entered into the database.
Have recent releases of PHP fixed earlier issues and is it safe?
I'm tempted to also use mysql_real_escape_string(), presumably the two functions can be used in parallel without any conflict?
Here is the mailing list code that I am using to put addresses into the database
<?php
// connects the database access information this file
include("mailing_list_include.php");
// the following code relates to mailing list signups only
if (($_POST) && ($_POST["action"] == "unsub")) {
// trying to ubsubscribe; validate email addresses
if ($_POST["email"] == "") {
header("Location: mailing_list_remove.php");
exit;
} else {
// connect to database
doDB();
// filtering out anything that isn't an email address
if ( filter_var(($_POST["email"]), FILTER_VALIDATE_EMAIL) == TRUE) {
echo '';
} else {
echo 'Invalid Email Address';
exit;
}
// check that email is in the database
emailChecker($_POST["email"]);
// get number of results and do action
if (mysqli_num_rows($check_res) < 1) {
// free result
mysqli_free_result($check_res);
// print failure message
$display_block = "We couldn't find ".$_POST["email"].". No action has therefore been taken.";
} else {
// get value of ID from result
while ($row = mysqli_fetch_array($check_res)) {
$id = $row["id"];
}
// unsubscribe the address
$del_sql = "DELETE FROM subscribers
WHERE id = '".$id."'";
$del_res = mysqli_query($mysqli, $del_sql)
or die(mysql_error($mysqli));
$display_block = " Your email address, ".$_POST["email"].", is unsubscribed!";
}
mysqli_close($mysqli);
}
}
?>
<html>
<?php echo "$display_block";?>
</html>
The filter_var flag FILTER_VALIDATE_EMAIL will do what it says = Validate value as e-mail, meaning if its not an email it will return false.
You might be looking for FILTER_SANITIZE_EMAIL which will (Remove all characters, except letters, digits and !#$%&'*+-/=?^_`{|}~#.[] )
or
FILTER_SANITIZE_STRING will Strip tags, optionally strip or encode special characters.
Tho I don't recommend w3schools it has a list of filter_var flags http://www.w3schools.com/php/php_ref_filter.asp
Also as others have said, use PDO's prepared query's tobe safe, you can find a great pdo example here: http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html#10 which will explain a few things and there is also a simple pdo CRUD (Create Retrieve Update Delete) class here: http://www.phpro.org/classes/PDO-CRUD.html
good luck...
Although the item is successfully added to the database, I'm not sure that I'm executing the mysql_real_escape_string() function correctly and, thus, getting the error. Any help is appreciated.
Success!
Warning: array_map() [function.array-map]: Argument #2 should be an array in /home/site4/public_html/lab/mailing_list_dev_1-0/mailing_list_add.php on line 32
Thanks for signing up!
Here's the code in question...
<?php
// connects the database access information this file
include("mailing_list_include.php");
// the following code relates to mailing list signups only
if (($_POST) && ($_POST["action"] == "sub")) {
if ($_POST["email"] == "") {
header("Location: mailing_list_add.php");
exit;
} else {
// connect to database
doDB();
// filtering out anything that isn't an email address
if ( filter_var(($_POST["email"]), FILTER_VALIDATE_EMAIL) == TRUE) {
echo 'Success!';
} else {
echo 'Invalid Email Address';
exit;
}
// check that the email is in the database
emailChecker($_POST["email"]);
// get number of results and do action
if (mysqli_num_rows($check_res) < 1) {
// free result
mysqli_free_result($check_res);
// cleans all input variables at once
$email = array_map("mysqli_real_escape_string", ($_POST["email"]));
// add record
$add_sql = "INSERT INTO subscribers (email)
VALUES('".$_POST["email"]."')";
$add_res = mysqli_query($mysqli, $add_sql)
or die(mysqli_error($mysqli));
$display_block = "<p>Thanks for signing up!</p>";
// close connection to mysql
mysqli_close($mysqli);
} else {
// print failure message
$display_block = "You're email address, ".$_POST["email"].", is already subscribed.";
}
}
}
?>
<html>
<?php echo "$display_block";?>
</html>
You're treating $_POST['email'] as an array, which it probably ins't.
If you only intended to escape email, do
$email = mysqli_real_escape_string($dbConn, $_POST['email']);
Then in your INSERT statement, use the escaped $email instead of $_POST['email']
$add_sql = "INSERT INTO subscribers (email) VALUES('$email')";
array_map() is meant for arrays. If all you have is a single value then just call the function directly.
There is at least one bug, here:
// Does not work because $_POST["email"] is a string, not an array
$email = array_map("mysqli_real_escape_string", ($_POST["email"]));
This looks like something you adapted from code that was working, but right now it's broken. You probably wanted something like this:
$post = array_map("mysqli_real_escape_string", $_POST["email"]);
after which you can use $post["email"] safely, as it has been escaped.
Of course escaping everything inside $_POST is possibly not the best way to go about this. There's still the mundane but spot-on way to consider:
$email = mysqli_real_escape_string($_POST['email']);
This is apparently not mysqli_real_escape_string problem but array_map() problem. Or rather misuse of the latter one.
However, you will face mysqli_real_escape_string() problem as soon as you solves this one.
To solve this latter your doDB() function have to return connection id, which you have to use with every mysqli_* function.
$conn = doDB();
$email = mysqli_real_escape_string($conn,$_POST["email"]);
thus you will have all your [listed] problems solved but I believe that emailChecker will may cause the same kind of problem of inexistent $check_res variable. Instea d of which such a function apparently have to return just a boolean and used like
if (!emailChecker($_POST["email"])) {