PHP script doesnt redirect to "header" page - php

Here is the issue. I am trying to troubleshoot an issue in my PHP script that prevents it from emailing the info, our client has inputted.
<?php
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$recaptcha=$_POST['g-recaptcha-response'];
if(!empty($recaptcha))
{
include("getCurlData.php");
$google_url="https://www.google.com/recaptcha/api/siteverify";
$secret='6LegpgYTAAAAABK9Nd45_DfAPu7_gwHro9pj902B';
$ip=$_SERVER['REMOTE_ADDR'];
$url=$google_url."?secret=".$secret."&response=".$recaptcha."&remoteip=".$ip;
$res=getCurlData($url);
$res= json_decode($res, true);
//reCaptcha success check
if($res['success'])
{
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
if(isset($_POST['submit'])) {
$to = "denislav#svishtov.net";
$subject = "New opinion post";
// data the visitor provided
$name_field = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$phone_field = filter_var($_POST['number']);
$address_field = filter_var($_POST['address'], FILTER_SANITIZE_STRING);
$comment = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
//constructing the message
$body = "
From: $name_field <br/>
Email Address: $address_field <br/>
Phone number: $phone_field <br/>
Message:<br/> $comment ";
// ...and away we go!
mail($to, $subject, $body, $headers);
// redirect to confirmation
header("Location: confirmation2.html");
}
else {
// handle the error somehow
echo "Error accessing the file";
}
}
else
{
echo "Въвели сте грешен код за потвърждаване (reCAPTCHA)! Натиснете "назад" и опитайте отново";
}
}
else
{
echo "Не сте въвели код за потвърждаване (reCAPTCHA)! Натиснете "назад" и опитайте отново";
}
}
?>
worse thing is , it used to work , then I opened it, edited some stuff and now it doesnt work, tried the back-up copy and it still doesnt work !?
Working in CMS MadeSimple. the URLs are correct , the confirmation2.html is a file, not a page made in CMS and it is in the same folder as the php script and if I try to access it directly (not via the contact from) its there, I have tried ' ' and " " quotes, still no change.
Probably a simple mistake, I did try looking for other solutions in here (stackoverflow.com) but nothing to fix my current issue. I know that I shouldnt have any output before the header but... well I dont have any output so, I'm baffled.
Appreciation in advance to those who want to help!

UPDATE:
Seems like the reCAPTCHA was shitting me, and after I removed it - WORKS.
Gonna leave it defenseless for now. Thanks to all who wanted to help.

Related

Can´t get accentuation to work on messages sent with my email form. Anyone can give me a hand? Here is my code:

This is what the message is showing:
Cão açorda água côco teste acentuação
This is what I wanted it to show:
Cão açorda água côco teste acentuação
Can someone give me a hand? I would be very grateful.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(!empty($_POST['contactname']) && !empty($_POST['contactemail']) && !empty($_POST['contactmessage'])) {
$to = 'email#gmail.com'; // Your e-mail address here.
$body = "\nNCliente: {$_POST['contactname']}\nEmail: {$_POST['contactemail']}\n\n\n{$_POST['contactmessage']}\n\n";
mail($to, "Mensagem de ", $body, "From: {$_POST['contactemail']}"); // E-Mail subject here.
}
}
?>
This looks like an encoding problem. If you want to display characters like 'ç', typical from portuguese language, you need to decode your text parameters to the UTF-8 pattern. That way, they are going to be displayed properly.
To do that, you could try using utf8_decode(string) function from PHP. Something like this:
$contactname = utf8_decode($_POST['contactname']);
EDIT: Your code would look like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(!empty($_POST['contactname']) && !empty($_POST['contactemail']) && !empty($_POST['contactmessage'])) {
//this is the part where you convert to utf8 pattern
$namecontact = utf8_decode($_POST['contactname']);
$messagecontact = utf8_decode($_POST['contactmessage']);
$to = 'email#gmail.com'; // Your e-mail address here.
$body = "\nNCliente: " .$namecontact. "\nEmail: {$_POST['contactemail']}\n\n\n". $messagecontact ."\n\n";
mail($to, "Mensagem de ", $body, "From:" . $namecontact); // E-Mail subject here.
}
}
?>

PHP header function line is not working in the file I want and it works in all other files

