Issue with sending information from contact form - php

I am trying to send the values from a php form as email. When I set the $message to var_export($_POST,true); it exports the information but not in a easily readable way.
I have tried to set the values for each one as $complain_detail = $_POST['complain_detail']; but it stops the page from working or does not send the email.
<?php
include 'main.php';
check_loggedin($pdo);
// output message (errors, etc)
$msg = '';
if ($_POST['submit']) {
if ($_POST['complain_type'] == null || $_POST['complain_title'] == null || $_POST['complain_issue_type'] == null || $_POST['complain_form'] == null || $_POST['complain_assigned_to'] == null || $_POST['complain_detail'] == null) {
$msg = "Something missing, please input all required information.";
} else {
$stmt = $pdo->prepare('INSERT IGNORE INTO complains (id, complain_type, complain_from, complain_assigned_to, complain_title, complain_detail, complained_date, complain_issue_type, complain_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
$status = $stmt->execute(["", $_POST['complain_type'], $_POST['complain_form'], $_POST['complain_assigned_to'], $_POST['complain_title'], $_POST['complain_detail'], date("Y-m-d H:i:s"), $_POST['complain_issue_type'], "Open"]);
$complain_id = $pdo->lastInsertId();
$incident_record = $pdo->prepare('INSERT IGNORE INTO incident_record (id,complain_id, user_id, issue_date, assign_to, assign_by_client, record_type, record_details) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
$status = $incident_record->execute(["", $complain_id , $_SESSION['id'], date("Y-m-d H:i:s"), $_POST['complain_assigned_to'], $_POST['complain_form'], 'Created' , 'Complain Title: ' . $_POST['complain_title'] . ', Complain Details : ' . $_POST['complain_detail'] . ', Complain Issue Type : ' . $_POST['complain_issue_type']. ', Open' ]);
$to_email = 'email#sdf.coms';
$subject = 'New Incident Logged';
$message = var_export($_POST,true);
$headers = 'From: email#sdf.coms';
mail($to_email,$subject,$message,$headers,"-f email#sdf.coms");
$msg = "Incident has been loggged.";
}
} else {
$msg = "Whoops, something went wrong - Please try again.";
}
?>
Currently format is been sent as
array ( 'complain_type' => 'WASP', 'complain_title' =>
'Test', 'complain_assigned_to' => '9', 'complain_issue_type' =>
'Support', 'complain_form' => '9', 'complain_detail' => 'Is this
better?', 'submit' => 'Submit Issue', )
I would like to to read as
"A ticket has been opened under "type" and has been assigned to "user"
"with description!

$_POST is an array, containing the request elements. Let's try to visualise it together...
If you have this HTML:
<form action="action.php" method="post">
<p>Your name: <input type="text" name="name" /></p>
<p><input type="submit" /></p>
</form>
And this action.php file:
<?php var_dump($_POST);?>
The output will be the following:
array(1) { ["name"]=> string(1) "1" }
So, in order to access the name value within the array, I need to call for $_POST["element"] where your element is the HTML name of the request parameter.
So, if in your HTML, the message is obtained with the following input:
<input type="text" name="message" />
In order to properly retrieve it in your PHP code, you need to adjust the $message variable to be the following:
$message = $_POST["message"];
Thus, you can concatenate your request parameters into your message variable like this:
$message = "A ticket has been opened under " . $_POST["complain_type"] . " and has been assigned to user " . $_POST["complain_assigned_to"] . " with description " . $_POST["complain_detail"];

Related

Why is my statement always false? if (isset($_GET['action']) && $_GET['action']=='IPN_Handler')

I wrote an IPN listener for PayPal and when I first did it everything worked fine. I am not sure why, it stopped working. My Instant Payment Notification is set to: https://domainname/webpage/?action=IPN_Handler
Auto return for website payments url is: https://domainname/webpage
My Listener code is:
if (isset($_GET['action']) && $_GET['action']=='IPN_Handler') {
echo "Thank you for your payment";
$amt = $_GET['amt'];
$txn_id = $_GET['tx'];
$st = $_GET['st'];
$msg = $_GET['item_name'];
$date= date("Y-m-d");
}
Once the code returns the page has this in the location area:
Link
I added a var_dump on the if statement and it returns bool(false).
What am I doing wrong with my code?
Thanks for hearing me, Let me explain you how to upgrade prepare statement espacily in a payment process.
I dont have all your data so I will do it with what you showed in question.
Here is a simple prepare statement, hope it will help you.
$conn is db connection field change it to yours
if (isset($_POST['action']) && $_POST['action']=='IPN_Handler') {
// we get all params from html form I use post method always if dont need to get a url paratemer
$amt = htmlspecialchars($_POST['amt']);
$txn_id = htmlspecialchars($_POST['tx']);
$st = htmlspecialchars($_POST['st']);
$msg = htmlspecialchars($_POST['item_name']);
$date= date("Y-m-d");
//Here we need to validate form inputs
if(empty($amt) || empty($txn_id) || empty($st) || empty($msg)) {
echo "Field all required";
}else{
$stmt = $conn->prepare("INSERT INTO Your_table_name (amt, tx, st, item_name, date) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss", $amt, $txn_id, $st, $msg, $date);
// we used bind_param so now we need to execute
if($stmt->execute()){
echo "New records created successfully";
header('Location: yourpage.php');
exit();
}else{
echo "Failed to insert new records in database.";
}
// Free yourconnection
$stmt->free_result();
}
}
UPDATE :
Tested working on my case here is html form :
<form action="page.php" method="POST">
<input type="text" name="amt" placeholder="dsdsd">
<input type="text" name="tx" placeholder="sdsd">
<input type="text" name="st" placeholder="dsdsd">
<input type="text" name="item_name" placeholder="sdsd">
<input type="text" name="date" placeholder="dsdsd">
<input type="hidden" name="action" value="IPN_Handler" />
<input type="submit" name="LoginBtn" placeholder="signup">
</form>
For more explanition see here https://www.w3schools.com/php/php_mysql_prepared_statements.asp
Here is where I modified your code:
if (isset($_GET['action']) AND $_GET['action']=='IPN_Handler') {
//Here we need to validate form inputs
$amt = mysqli_real_escape_string($link, $_GET['amt']);
$txn_id = mysqli_real_escape_string($link, $_GET['tx']);
$st = mysqli_real_escape_string($link, $_GET['st']);
$msg = mysqli_real_escape_string($link, $_GET['item_name']);
$date= date("Y-m-d");
$sql = "UPDATE wp_ready2_play SET amount=?, payment_id=?, payment_status=?, message=?, payment_dte=? WHERE id =?";
$stmt = mysqli_stmt_init($link);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL error";
} else {
mysqli_stmt_bind_param($stmt, "ssssss", $amt, $txn_id, $st, $msg, $date, $data);
mysqli_stmt_execute($stmt);
echo "Thank you for your payment";
echo "Transaction has been made successfully.";
}
// Free yourconnection
mysqli_free_result($stmt);
}
The statement is always false because... the statement is always false. Look at the query string:
?amt=0.01&cc=USD&item_name=Subscription%20-%20214&st=Completed&tx=6PK91382LD487075H
There is no action item set anywhere, so the code execution correctly skips the block. You need to actually pass in the action, and it's associated value somehow for the code to execute like you expect.
The easiest, lowest-effort way of doing this is to simply add a hidden input inside the form.
<input type="hidden" name="action" value="IPN_Handler" />
When you submit the form, you should then see the new query string include the action parameter with the specified value, as action=IPN_Handler. You should be careful to verify the action value though, as users can manipulate hidden inputs simply by opening the developer tools.

JSON not properly inserting into mysql through php

I have been trying to insert data from a json file into mysql through php.
I have a function doing the insert in one file, while the decoding is done in another file.
When I run the code, I recieve this error:
You could not be registered due to a system error. We apologize for any inconvenience.
Column 'password' cannot be null
Query: INSERT INTO users (id, email, password, username, deviceId, date_created) VALUES (null, ?, ?, ?, ?, NOW() )
Query was executed
enter code here
Here are my three files:
insertion.php:
//Require files
require('functions.php');
if(file_exists('data.json')){
echo "The file exists ";
$file= file_get_contents('data.json');
echo json_encode('data.json');
$data=json_decode($file, true);
var_dump($data);
$email= $data["email"];
$password= $data["password"];
$username= $data["username"];
$deviceId= $data["deviceId"];
$tableName= 'users';
$email= "email#example.com";
$error=json_last_error();
echo "<br><br>";
echo "your email shoudl be displayed right here: ".$email. "This is email";
echo "<br>JSON Errors will display here:". $error;
$execute= dataInsert($tableName, $email, $password, $username, $deviceId);
if($execute){
echo "Query was executed";
}
}
else{
echo "file does not exist";
}
functions.php:
//------------------------dataInsert()---------------------------//
function dataInsert($tableName, $email, $password, $username, $deviceId){
//set database connection
require('mysqli_connect.php');
if($dbc){
echo "<h3>connection successful</h3>";
}
//form query using the values and tablename
$query = "INSERT INTO users (id, email, password, username, deviceId, date_created)
VALUES (null, ?, ?, ?, ?, NOW() )";
//Prepare statement
$stmt= mysqli_prepare($dbc, $query);
//Bind the variables
mysqli_stmt_bind_param($stmt, 'sssi', $email, $password, $username, $deviceId);
//Execute the query
$result=mysqli_stmt_execute($stmt);
if($result){
echo "Success !";
}
else{
// Public message:
echo 'System Error
<p class="error">You could not be registered due to a system error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $query . '</p>';
}
mysqli_close($dbc); // Close the database connection.
return true;
}
data.json
<pre>
<code>
{"users":[
{
"email":"fakeemail#gmail.net",
"password":"mypass12",
"username":"myusername",
"deviceId":"21"
}
]}
When I use var_dump to display the json array, it looks correct:
"data.json"array(1) { ["users"]=> array(1) { [0]=> array(4) { ["email"]=> string(19) "fakeemail#gmail.net" ["password"]=> string(6) "mypass12" ["username"]=> string(13) "myusername" ["deviceId"]=> string(2) "21" } } }
I've been able to insert rows into the database, but they were all blank, besides the date, and auto increment id. When I set $email= email#example.com it will display the password cannot be null, but commenting that line out will cause the error to display 'email' cannot be null
You are inserting null into your ID field. Try removing that.
You are accessing the values of the decoded json string wrongly, passing true as the second value of json_decode you get one associative array.
var_dump($data['users'][0]['email']);
Result
fakeemail#...
So you could do something like
if (count($data['users']))
{
foreach($data['users'] as $user)
{
// insert query passing
// $user['email'], $user['password'],
print $user['email'];
}
}

Adding data to database

When I try to add a user to the database with POST a new user is added but all fields are Null.
Any help guys ? Thank you in advance.This is my source code:
if($_SERVER['REQUEST_METHOD'] == "POST")
{
// Get data
$name = isset($_POST['name']) ;
$email = isset($_POST['email']);
$password = isset($_POST['password']);
$status = isset($_POST['status']);
// Insert data into data base
$sql = "INSERT INTO users (`name`, `email`, `password`, `status`) VALUES ('$name', '$email', '$password', '$status')";
$qur = mysql_query($sql);
if($qur){
$json = array("status" => 1, "msg" => "Done User added!");
}else{
$json = array("status" => 0, "msg" => "Error adding user!");
}
}else{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
**
isset return only true or false so if you want to insert value you can check it with if condition replace your code with above it will be work fine
if($_SERVER['REQUEST_METHOD'] == "POST"){
$name = (isset($_POST['name']))?$_POST['name']:'' ;
$email = (isset($_POST['email']))?$_POST['email']:'';
$password = (isset($_POST['password']))?$_POST['password']:'';
$status = (isset($_POST['status']))?$_POST['status']:'';
$sql = "INSERT INTO users (`name`, `email`, `password`, `status`) VALUES ('$name', '$email', '$password', '$status')";
$qur = mysql_query($sql);
if($qur){
$json = array("status" => 1, "msg" => "Done User added!");
}else{
$json = array("status" => 0, "msg" => "Error adding user!");
}
}else{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
header('Content-type: application/json');
echo json_encode($json);
save this form in html file and check it with this edited example
<form method="post">
<input type="text" name="name" value="Red Symbol" />
<input type="text" name="email" value="red#symbol.com" />
<input type="text" name="password" value="chock" />
<input type="text" name="status" value="1" />
<input type="submit" name="submit" value="Submit" />
</form>
You are not checking if any of the fields are empty.
You need to do that, and only perform the query if they are not.
You can also restructure your code to avoid nested if/else:
function sendJson($data){
header('Content-type: application/json');
echo json_encode($data);
//stop execution after sending response
exit;
}
//if not POST request, exit
if($_SERVER['REQUEST_METHOD'] !== "POST") {
sendJson(["status" => 0, "msg" => "Request method not accepted"]);
}
//default data
$defaults = [
'name' => false,
'email' => false,
'password' => false,
'status' => false,
];
$input = array_intersect_key(array_merge($defaults, $_POST), $defaults);
//if empty field, exit
if(in_array(false, $input)){
sendJson(["status" => 0, "msg" => "All fields are required"]);
}
// Insert data into data base
//you REALLY REALLY need to use PDO/MYSQLI with prepared statements, this code is dangerous
$sql = "INSERT INTO users (`name`, `email`, `password`, `status`) VALUES ('$input[name]', '$input[email]', '$input[password]', '$input[status]')";
$qur = mysql_query($sql);
//if query failed, exit
if(!$qur){
sendJson(["status" => 0, "msg" => "Error adding user!"]);
}
//if we get here, all is OK
sendJson(["status" => 1, "msg" => "Done User added!"]);
#mysql_close($conn);

Prevent users to edit eachother entries

I have a PHP script that allow users to register entries to a database. Entries are autoincremented. What I found out, is that user #A can get an entry from user #B by changing url from edit.php?id=2 to id=1.
Of course I want to prevent that. So my idea: if the user ID field in the mysql entry matches $_SESSION['user_id'] in my php script, editing is allowed.
A user should only be able to edit entries they have posted themselves.
What would be the best and most efficient way to achieve this?
<?php $bruker = $_SESSION['user_id']; ?>
<?php }
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['id']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id']))
{
// get variables from the URL/form
$id = $_POST['id'];
$elv = htmlentities($_POST['elv'], ENT_QUOTES);
$vald = htmlentities($_POST['vald'], ENT_QUOTES);
$art = htmlentities($_POST['art'], ENT_QUOTES);
$dato = htmlentities($_POST['dato'], ENT_QUOTES);
$vekt = (int)$_POST['vekt'];
$lengde = (int)$_POST['lengde'];
$flue = htmlentities($_POST['flue'], ENT_QUOTES);
$gjenutsatt = (int)$_POST['gjenutsatt'];
$kjonn = (int)$_POST['kjonn'];
$bilde = htmlentities($_POST['bilde'], ENT_QUOTES);
$user = $_SESSION['user_id'];
// check that required fields are not empty
if ($elv == '' || $vald == '' || $art == '' || $dato == '' || $vekt == '' || $kjonn == '')
{
// if they are empty, show an error message and display the form
$error = 'Du må fylle ut de påkrevde feltene!';
renderForm($elv, $vald, $art, $dato, $vekt, $lengde, $flue, $gjenutsatt, $kjonn, $bilde, $user, $error, $id);
}
else
{
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE fisk SET elv = ?, vald = ?, art = ?, dato = ?, vekt = ?, lengde = ?, flue = ?, gjenutsatt = ?, kjonn= ?, bilde = ?, user = ?
WHERE id=?"))
{
$stmt->bind_param("ssssiisiisii", $elv, $vald, $art, $dato, $vekt, $lengde, $flue, $gjenutsatt, $kjonn, $bilde, $user, $id);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: /");
}
}
// if the 'id' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else
Assuming your users have unique ID's you can simply add additional WHERE clause to your SQL:
if ($stmt = $mysqli->prepare("UPDATE fisk SET elv = ?, vald = ?, art =
?, dato = ?, vekt = ?, lengde = ?, flue = ?, gjenutsatt = ?, kjonn= ?,
bilde = ?, user = ?
WHERE id=? AND created_user = ?"))
Obviously replace created_user with the column you use to store the users ID who created the entry.
That way it will only ever update a row created by the user trying to edit it.
More securely, you could prevent them from ever seeing the page by first querying the created user id of the row in question then checking it against your user id $_SESSION as you suggest - then killing the script or redirecting them before it ever gets to the query.

PHP Mysql query, No Error, Wont Insert Row

The form submits correctly and it sends me an email. No error is reported and the SQL it creates works fine, I tested it at phpMyAdmin. mysql_error() raises nothing, it just doesn't add a row. Can anyone see what's going on?
<?PHP
$to = "me#gmail.com";
$subject = "New Lead";
$date = date ("l, F jS, Y");
$time = date ("h:i A");
$mysql = mysql_connect("db.perfora.net:3306","db","password");
if(!$mysql)
{
die("Could Not Connect: ".mysql_error());
}
mysql_select_db("db",$mysql);
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$name = $_POST['firstname']." ".$_POST['lastname'];
$email = $_POST['email'];
$phone = "(".$_POST['areacode'].") ".$_POST['firstthree']."-".$_POST['lastfour'];
$area = $_POST['area'];
$lookdate = $_POST['lmm']."/".$_POST['ldd']."/".$_POST['lyyyy'];
$lookdatedb = date("{$_POST['lmm']}.{$_POST['ldd']}.{$_POST['lyyyy']}");
$movedate = $_POST['mmm']."/".$_POST['mdd']."/".$_POST['myyyy'];
$movedatedb = date("{$_POST['mmm']}.{$_POST['mdd']}.{$_POST['myyyy']}");
$loft = $_POST['loft'] ? "loft" : "";
$highrise = $_POST['highrise'] ? "highrise" : "";
$traditional = $_POST['traditional'] ? "traditional" : "";
$price = $_POST['price'];
$comments = $_POST['comments'];
$sql = "INSERT INTO Leads
(Name, Email, Phone, Area, LookDate, MoveDate, Loft, HighRise, Traditional, Price, Comments)
VALUES
('$name', '$email', '$phone', '$area', '$lookdatedb', '$movedatedb', '{$_POST['loft']}', '{$_POST['highrise']}', '{$_POST['traditional']}', '$price', '$comments')";
if (mysql_query($sql,$con))
{
echo "Row added.";
}
else
{
echo "Error adding row: " . mysql_error();
echo("\n\n".$sql);
}
$msg = "
New Lead Submitted On $date at $time.\n\n
Name: $name\n
Email: $email\n
Phone: $phone\n
Area: $area\n
Look Date: $lookdate\n
Move Date: $movedate\n
Type: $loft $highrise $traditional \n
Price: $price\n
Comments: $comments\n
";
}
mysql_close($mysql);
mail($to, $subject, $msg, "From:$email");
if ($forward == 1) {
header ("Location:$location");
}
else {
echo "Thank you for submitting our form. We will get back to you as soon as possible.";
}
?>
Response:
Thank you for submitting our form. We will get back to you as soon as possible.
Generated SQL:
INSERT INTO Leads (Name, Email, Phone, Area, LookDate, MoveDate, Loft, HighRise, Traditional, Price, Comments) VALUES ('work work', 'work#work.com', '(214) 131-4131', 'dallas', '02.18.2010', '02.25.2010', '', '1', '1', '$333333333333333333', '33fdsdfsdfsd')
Database Structure:
http://imgur.com/iQHRk.jpg
Let's see, your DB connection handle is obviously referenced by $mysql, but you've done this:
if (mysql_query($sql,$con))
Your DB handler is wrong.
mysql_query($sql,$con);
should return something why don't you take a look at that
i.e.
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
It's a best practice to check for errors when you can.
Also to be noted, you are not escaping any of the user input so your code is vulnerable to SQL injections. please use mysql_real_escape_string.
take the post variable in another variable and then pass to the insert query i think it will be work
like this
$sql = "INSERT INTO Leads
(Name, Email, Phone, Area, LookDate, MoveDate, Loft, HighRise, Traditional, Price, Comments)
VALUES
('$name', '$email', '$phone', '$area', '$lookdatedb', '$movedatedb', '$loft', '$highrise', '$traditional', '$price', '$comments')";
mysql_query($sql);

Categories