I didn't find an answer so im asking you guys.
window.location.reload() constantly reloads without a break.
I'm trying to make something that checks if the form has no input in it, and if doesn't I want it to make an alert, it's working but it reloads constantly. Here's my code:
<?php
$from = $_POST['email_adress'];
$subject = $_POST['subject'];
$select = $_POST['select'];
$message2 = $_POST['message2'];
$name = $_POST['firstname'];
$name2 = $_POST['lastname'];
if ($_POST['firstname'] == "") {
echo '<script language="javascript">';
echo 'alert("First Name is Mandatory.");';
echo 'window.location.reload("contactus.html");';
echo '</script>';
exit;
}
elseif ($_POST['subject'] == "") {
echo '<script language="javascript">';
echo 'alert("Subject is Mandatory.");';
echo 'window.location.reload("contactus.html");';
echo '</script>';
exit;
}
elseif ($_POST['email_adress'] == "") {
echo '<script language="javascript">';
echo 'alert("Email Adress is Mandatory.");';
echo 'window.location.reload("contactus.html");';
echo '</script>';
exit;
}
elseif ($_POST['message2'] == "") {
echo '<script language="javascript">';
echo 'alert("A Message is Mandatory.");';
echo 'window.location.reload("contactus.html");';
exit;
echo '</script>';
exit;
} else {
header("Location: contactus.html");
$email_subject = "A submittion form";
$to ="sudaiguy1#gmail.com";
$headers = "From: sudaiguy1#gmail.com";
$email_body = 'You have been contacted by $name $name2 and his email is $from. \n The message he wanted to say was in the general subject of $select and more specifically $subject and the message is $message2';
mail($to,$email_subject,$email_body, $headers);
}
?>
Maybe this can be an inspiration?
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$is_redirect = isset($_SESSION['to']);
if ($is_redirect && !is_mail_valid($_SESSION)) {
$to = $_SESSION['to'];
$subject = $_SESSION['subject'];
$body = $_SESSION['body'];
}
$_SESSION = array();
} else {
if (is_mail_valid($_POST)) {
$to = $_POST['to'];
$subject = $_POST['subject'];
$body = $_POST['body'];
mail($to, $subject, $body);
} else {
$_SESSION = $_POST;
}
header("Location: index.php");
exit;
}
function is_mail_valid($mail) {
global $errors;
global $valid;
$errors = array();
if (trim($mail['to']) == FALSE) { $errors['empty_to'] = TRUE; }
if (trim($mail['subject']) == FALSE) { $errors['empty_subject'] = TRUE; }
if (trim($mail['body']) == FALSE) { $errors['empty_body'] = TRUE; }
$valid = empty($errors);
return $valid;
}
?>
<?php if (!$valid) { ?>
<script type="text/javascript">
<?php if ($errors['empty_to']) {?>
alert('To: cannot be empty')
<?php } ?>
<?php elseif ($errors['empty_subject']) {?>
alert('Subject: cannot be empty')
<?php } ?>
<?php elseif ($errors['empty_body']) {?>
alert('Body: cannot be empty')
<?php } ?>
</script>
<?php } ?>
<form method="post">
<div>
<label for="to">To</label>
<input id="to" type="email" name="to" value="<?php echo $to;?>" />
</div>
<div>
<label for="subject">Subject</label>
<input id="subject" type="text" name="subject" value="<?php echo $subject;?>" />
</div>
<div>
<label for="body">Body</label>
<textarea id="body" name="body"><?php echo $body;?></textarea>
</div>
<div>
<input type="submit" value="Send">
</div>
</form>
Basically you start using session using session_start()
On POST:
If you don't have an error:
send the mail
redirect to the conctactus page.
If you have an error:
save the input in the session
redirect to the contact us page
On GET:
If you have nothing in session or the mail in session is valid, just render the html.
If you have something in session and that data is invalid, render the html, render the alert script, and set the "value" attributes of the input to maintain the user's input values.
Clear the session data.
This solution requires that you change your contactus.html to contactus.php in order to use sessions.
<?php
// to use a session, you must start it
session_start();
// variable to store any error message
$error = null;
$from = $_POST['email_adress'];
$subject = $_POST['subject'];
$select = $_POST['select'];
$message2 = $_POST['message2'];
$name = $_POST['firstname'];
$name2 = $_POST['lastname'];
if ($_POST['firstname'] == "") {
$error = "First Name is Mandatory.";
} elseif ($_POST['subject'] == "") {
$error = "Subject is Mandatory.";
} elseif ($_POST['email_adress'] == "") {
$error = "Email Adress is Mandatory.";
} elseif ($_POST['message2'] == "") {
$error = "A Message is Mandatory.";
}
if ($error) {
// store the error in a session so that you can use it on another page
$_SESSION['error'] = $error;
} else {
$email_subject = "A submittion form";
$to ="sudaiguy1#gmail.com";
$headers = "From: sudaiguy1#gmail.com";
$email_body = 'You have been contacted by $name $name2 and his email is $from. \n The message he wanted to say was in the general subject of $select and more specifically $subject and the message is $message2';
mail($to,$email_subject,$email_body, $headers);
}
// regardless of whether there is an error or not, it always goes to Contact Us page
header("Location: contactus.php");
exit;
?>
Then in your contactus.php, you would have
<?php
// resume session again
session_start();
?>
<!-- somewhere in your HTML code -->
<?php if (isset($_SESSION['error'])) : ?>
<div class="error-message"><?php echo $_SESSION['error'] ?></div>
<?php endif ?>
<?php
// you probably will want to remove the error afterwards
unset($_SESSION['error']);
?>
If you can't do that, then this solution will not work and you'll have to resort to AJAX (where you send back your error message via the response you get back from your AJAX response).
Related
I want to send data from php to php and in same time I also want to send data from js to php. I have one index.php which contains php and js part. In enrolled.php I want to collect my data. SQL injection or other security problems are not important. I do not get any error but it does not save to database.
Small part of index.php
<!DOCTYPE html>
<html lang="en">
<head>
//smt....Not important
</head>
<body>
//smt....Not important
<div id="dom-target" style="display: none;">
<?php
include_once "connection.php";
session_start();
$username = $_SESSION['username'];//coming from previous page.
echo htmlspecialchars($username); //for sending variable from php to js.
?>
</div>
<script type = "text/javascript">
$('#addmore').click(function(){
var subjectone = $('#selectedsubjectone :selected').val();
var courseone = $('#courseListone').val();
var gradeone = $('#selectedGradeOne :selected').val();
var div = document.getElementById("dom-target");
var username = div.textContent;//these lines help to gett data from php
document.getElementById("usernamee").innerHTML = username;//for checking
$.ajax({
type: "POST",
url: "addenrolled.php",
data: {
// Send the username (js, not php)
username: username,
subject: subjectone,
course: courseone,
grade: gradeone
}, success: function(data) {
alert("sucess");
}
});
});
</script>
</body>
</html>
enrolled.php
<?php
include_once "connection.php";
$nick = $_POST['username'];
$subject=$_POST['subject'];
$course=$_POST['course'];
$grade=$_POST['grade'];
echo "$nick -- $subject -- $course -- $grade"; //for checking
$prep = $con->prepare("INSERT INTO enrolledtable ('nickname', 'subject', 'course', 'grade') VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
if ($send == TRUE) {
echo "Courses added successfully";
header('Location: index.php');
exit();
} else {
echo "Error: " . $con->error;
header('Location: index.php');
exit();
}
?>
Change your jQuery to this
<script>
$(document).ready(function(){
$('#addmore').click(function(){
var subjectone = $('#selectedsubjectone :selected').val();
var courseone = $('#courseListone').val();
var gradeone = $('#selectedGradeOne :selected').val();
$.post('enrolled.php', {subjectone: subjectone, courseone: courseone, gradeone: gradeone, addmore: "yes"}, function(response){
console.log(response);
})
});
});
</script>
Then in your PHP modify the prepare statement to the following
$prep = $conn->prepare("INSERT INTO enrolledtable (`nickname`, `subject`, `course`, `grade`) VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
enrolled.php
<?php
session_start();
include_once "connection.php";
if (isset($_POST['addmore'])) {
$nick = $_SESSION['username'];
$subject=$_POST['subjectone'];
$course=$_POST['courseone'];
$grade=$_POST['gradeone'];
// //echo "$nick -- $subject -- $course -- $grade"; //for checking
$prep = $conn->prepare("INSERT INTO enrolledtable (`nickname`, `subject`, `course`, `grade`) VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
if ($send == TRUE) {
echo "Courses added successfully";
// header('Location: index.php');
exit();
} else {
echo "Error: " . $con->error;
//header('Location: index.php');
exit();
}
}
?>
I have two files named index.php and uploadcover.inc.php. Everything is working fine, except the script tags being executed if the upload fails for any of the if-else conditions. Here is the code:
index.php =>
<form action="include/uploadcover.inc.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="cover-upload" style="display:none" onchange="this.form.submit();">
<label for="cover-upload" class="fa fa-camera fa-2x" aria-hidden="true"></label>
</form>
uploadcover.inc.php =>
<?php
session_start();
include_once 'dbh.inc.php';
$sessionid = $_SESSION['u_id'];
$filename = "../profile/cover".$sessionid.".*";
$fileinfo = glob($filename);
$fileExt= explode('.',$fileinfo[0]);
$fileActualExt= $fileExt[3];
$file = "../profile/cover".$sessionid.".".$fileActualExt;
if(!unlink($file)){
echo "File not deleted";
} else {
"File deleted";
}
$sql = "UPDATE coverimg SET status=1 WHERE user_id='$sessionid';";
mysqli_query($conn,$sql);
$file= $_FILES['file'];
$fileName= $file['name'];
$fileTmpName= $file['tmp_name'];
$fileSize= $file['size'];
$fileError= $file['error'];
$fileType= $file['type'];
$fileExt = explode('.',$fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg','jpeg','png','gif');
if(in_array($fileActualExt,$allowed)){
if($fileError=== 0){
if($fileSize<3145728){
$fileNameNew = "cover".$sessionid.".".$fileActualExt;
$fileDestination = '../profile/'.$fileNameNew;
move_uploaded_file($fileTmpName,$fileDestination);
$sql = "UPDATE coverimg SET status=0 WHERE user_id='$sessionid'";
mysqli_query($conn,$sql);
header("Location: ../index.php?upload=success");
} else {
header("Location: ../index.php?upload=size_exceeded_3MB");
exit();
echo "<script>alert('File should be less than 3MB!')</script>";
}
} else {
header("Location: ../index.php?upload=error");
exit();
echo "<script>alert('Error uploading the file!')</script>";
}
} else{
header("Location: ../index.php?upload=typeerror");
exit();
echo "<script>alert('Filetype not supported!')</sc
ript>";
}
Note: I tried die(), exit() and also removing them in case it executes the script after being redirected to index.php but it doesn't work.
A redirect tells the client that why they are looking for can be found at a different URL. The client then requests that other URL and displays that document instead.
You can't simultaneously say "Here is the document you should show" and "The document you should show can be found over here". It is one or the other.
I'm looking for a way to redirect after submit depending on the echo
and i used the following code:
<?php
$to = "mymail#gmail.com";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$subject = "New Client Call";
$body = 'name: ' .$name."\r\n";
$body = 'email: ' .$email."\r\n";
$body = 'message: ' .$message."\r\n";
$go = mail($to, $subject, $body, "From:<$email>");
if ($go) {
echo "Success";
}
else {
echo "error";
}
?>
<form action="index9.html" method="post" name="redirect" ></form>
<script> document.forms['redirect'].submit()</script>
but i have now two problems:
i am always getting "success" echo. even the client sending empty details.
i want to redirect to an error page with Javascript (if/else) and i don't now how.
BTW i am new in this field so:
I will appreciate your advise/help and be thankful.
You don't need javascript to achive this you can use pure php.
You can use error checking if a field is empty in the form as follows
validate.php
if(isset($_POST['submit'])){
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (isset( $nameErr) || isset($emailErr){
// you have a error
}
else {
$to = "mymail#gmail.com";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$subject = "New Client Call";
....
This will check if "email" field is empty if it is it will promp a error "Email is required"
And then in your html you add the error
<form class="form-horizontal" action="validate.php" method="post">
<label for="email">Email: </label>
<input type="text" class="form-control input-sm" name="email">
<span class="error">* <br><?php echo $emailErr;?></span>
<input class="btn btn-info btn-lg" type="submit" name="submit" value="Submit">
</form>
Hope that helps
You seem to be on the right path, before throwing the arguments into the the mailer I would say you can do more sanity checking to make sure all values are entered, this way you avoid trying to send emails that you know will fail, so you fail early and notify the user, you may also see the error message the mail function returns in case of failure to make it easy to rectify any other issues by using the erorr_get_last() method.
echo error_get_last()['message'];
Note: php mail does not verify the headers given, so you have to be 100% sure it's clean and there are no possibilities for the user to inject their own headers, so make sure you sanitize that too.
Then to do redirecting you can just directly replace the echo "success" and echo "error" calls with your javascript part.
So the script would finally look like this:
<?php
$to = "mymail#gmail.com";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$subject = "New Client Call";
$missingFieldCount = 0;
if(!isset($_POST['name'])) {
echo "Error: Name requried";
$missingFieldCount++;
}
if(!isset($_POST['email'])) {
echo "Error: Email required";
$missingFieldCount++;
}
if(!isset($_POST['message'])) {
echo "Error: message required";
$missingFieldCount++;
}
if($missingFieldcount > 0) {
echo "Please fill in the missing $missingFieldcount fields, then submit again";
} else {
$body = 'name: ' .$name."\r\n";
$body .= 'email: ' .$email."\r\n"; // Using .= to append instead of replace
$body .= 'message: ' .$message."\r\n";
$headers = "From:<$email>"; //Make sure $email is actually just an email address and not injected headers
$success = mail($to, $subject, $body, $headears);
if ($success) {
$redirectPage = "successPage.html"
} else {
$redirectPage = "errorPage.html"
echo "An error occured:";
//Don't show this to the user, but log it to file instead
//this is here only for demonstration
echo error_get_last()['message'];
}
echo "<form action="$redirectPage" method="post" name="redirect" ></form>";
echo "<script> document.forms['redirect'].submit()</script>";
}
}
?>
Tnq Guys for your answers.
finally i manged a perfect PHP form from all the information i get in this issue. no need Javascript to redirect TO 2 different pages:
1. Thank you page.
2. error page.
and the code is like this:
<?php
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$to = "mymail#gmail.com";
$subject = " New Client order ";
$errors = 0;
$body ="";
$body .="Name: ";
$body .=$name;
$body .="\n";
$body .="Email: ";
$body .=$email;
$body .="\n";
$body .="Message: ";
$body .=$message;
$body .="\n";
if(isset($_POST['submit'])) { // Checking null values in message.
$name = $_POST["name"]; // Sender Name
$email = $_POST["email"]; // Sender's email ID
$message = $_POST["message"]; // Sender's Message
if (empty($_POST["name"])){
$nameError = "Name is required";
$errors = 1;
}
if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
{
$emailError = "Email is not valid";
$errors = 1;
}
if (empty($_POST["message"])){
$messageError = "Message is required";
$errors = 1;
}
}
if($errors == 0){
$successMessage = mail($to, $subject, $body, "From: <$email>");
}
else {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.html\">";
}
if ($successMessage){
print "<meta http-equiv=\"refresh\" content=\"0;URL=thanks.html\">";
}
?>
My PHP:
include_once ('db.php');
$capt_err = '';
$error = 0;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$captcha = $_POST['g-recaptcha-response'];
if (!$captcha) {
echo '<script language="javascript">';
echo 'alert("please check the captcha!");';
// echo 'window.location.href="#mymodal";';
echo '</script>';
exit();
}
else {
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6LcoHioTAAAAAHvJ0FIRLC-VWVmpBSs_-7igEkXh&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
}
if ($response . success == false) {
echo '<h2>You are spammer ! Get the #$%K out</h2>';
}
else {
$result = mysqli_query($mysqli, "INSERT INTO vibodha_feedback (`id`,`name`,`email`,`phone`,`message`,`date`) VALUES('','$name','$email','$phone','$message',now())");
echo "<script>" . "alert('Your Message has been sucessfully sent.')" . "</script>";
}
}
// header('location:testimonials.php');
My HTML:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<fieldset>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="mail">Email:</label>
<input type="email" id="email" name="email" required>
<label for="phone">Phone:</label>
<input type="number" id="phone" name="phone" required>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
<div class="g-recaptcha" data-sitekey="6LewHioTAAAAANGO-VChqdjsoZARTVOxsrgPW6T8"></div>
</fieldset>
<button type="submit">Send!</button>
</form>
My JavaScript:
the script is default for g-recapcha(google),the google intergrate only recaptcha option..not to give required option.
i wrote validation in php code.the captcha is empty alert will come(refer php code)
the above three parts in my code..i give required in div class,,,the div not taken,then how to give required in captcha.
Try something like this
<input type="text" class="inputcontact" id="captcha_contact" placeholder="Cod securitate" name="captcha" onchange="isEmpty('captcha_contact', 'hiba-captcha_contact')">
<div id="error-captcha_contact"><span style="font-size: 8px;"></span></div>
JS file:
jQuery(document).ready(function () {
jQuery('#contact_send').click(function () {
var minden_ok = true;
if (minden_ok == true) {
minden_ok = isEmpty('captcha_contact', 'error-captcha_contact');
}
if (minden_ok == true) {
//your code here
}
});
function isEmpty(ID, errorID) {
var value= jQuery('#' + ID).val();
if (value.length > 0) {
jQuery("#" + errorID).hide("slow");
jQuery("#" + ID).css("border-color", "");
return true;
} else {
jQuery("#" + errorID + " span:first").text("Please fill !");
jQuery("#" + ID).css("border-color", "red");
jQuery("#" + errorID).show("slow");
jQuery("#" + ID).focus();
return false;
}
You can get it by $_POST['g-recaptcha-response'];
like
include_once ('db.php');
$capt_err = '';
$error = 0;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
if($_POST['g-recaptcha-response']=='')
{
echo '<script language="javascript">';
echo 'alert("please check the captcha!");';
// echo 'window.location.href="#mymodal";';
echo '</script>';
exit();
}
else {
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6LcoHioTAAAAAHvJ0FIRLC-VWVmpBSs_-7igEkXh&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
}
if ($response . success == false) {
echo '<h2>You are spammer ! Get the #$%K out</h2>';
}
else {
$result = mysqli_query($mysqli, "INSERT INTO vibodha_feedback (`id`,`name`,`email`,`phone`,`message`,`date`) VALUES('','$name','$email','$phone','$message',now())");
echo "<script>" . "alert('Your Message has been sucessfully sent.')" . "</script>";
}
}
// header('location:testimonials.php');
I'm working on a login page by user level to separate the admin and user. but it didnt seems to work. it doesnt redirect and leave a blank page. I've tried remove the javascript part, but it doesnt change anything either.
index.php
<form class="login" action="login.php" method="post">
Username:<input type="text" name="username" id="username"/>
Password:<input type="password" name="password" id="password"/>
<input type="submit" value="login"/>
</form>
login.php
<?php
session_start();
include('config.php');
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql = mysql_query("SELECT * FROM admin WHERE username='$username' AND password='$password'");
$result = mysql_fetch_array($sql);
$username=$result['username'];
$adminID=$result['adminID'];
$userLevel=$result['UserLevel'];
$_SESSION['adminID']=$adminID;
$_SESSION['userLevel']=$userLevel;
$_SESSION['username']=$username;
$_SESSION['password']=$password;
if($userLevel == '1')
{
$sql = "UPDATE admin SET status = 'AKTIF' where username = '$username' ";
$result = mysql_query($sql) or die('Cannot UPDATE.'.mysql_error());
?>
<script type="text/javascript">
alert("Welcome <?php echo "$username" ?> to Admin page! ");
</script>
<?php
header('Location:admin.php');
exit();
}
elseif($userLevel == '0')
{
$sql = "UPDATE admin SET status = 'AKTIF' where username = '$username' ";
$result = mysql_query($sql) or die('Cannot UPDATE.'.mysql_error());
?>
<script type="text/javascript">
alert("Welcome <?php echo "$username" ?> to User page! ");
</script>
<?php
header('Location: user.php');
exit();
}
else
{
?>
<script type="text/javascript">
alert("Invalid Username or Password! ");
//window.location.href = "index.php";
</script>
<?php
}
}
?>
Use PHP Header:
for userLevel1:
header("Location: admin.php");
for userLevel2:
header("Location: user.php");
Name in your submit so it will enter your PHP code block:
<input type="submit" name="submit" value="login"/>
try the following code and replace into your code. see whether can work or not. you try on the first if condition first and see on the result. if cannot work tell me what problem you face.
<?php
if($userLevel == '1')
$sql = "UPDATE admin SET status = 'AKTIF' where username = '$username' ";
$result = mysql_query($sql) or die('Cannot UPDATE.'.mysql_error());
?>
<script>
var a = alert("Welcome <?php echo "$username" ?> to Admin page! ");
if (a === true){
window.location.href="admin.php";
}
else{
window.location.href="admin.php";
}
</script>
<?php
}