I am working with a mail. What I exactly want is the page should be redirected to the universal resource locator after 5 seconds. The header line is working fine in all other files but not in this file. I tried my best to find what is wrong. The before and after line is also working fine but the page is not redirecting. And even I have checked the code many time and there is no error.
Can you please tell me the reason why is it happening?
Code
<?php
if (isset($_POST['fullname']) && isset($_POST['email']) && isset($_POST['message']) && isset($_POST['submit'])) {
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = "ziajappa1#gmail.com";
$subject = "Customer";
$txt = "Hi, Grand4Love ".$fullname." have contacted you. Do hurry to contact him back! The user's email address is: ".$email."";
$headers = "From: client#perfecttips.com\r\n";
//."CC: somebodyelse#example.com";
if(mail($to,$subject,$txt,$headers)){
echo "<h2>Thank you for contacting us, we will respond to your message withing 24 hrs<h2>";
}
header('refresh:5; url=http://perfecttips.co/');
// The above line is working in the other files but not here.
// Please suggest me why the above line is not working?
echo "hi";
}
?>
Is there anything that is included in this file that is written to the response before the header is parsed?
Headers need to be the first thing that page parses, or else it will be ignored.
Look for echoes or something in previously imported files.
Edit:Yup. You are echoing. Comment out all echoes and you'll see it should work.

PHP validation issue - form submitting even when required fields empty

