Stripslashes() not working in email - php

Right now I'm trying to make an email notification whenever somebody submits a comment going into a database. I'm using mysql_real_escape_string() to protect against injections and I'm trying to strip the slashses off the name, email, and comment when they are sent in the email notification. The database entry code is commented out, as I don't want there to be an entry made every time I test the email system.
The email is sent just fine, however stripslashes() is not working properly. For example, if the message is "Can't wait!" the email will have "Comment: Can\'t wait!". This is strange to me because when I have the comments displayed on the page, stripslashses works fine.
Is this because I'm not applying stripslashes() to data not coming directly out of the database?
$li = mysql_connect($dbHost, $dbUser, $dbPass) or die("Could not connect");
mysql_select_db($dbDatabase, $li) or die ("could not select DB");
$name = mysql_real_escape_string($HTTP_POST_VARS["name"]);
$email = mysql_real_escape_string($HTTP_POST_VARS["email"]);
$comment = mysql_real_escape_string($HTTP_POST_VARS["comment"]);
$date = Date("Y-m-d h:i:s");
/*
$gb_query = "insert into entries
values(0, '$name', '$email', '$comment', '$date')";
mysql_query($gb_query);
$res = mysql_affected_rows();
// See if insert was successful or not
if($res > 0) {
$ret_str="Your guestbook entry was successfully added!";*/
$name2=stripslashes($name);
$email2=stripslashes($email);
$comment2=stipslashes($comment);
$subject = 'New Guestbook Entry Has been Added!';
$message = "Name: $name2\nEmail: $email2\nComment: $comment2";
$to = "chetg329#yahoo.com";
mail($to, $subject, $message);
//header('Location: guestbook.php?ps=1');
//exit(); // End the request
/*
} else {
$ret_str = "There was a problem with your guestbook entry. Please try again.";
}
// Append success/failure message
$gb_str .= "<span class=\"ret\">$ret_str</span><BR>";*/
mysql_close();

My guess is that the problem lies within magic_quotes. I would take a look at your php.ini and see if you can turn it off (pending you are not relying on it to prevent SQL Injection). If you cannot access the php.ini to turn it off PHP provides a method for you to test it and act accordingly (IE stripslashes on the data before escaping it with mysql_real_escape_string ) It is called get_magic_quotes_gpc
Alternatively, why are you using mysql_real_escape_string on data that is not being inserted into the database? If you do insert it later on, then move those calls till after the mail call.

Related

how do i get user seesion data and insert it to another table

I want to get the user's (currently logged in) email and his/her uid from database table then insert it into another table. I have tried but i am getting blank results that is in to the uid and email.
<?php
session_start();
if(isset($_POST['button'])){
$bidamount = $_POST['bidamount'];
$email = $_SESSION['$u_email'];
$uid = $_SESSION['$u_uid'];
//TO ALERT SUBMISSION OF BLANK FIELDS(IT DOESN'T PREVENT SUBMISSION OF BLANK FIELD THOUGH)
if (!$bidamount){
echo "can't submit blank fields";
}
//TO CONFIRM YOU ARE CONNECTED TO YOUR DATABASE (OPTIONAL)
$connection = mysqli_connect('localhost', 'root', '', 'tickmill_auctions');
if ($connection){
header ("Location: ../Afterlogin.php?action=success");
}else{
die("connection failed");
}
//TO INSERT username and password from field to jossyusers database
$query = "INSERT INTO orders(bidamount,email,uid) VALUES('$bidamount','$email','$uid')";
$result = mysqli_query($connection, $query);
if(!$result){
die("OOPPS! query failed".mysqli_error($connection));
}
}
?>
This looks wrong as I see no variables in your script with the names $u_email and $u_uid
$email = $_SESSION['$u_email'];
$uid = $_SESSION['$u_uid'];
Remove the $ signs and try
$email = $_SESSION['u_email'];
$uid = $_SESSION['u_uid'];
Alternatively if you do in fact have these variables set up use double quotes instead of single quotes like this
$email = $_SESSION["$u_email"];
$uid = $_SESSION["$u_uid"];
WARNING: Your script is wide open to SQL Injection Attack
Even if you are escaping inputs, its not safe!
Use prepared parameterized statements
Also while testing, add
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
to the top of your script. This will force any mysqli_ errors to
generate an Exception that you can see on the browser and other errors will also be visible on your browser.

INTRO-LVL PROGRAMMER: Verify & Execute Guidance in PHP/MySQL

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.

Data not inserting in MySQL

