I have a working PHP form that is taking data from a form in the backend of the website and inserting it into the SQL database applicable. My issue is, whenever I try and set it up so that it also send the data to an email address ( email captured in form & email defined ) I recieve Error 500.
Code is below:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("#", "#", "#", "#");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$name = mysqli_real_escape_string($link, $_POST['name']);
$initials = mysqli_real_escape_string($link, $_POST['initials']);
$item = mysqli_real_escape_string($link, $_POST['item']);
$issue = mysqli_real_escape_string($link, $_POST['issue']);
$tel = mysqli_real_escape_string($link, $_POST['tel']);
$email = mysqli_real_escape_string($link, $_POST['email']);
$cost = mysqli_real_escape_string($link, $_POST['cost']);
$loggedby = mysqli_real_escape_string($link, $_POST['loggedby']);
$bag = mysqli_real_escape_string($link, $_POST['bag']);
$charger = mysqli_real_escape_string($link, $_POST['charger']);
// attempt insert query execution
$sql = "INSERT INTO `repairs` (`name`,`initials`,`item`, `issue`, `telephone`,`email`, `cost`, `loggedby`, `bag`, `charger`) VALUES ('$name', '$initials', '$item', '$issue', '$tel', '$email', '$cost', '$loggedby', '$bag', '$charger')";
if(mysqli_query($link, $sql)){
header('location:repairs.php');
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
$to = "emailaddress#emails.co.uk,$email"
$subject= "Thankyou $name - Your repair has been logged"
$body= "<h2>Thankyou $name</h2> /n
This is a confirmation email regarding your $item /n
Your repair log is below: /n
$item /n
$issue /n/n
<h3>Accessories</h3> /n
bag - $bag /n
charger - $charger /n/n
Your repair was logged by $loggedby on echo date("d-m-Y"); /n/n
We will contact you on $tel & $email when your $item is ready to
collect.
/n/n
Loud Crowd IT - 01302 965482 /n
repairs#loudcrowdit.co.uk /n
www.loudcrowd.agency /n"
$mail ($to,$subject,$body);
// close connection
mysqli_close($link);
?>
Does anyone know why I receive the error?
Internal server error means there's an error in your server side script, in this case :
$to = "emailaddress#emails.co.uk,$email" // missing a semicolon
The missing semicolon above triggers Unexpected '$subject' (T_VARIABLE)
also here :
$subject= "Thankyou $name - Your repair has been logged"
this is the code you should use :
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("#", "#", "#", "#");
// Check connection
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$name = $_POST['name'];
$initials = $_POST['initials'];
$item = $_POST['item'];
$issue = $_POST['issue'];
$tel = $_POST['tel'];
$email = $_POST['email'];
$cost = $_POST['cost'];
$loggedby = $_POST['loggedby'];
$bag = $_POST['bag'];
$charger = $_POST['charger'];
// attempt insert query execution
$sql = "INSERT INTO `repairs` (`name`,`initials`,`item`, `issue`, `telephone`,`email`, `cost`, `loggedby`, `bag`, `charger`) VALUES (?,?,?,?,?,?,?,?,?,?)";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, 'ssssssssss', $name, $initials, $item, $issue, $tel, $email, $cost, $loggedby, $bag, $charger);
if (mysqli_stmt_execute($stmt)) {
$to = "emailaddress#emails.co.uk,$email";
$subject = "Thankyou $name - Your repair has been logged";
$body = "<h2>Thankyou $name</h2> /n
This is a confirmation email regarding your $item /n
Your repair log is below: /n
$item /n
$issue /n/n
<h3>Accessories</h3> /n
bag - $bag /n
charger - $charger /n/n
Your repair was logged by $loggedby on " . date("d-m-Y") . "/n/n
We will contact you on $tel & $email when your $item is ready to
collect.
/n/n
Loud Crowd IT - 01302 965482 /n
repairs#loudcrowdit.co.uk /n
www.loudcrowd.agency /n";
if (mail($to, $subject, $body)) {
header('location:repairs.php');
}
} else {
printf("Error: %s.\n", mysqli_stmt_error($stmt));
}
mysqli_close($stmt);
// close connection
mysqli_close($link);
?>
How to Fix the 500 Internal Server Error
500 Internal Server Error is a server-side error, meaning the problem probably isn't with your computer or internet connection but instead with the website's server.
While not probable, it is possible that there's something wrong on your end, in which case we'll look at some things you can try:
Reload the web page. You can do that by clicking the refresh/reload button, pressing F5 or Ctrl-R, or trying the URL again from the address bar.
Even if the 500 Internal Server Error is a problem on the web server, the issue might just be temporary. Trying the page again will often be successful.
Note: If the 500 Internal Server Error message appears during the checkout process at an online merchant, be aware that duplicate attempts to checkout may end up creating multiple orders - and multiple charges! Most merchants have automatic protections from these kinds of actions, but it's still something to keep in mind.
Clear your browser's cache. If there's a problem with the cached version of the page you're viewing, it could be causing HTTP 500 issues.
Note: Internal Server Errors are not often caused by caching issues, but I have, on occasion, seen the error go away after clearing the cache. It's such an easy and harmless thing to try, so don't skip it.
Delete your browser's cookies. Some 500 Internal Server Error issues can be corrected by deleting the cookies associated with the site you're getting the error on.
After removing the cookie(s), restart the browser and try again.
Troubleshoot as a 504 Gateway Timeout error instead.
It's not very common, but some servers produce a 500 Internal Server Error when in reality a more appropriate message based on the cause of the problem, is 504 Gateway Timeout.
Related
I have a script that posts form responses to a MySQL Database. However, it is on occasion posting twice to the table with seconds between each row.
Here is the handling script:
if (isset($_POST['SignIn']))
{
$Name = $_POST['Name'];
$Sleep = $_POST['Sleep'];
$Soreness = $_POST['Soreness'];
$Fatigue = $_POST['Fatigue'];
$Energy = $_POST['Energy'];
$Stress = $_POST['Stress'];
$Total = $Sleep + $Soreness + $Fatigue + $Energy + $Stress;
$Comments = $_POST['Comments'];
$sql = "
INSERT INTO
YDP_Wellbeing (Name, Sleep, Soreness, Fatigue, Energy, Stress, Total, Comments)
VALUES
('$Name', $Sleep, $Soreness, $Fatigue, $Energy, $Stress, $Total, '$Comments')";
if (mysqli_query($con, $sql))
{
$_SESSION['alert-type'] = 'success';
$_SESSION['alert-head'] = 'Welcome!';
$_SESSION['alert-body'] = 'Thank You <strong>' . $Name . '</strong> You\'re Response Has Been Submitted.';
header("location: index.php");
}
else
{
echo "Failed: " . mysqli_error($con);
}
}
Sometimes it posts once, other times it posts twice, so the issue is intermittent it would appear?
The most likely cause of the inconsistent behavior is the failure to stop the script after the redirect. Without adding die() or exit(), the script will continue to execute.
Since you've enclosed the section in an if clause that tests for a POST submission, I assume that if it fails the test it will present a form to be submitted. Since the script fails to terminate after the redirect, it will print the form again (and may or may not redirect).
Therefore what is likely happening is your user is submitting the form; and then upon seeing the same form presented after submission either
goes on his merry way,
resubmits the form, or
attempts to press the back button and resubmits the form accidentally
Your code is vulnerable to the followings Attacks
1.) sql injection Attack as you passed variable directly into sql queries. I have mitigated it using prepared statements
2.) Html Injections and XSS attack: you will need to ensure sanitization for form inputs. i used intval() for integers and strip_tags() for strings assuming that
you want to strip out dangerous html.
3.) session fixation attack. I also eliminate that using session _regenerate_id()
Here is your code Re written
<?php
$servername = "localhost";
$username = "db username goes here";
$pass = "your db password here";
$db_name = "your db name here";
// Create connection
$conn = new mysqli($servername, $username, $pass, $db_name);
// Check connection
if ($conn->connect_error) {
echo "Connection to db failed";
}
if(isset($_POST['SignIn'])) {
$Name = strip_tags($_POST['Name']);
$Sleep = intval($_POST['Sleep']);
$Soreness = intval($_POST['Soreness']);
$Fatigue = intval($_POST['Fatigue']);
$Energy = intval($_POST['Energy']);
$Stress = intval($_POST['Stress']);
$Total = $Sleep + $Soreness + $Fatigue + $Energy + $Stress;
$Comments = strip_tags($_POST['Comments']);
// prepare your data
// i stands for integers and s stands for string
$stmt = $conn->prepare("INSERT INTO YDP_Wellbeing (Name, Sleep, Soreness, Fatigue, Energy, Stress, Total, Comments) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("siiiiiis", $Name,$Sleep,$Soreness,$Fatigue,$Energy,$Stress,$Total,$Comments);
$stmt->execute();
if($stmt){
echo "data inserted successfully";
// create session
session_start();
// prevents session fixation attacks using session regenerate id
session_regenerate_id();
//
$_SESSION['alert-type'] = 'success';
$_SESSION['alert-head'] = 'Welcome!';
$_SESSION['alert-body'] = 'Thank You <strong>' . $Name . '</strong> You\'re Response Has Been Submitted.';
header("location: index.php");
}else{
echo "data insertion failed";
}
}
$stmt->close();
$conn->close();
?>
Here's the PHP code:
<?php
$servername = "***";
$username = "*****";
$password = "*****";
$database = "*****";
try {
$conn = new PDO('mysql:host='.$servername.';dbname='.$database, $username, $password);
console.log('yes!');
}
catch(PDOException $e) {
print "Error!:" . $e->getMessage(). "<br/>";
die();
}
if (isset($_POST['submit']))
{
//$name = $_POST['name'];
//$day = $_POST['day'];
//$acctName = $_POST['acctName'];
//$acctType = $_POST['acctType'];
//$location = $_POST['location'];
//$prospect = $_POST['prospect'];
//$notes = $_POST['notes'];
$name = 'sally sue';
$day = 'monday';
$acctName = 'Account Uno';
$acctType = 'Cold Call';
$location = 'Location';
$prospect = 'Prospect';
$notes = 'These are notes! Notey notey notes';
$order = "INSERT INTO `schedule`(`id`, `name`, `day`, `acctName`, `acctType`, `location`, `prospect`, `notes`) VALUES ('$name', '$day', '$acctName', '$acctType', '$location', '$prospect', '$notes')";
$stmt = $conn->prepare($order);
$stmt->execute();
}
?>
Here's the deal. I have an HTML form that I use jQuery to grab the variables, and AJAX to post the form to this PHP file. I feel confident that everything is fine up to the point where it gets to the PHP file.
I commented out the POST variables and hard-coded my own to make it a little simpler. I'm not getting a 500 Internal Server Error. I've ran my code through a PHP syntax validator (and fixed a billion errors haha). Obviously I'm still doing something wrong, but I cannot find it for the life of me. I'm hoping that someone here has some insight?
EDIT: Also, the username, password, database, and table name are ALL correct. I've double checked them several times. The only thing I'm not sure of is the server name, which is 'localhost' since the DB is on the same server as this web page.
EDIT 2: I've changed the MySql insert statement back to the original, which had the back ticks. I copied it straight from phpMyAdmin console on the server which it resides. It was that way originally, but I changed it due to desperation. It still is not updating my database. Any further ideas?
Thanks in advance!
Hi I am working on a simple php registration. But everytime I am submitting the registration page, i am getting a blank screen, no error, no display.
The code in my php file is :
<?php
if($_SERVER['REQUEST_METHOD']=="POST"){
$IP = //my hostname
$dbuser = "my user id";
$conn = new mysqli_connect($IP, $dbuser, "","my databse name");
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
$address = $_POST['address'];
$query = "SELECT email FROM user where email='".$email."'";
$result = mysqli_query($conn,$query);
$numResults = mysqli_num_rows($result);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // Validate email address
{
$message = "Invalid email address please type a valid email!!";
}
elseif($numResults>=1)
{
$message = $email." Email already exist!!";
}
else
{
mysqli_query("(insert into user(name,phone_number, email,pass1, pass2, address) values
('".$name."','".$phone."', '".$email."', '".$pass1."','".$pass2."','".$address."')");
echo $message = "Signup Sucessfully!!";
}
mysqli_close($conn);
}
print_r(error_get_last());
?>
there is no issue in establishing connection as i am using this connection method in other pages and they are working fine. Also i should specify that currently i am working on cloud 9 and my mysql database is on cloud9 itself.
please help me in undersstanding the trouble.
You say your line 42 has the insert query. I suppose you mean this query:
mysqli_query("(insert into user(name,phone_number, email,pass1, pass2, address) values
('".$name."','".$phone."', '".$email."', '".$pass1."','".$pass2."','".$address."')");
As your error says "2 parameters expected", you are missing here your connection parameter. You should have this:
mysqli_query($conn, "(insert into user(name,phone_number, email,pass1, pass2, address) values
('".$name."','".$phone."', '".$email."', '".$pass1."','".$pass2."','".$address."')");
Put this in on the first line of your script
ini_set('display_errors', '1');
This will then display the errors on the page and you will be able to see what is going wrong.
Also rather than the IP address try "localhost"
$conn = new mysqli_connect("localhost", $dbuser, "","my databse name");
If the database is on the same machine this may solve your problem.
Also your code is incredibly unsafe and will suffer from SQL injection. Please consider the following lines:
$email = $_POST['email'];
$query = "SELECT email FROM user where email='".$email."'";
Basically you put whatever the user is passing into your SQL statement. What if he enters "' OR 1; DROP TABLE user". You would lose all your data.
Please read about SQL injection and use PDO:
http://en.wikipedia.org/wiki/SQL_injection
http://php.net/manual/fr/book.pdo.php
I have an issue where a php page which runs twice, but it only runs twice when connecting through a proxy server. This code runs fine if the user doesn't connect through a proxy.
How do I fix this so that it will only run once, whether connecting through a proxy or not?
This php code is running within a Drupal CMS page, but independent of Drupal. The user gets to this page by clicking on a hyperlink.
Is it that I am using header to redirect the user to another page?
<?php
$userId = 0;
$userId = $_GET["userId"];
$userEmail = 0;
$userEmail = $_GET["userEmail"];
$userName = 0;
$userName = $_GET["userName"];
//connect to the database
$con = mysql_connect("HOSTNAME","USERNAME","PASSWORD");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
{
//echo "Connected.";
//echo "<br>";
}
mysql_select_db("formredirectdata", $con);
$userId = intval($userId);
mysql_query("INSERT INTO webforms
(userid, formisactive, formname, formtitle, shortdesc, confirmationlink) VALUES('$userId', '1', 'Form Name', 'Form Title', 'Short Description', 'Confirmation Link') ")
or die(mysql_error());
$newformnum = mysql_insert_id();
$recipientname = 0;
$recipientemail = 0;
$recipientname = "default" . $newformnum;
$recipientemail = $userEmail;
//send to the next script
header('Location: addtriggernewform.php?formnum2=' . $newformnum . '&recipientemail=' . $recipientemail . '&operator=(default)&inputname=(default)&triggervalue=(default)&userName=' . $userName);
?>
I later found out that the reason the query was getting processed twice is that I was logged into the website (Drupal based) in two different browsers with different user accounts. After logging out in one of the browsers then the query no longer gets processed twice. This must be a quirk involving Drupal and temporary internet files.
i have a PHP contact form that submits data, and an email...:
<?php
$dbh=mysql_connect ("localhost", "username", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("guest");
if (isset($_POST['submit'])) {
if (!$_POST['name'] | !$_POST['email'])
{
echo"<div class='error'>Error<br />Please provide your Name and Email Address so we may properly contact you.</div>";
}
else
{
$age = $_POST['age'];
$name = $_POST['name'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
$query = "INSERT INTO contact_us (age,name,gender,email,phone,comments)
VALUES ('$age','$name','$gender','$email','$phone','$comments')";
mysql_query($query);
mysql_close();
$yoursite = "Mysite ";
$youremail = $email;
$subject = "Website Guest Contact Us Form";
$message = "$name would like you to contact them
Contact PH: $phone
Email: $email
Age: $age
Gender: $gender
Comments: $comments";
$email2 = "my#email.com";
mail($email2, $subject, $message, "From: $email");
echo"<div class='thankyou'>Thank you for contacting us,<br /> we will respond as soon as we can.</div>";
}
}
?>
The email is coming through fine, but the data is not storing the dbase... am i missing something?
Its the same script as i use on another contact us page, only difference is instead of parsing the data on teh same page, i now send this data to a "thankyou.php" page... i tried changing $_POST to $_GET but that killed the page... what am i doing wrong?
First of all, you must escape your data before injecting them in your SQL query.
This can be done using the mysql_real_escape_string function, like this :
$name = mysql_real_escape_string($_POST['name']);
// ... same for other fields that contain strings
$comments = mysql_real_escape_string($_POST['comments']);
This will ensure that quotes in your data are escaped, and don't mess with the ones that are arround the fields' data in the SQL query, first.
And, second, this will help you prevent SQL Injections.
Also, in case of an error during the execution of a query, mysql_query will return false -- which means you should test the value returned by that function -- to possibly log the cause of the error :
$result = mysql_query($query);
if ($result === false) {
// An error has occured...
echo mysql_error();
}
Note : here, I just displayed the error message -- but you should instead log the error somewhere (to a file, for instance), before putting your application to production : your users don't need (nor want) to see any technical error message !
Check the result from mysql_query(...) to see if it failed or not. If it didn't fail, MySQL should definitely have stored the information for you.