I'm new to PHP and trying to create a form with all fields required, including one where a file must be selected. Here is what I would like to achieve:
user must complete 4 fields + upload a file
file can only be of a certain type + under a certain size
if user does not complete one of the requirements and clicks submit, the word "Required" appears next to the empty field
if selected file does not meet criteria, a different message appears
data is preserved in the fields that were filled in if the user left something blank and has to go back to fill it in.
when form submits, info goes into database + into an email
I am close but missing something. If I select a file that meets the requirements, the form submits even if the other fields are blank. As long as the form field is empty, the other fields behave correctly. What am I missing? I would appreciate any help. Thank you.
<?php require_once('../scripts/lcoa.php'); ?>
<?php
if (isset($_GET['jobid'])) {
$jobid = $_GET['jobid'];
}
if (isset($_GET['jobtitle'])) {
$jobtitle = $_GET['jobtitle'];
}
//This is the directory where resumes will be saved
$timestamp = time();
$folder = "../careers/resumes/";
$resume = ($_FILES['resume']['name']);
$target = $folder.basename($timestamp.$_FILES['resume']['name']);
$type = ($_FILES['resume']['type']);
$extension = strtolower(substr($resume, strpos($resume, '.') + 1));
$size = ($_FILES['resume']['size']);
$max_size = 3145728;
$name = ($_POST['name']);
$email = ($_POST['email']);
$phone = ($_POST['phone']);
$jobid = ($_POST['jobid']);
$jobtitle = ($_POST['jobtitle']);
$cover = ($_POST['coverletter']);
$error=array();
if(isset($name)){
if (empty ($name)){
$error['name']="<p class='error'>Required </p>";
}
}
if(isset($email)){
if (empty ($email)){
$error['email']="<p class='error'>Required </p>";
}
}
if(isset($phone)){
if (empty ($phone)){
$error['phone']="<p class='error'>Required </p>";
}
}
if(isset($cover)){
if (empty ($cover)){
$error['coverletter']="<p class='error'>Required </p>";
}
}
//Writes the resume to the server
if (isset ($resume)) {
if (empty ($resume)){
$error['resume']="<p class='error'>Resume Required </p>";
}
if (!empty ($resume)){
if(($extension=='doc'||$extension=='docx'||$extension=='txt'||$extension=='pdf')&&($type=='application/pdf'||'application/msword'||'application/vnd.openxmlformats-officedocument.wordprocessingml.document'||'text/plain')&&$size<=$max_size) {
if(move_uploaded_file($_FILES['resume']['tmp_name'], $target)) {
//Writes the information to the database
$insertSQL = "INSERT INTO applicants (id, name, email, phone, jobid, jobtitle, coverletter, resume) VALUES ('','".$_POST['name']."','".$_POST['email']."','".$_POST['phone']."','".$_POST['jobid']."','".$_POST['jobtitle']."','".$_POST['coverletter']."','".$resume."')";
mysql_select_db($database_lcoa, $lcoa);
$Result1 = mysql_query($insertSQL, $lcoa) or die(mysql_error());
//Sends Email
$sendto = "emailaddress";
$name = nl2br($_POST['name']);
$email = nl2br($_POST['email']);
$phone = nl2br($_POST['phone']);
$jobid = nl2br($_POST['jobid']);
$jobtitle = nl2br($_POST['jobtitle']);
$cover = nl2br($_POST['coverletter']);
$subject = "Submitted Job Application";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$headers = "From: " . strip_tags($email) . "\r\n";
$headers .= "Reply-To: ". strip_tags($email) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>Job Application Submitted</h2>\r\n";
$msg .= "<p><strong>Applied for:</strong> ".$jobtitle."</p>\r\n";
$msg .= "<p><strong>Job ID:</strong> ".$jobid."</p>\r\n";
$msg .= "<p><strong>Applicant Name:</strong> ".$name."</p>\r\n";
$msg .= "<p><strong>Email:</strong> ".$email."</p>\r\n";
$msg .= "<p><strong>Phone:</strong> ".$phone."</p>\r\n";
$msg .= "<p><strong>Cover Letter:</strong> ".$cover."</p>\r\n";
$msg .= "<a href='http://domain.com/".$target."'>Download Resume</a>\r\n";
$msg .= "</body></html>";
if(#mail($sendto, $subject, $msg, $headers)) {
echo "";
} else {
echo "false";
}
//Tells you if its all ok
echo "<div id='confirm-app'><p>Thank you for submitting your application. Resumes submitted will be reviewed to determine qualifications that match our hiring needs.<br /><br /> If you are selected you will be contacted by a member of our recruiting team.</p><br /><br /><a href='../careers/job-postings.php'>Return to current opportunities</a></div>";
}
}
else {
//Gives and error if its not
echo "<p style='color: #6D6E71; font-family: Arial,Helvetica,sans-serif; font-size: 13px;'>We accept resumes in <strong>.doc</strong>, <strong>.docx</strong>, <strong>.pdf</strong>, or <strong>.txt</strong> formats, 3MB or less. Please <a href='javascript:history.back(-1);'>go back</a> to upload a file that meets these requirements.<br /><br />If you continue to experience errors, please report them.</p>";
die();
}
}
}
?>
You have to add one more condition near if (!empty ($resume)) that checks your $error array empty if not empty then print the errors else insert or email etc
if (!empty ($resume) && empty($error)){
//do your stuff
}else{
//display errors
}
you are only testing to see if if (!empty ($resume)){ and the requirements for the file before you execute the database insert and email sending. you will have to test for other elements being correct as well. Since you are building an array called $error you can test to see if empty($error) before performing the database insert and email.

PHP: submit form with self and render different page items?

I've never done that before and simply need a little advice how to do so …
I have a index.php file with a simple contact form.
<form id="contactform" method="post" action="<?php echo $_SERVER["SCRIPT_NAME"] ?>">
The index.php file has the following script on top.
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<?php
//Vars
$Name = Trim(stripslashes($_POST['author']));
$EmailFrom = Trim(stripslashes($_POST['email']));
$Subject = Trim(stripslashes($_POST['subject']));
$Type = Trim(stripslashes($_POST['type']));
$Comment = Trim(stripslashes($_POST['message']));
$EmailTo = "address#something.com";
//Validation
$valid = true;
if ( $Name == "" ) $valid = false;
if ( isValidEmail( $EmailFrom ) == 0 ) $valid = false;
if ($Subject == "") $valid = false;
if ($Comment == "") $valid = false;
function isValidEmail( $email = null ) {
return preg_match( "/^[\d\w\/+!=#|$?%{^&}*`'~-][\d\w\/\.+!=#|$?%{^&}*`'~-]*#[A-Z0-9][A-Z0-9.-]{1,61}[A-Z0-9]\.[A-Z]{2,6}$/ix", $email );
}
//Body
$Body = $Type;
$Body .= "\n\n";
$Body .= $Comment;
//Headers
$email_header = "From: " . $EmailFrom . "\r\n";
$email_header .= "Content-Type: text/plain; charset=UTF-8\r\n";
$email_header .= "Reply-To: " . $EmailFrom . " \r\n";
//Send
if ($valid)
$success = mail($EmailTo, $Subject, $Body, $email_header);
?>
I have two questions now:
1.)
How exactly can I render/not-render certain stuff when either the validation went wrong or a success or an error comes back when submitting the mail?
e.g. I know that I can do that!
if ( !$valid )
print "Failed to make contact. Enter valid login credentials! <a href='/#contact' title='try again'>try again?</a>";
if ( $success )
print "Successfully made contact.";
else
print "Failed to make contact. <a href='/#contact' title='try again'>try again?</a>"; */
?>
However $valid will always be wrong on page-load when not submitting the form and also the email will always return the error message on the first page load. How can I only render or not render specific stuff when the form is submitted?
E.g. When submitting the form and a success comes back I don't want to render the #contactform anymore. I simply want to print "Successfully made contact" into an h1 or so.
How can I make that happen? It's probably rather simple I just can't find a solution for myself.
2.)
When using $_SERVER["SCRIPT_NAME"] or PHP_SELF as action the url after submitting the form will always change to "mydomain.com/index.php". Can I prevent that from happening? I want to submit the index.php file itself however I just don't like it when /index.php is written into the url. Is it possible to stop that from happening?
Thank you for your help!
Matt,
For the first question as to printing to the screen based on success or failure of the email, your checks seem fine, but you probably aren't going to get an email failure in time to display that to the screen. That said, you just need to wrap your second set of code in an if statement. Something like this:
if( isset($_POST['Submit']) ){ //only attempt to display if form submitted.
//Your code here
}
As for not including the directory in the form action, there are many ways to do this, but here's one:
$scriptString= explode('/',$_SERVER['SCRIPT_NAME']);
$scriptSize = count($scriptString)-1;
$script = $scriptString[$scriptSize];
And then use $script in the form action.