I am making a script for a guy and he uses Advanced Outgoing API (not familiar). He gives me this URL where the POST variable will be stored in http://example.com/your_script.php?email_address={u_email}&firstname={u_firstname}. So here is my php code. The problem is it cannot read the post values. When I echo it, it's empty.
NOTE: This is the instruction from the API Manual.
Advanced Outgoing API
You can have up to 5 URLs for each Product/Podcast/RSS Feed/Membership be notified whenever a subscriber event happens. You can enter these URLs by clicking on "Edit Notifications/Custom Fields" for a particular item. The system will then POST the following variables to the URLs you've entered. You can also include any of the variables below as a "tags" in your URL and the system will replace the tag with the actual value. This way you can post the values to an existing script that expects a variable name to be different than the ones listed below. For example, your notification URL could be: http://example.com/your_script.php?email_address={u_email}&firstname={u_firstname} . The system would then post all the variables below to: http://example.com/your_script.php?email_address=joe#example.com&firstname=Joe
$con = mysql_connect("localhost","xyz","xyz","xyz"); // Establish connection to insert in the first table.
$username = $_POST['paypal_email']; // username of the user.
$rawpass = $_POST['access_code']; // Raw password.
$pass = md5($rawpass); // Password of the user encrypted with md5.
$email = $_POST['email_address']; // E-mail of the user.
$time = date("Y-m-d H:i:s");
echo $username;
echo $pass;
echo $email;
echo $time;
mysql_query("INSERT INTO wpinrootusers ('user_login', 'user_pass', 'user_email', user_registered, 'user_status') VALUES ('$username', '$pass', '$email', '$time', 0), $con"); // Insertion into wpinrootusers table.
mysql_close($con); // Close connection.
$con = mysql_connect("localhost","xyz","xyz","xyz"); // Establish connection to insert in the second table.
mysql_query("INSERT INTO customers ('receipt', 'prod_num', 'email') VALUES ('$rawpass', '6', '$email')", $con); // Insertion into customers table.
mysql_close($con); // Close second connection.
With mysql you have to do:
$con = mysql_connect("localhost","xyz","xyz");
and then select the database:
$db = mysql_select_db("xyz");
The code you used to connect to database works with mysqli (i stands for improved) and you should consider switching from mysql to mysqli
When you send the variable as GET parameters you have to use $_GET of course.

mysqil_real_escape_string() error I can't fix

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"])) {

Form processing causing apache to crash?

I use the following code to register users on my site. The problem is that when a user registers apache doesn't respond and crashes.
Is there a break in my code or something I am doing wrong????
<?php
include ('../includes/db_connect.php');
$firstname = $_POST['firstname'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = md5($_POST['password']);
// lets check to see if the username already exists
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");
$username_exist = mysql_num_rows($checkuser);
if($username_exist > 0){
echo "I'm sorry but the username you specified has already been taken. Please pick another one.";
unset($username);
//include 'register.html';
exit();
}
// lf no errors present with the username
// use a query to insert the data into the database.
$query = "INSERT INTO users (firstname, email, username, password)
VALUES('$firstname', '$email', '$username', '$password')";
mysql_query($query) or die(mysql_error());
mysql_close();
echo "You have successfully Registered";
// mail user their information
//$yoursite = ‘www.blahblah.com’;
//$webmaster = ‘yourname’;
//$youremail = ‘youremail’;
//
//$subject = "You have successfully registered at $yoursite...";
//$message = "Dear $firstname, you are now registered at our web site.
// To login, simply go to our web page and enter in the following details in the login form:
// Username: $username
// Password: $password
//
// Please print this information out and store it for future reference.
//
// Thanks,
// $webmaster";
//
//mail($email, $subject, $message, "From: $yoursite <$youremail>\nX-Mailer:PHP/" . phpversion());
//
//echo "Your information has been mailed to your email address.";
?>
this script will NOT cause apache to die. on this side theres nothing wrong with it.
however i dont know whats in db_connect.php
the mailing is deactivated, this indeed could take a very long time if the server settings are not correctly. e.g. if the server cant find its fully qualified domain name as your comments suggests.
do you have a session active? this could explain why you cant access any website while the other one is still running and sending the mail and it may look to you like apache crashed.
because you didnt call session_write_close and only once session can be active for writing at a time.
whats definately wrong is the vulnerability to mysql injection.
you absolutely need to change your variables the following way:
$firstname = mysql_real_escape_string($_POST['firstname']);
$email = mysql_real_escape_string($_POST['email']);
$username = mysql_real_escape_string($_POST['username']);
furthermore i would recommend just having a unique que on username and try the insert and see whether you get an error or if you get an mysq_insert_id. let mysql do the job.
but your check is fine too.. but you should have a constraint in the database too, just as a precaution.
and you should trim your values and maby allow only certain chars, its annoying if a username on a website is &%DTRFG$Ä←↓ff

Categories