WhileLoop through a mysql db list

Ok so long story short, I have a simple mailto function I want to apply/run for every name on a db list. Since it's not working, I removed all the mail stuff from it and to test to make sure the while loop was working with the db, did this
<?php
$connect2db = mysqli_connect('127.0.0.1','root','pass','dbnamehere');
if(!$connect2db){
die("Sorry but theres a connection to database error" . mysqli_error);
}
$sn_query = "SELECT * FROM email_list";
$sn_queryResult = mysqli_query($connect2db, $sn_query) or die("Sorry but theres a connection to database error" . mysqli_error);
$sn_rowSelect = mysqli_fetch_array($sn_queryResult);
$to = $sn_rowSelect;
?>
<br/><br/>
////lower part on page //////<br/><br/>
<?php
while($sn_rowSelect = mysqli_fetch_array($sn_queryResult) ) {
echo "hello there" . " " . $sn_rowSelect['firstname'] . " <br/>";
}
?>
Now this works, it goess through my db and prints out all my first names from the database list. In my noob brain, id think that if i remove the echo lines, and enter the appropriate mailto information, that it would loop just like before, but send mail to each name. so i did this:
<?php
$sn_query = "SELECT email FROM email_list";
$sn_queryResult = mysqli_query($connect2db, $sn_query) or die("Sorry but theres a connection to database error" . mysqli_error);
$sn_rowSelect = mysqli_fetch_array($sn_queryResult);
$to = implode(",",$sn_rowSelect);
$from = $_POST['sender'];
$subject = $_POST['subj'];
$mssg = $_POST['message'];
$headers = "MIME-Version: 1.0rn";
$headers .= "From: $from\r\n";
$mailstatus = mail($to, $subject, $mssg, $headers);
?>
<br/><br/>
//////////<br/><br/>
<?php
while($sn_rowSelect = mysqli_fetch_array($sn_queryResult) ) {
$mailstatus;
if($mailstatus) {
echo "Success";
}else{
echo "There was a problem sending the mail. Check your code and make sure that the e-mail address $to is valid\n";
}
}
?>
now this emails the first name on my list, but not the rest.
I don't get any errors so not sure what the problem is. I was going to try an if statement with num_rows but somewhere else, on StackOverflow, someone said that didn't help since the while loop took care of it by itself. (I tried it either way and it still emailed only the first name) I'm trying here but to no avail.
You have not called the mail() function inside your loop. You call it once outside. Instead try something like the following.
Assuming you have retrieved the $to address from your database query (like you did with the firstname in testing), pull it from the rowset, and use it in mail():
while($sn_rowSelect = mysqli_fetch_array($sn_queryResult) ) {
// Get the $to address:
$to = $sn_rowSelect['email'];
// Call mail() inside the loop.
$mailstatus = mail($to, $subject, $mssg, $headers);
if($mailstatus) {
echo "Success";
}else{
echo "There was a problem sending the mail. Check your code and make sure that the e-mail address $to is valid\n";
}
}
Note also, that since you call mysql_fetch_array() at the top of your script, your while loop will start with the second row. You should remove the first call to mysql_fetch_array() that occurs before the loop.
$sn_queryResult = mysqli_query($connect2db, $sn_query) or die("Sorry but theres a connection to database error" . mysqli_error);
// Don't want this...
//$sn_rowSelect = mysqli_fetch_array($sn_queryResult);

Categories