Send array values in PHP form - php

I have a HTML form with embedded PHP code that creates a checkbox for each value contained in an array. Just like this:
<?php
$rows = array_map( 'str_getcsv', file( 'file.csv' ) );
$header = array_shift( $rows );
foreach ( $rows as $row ) {
echo '<input type="checkbox" id="'.$row[0].'" name="'.$row[0].'">
<label for="'.$row[0].'">'.$row[0].'</label>
<input type="number" name="'.$row[0].'" placeholder="Some text">';
}
?>
Now, I want to send this form using this code, which is inserted into another PHP file:
<?php
if( isset( $_POST ) == true && empty( $_POST ) == false ) {
$account = $_POST['account'];
$investment = $_POST['row[0]'];
$password = $_POST['password'];
$formcontent=" Account: $account \n $row[0]: $investment \n Password: $password";
$recipient = "my#email.com";
$subject = "My Form";
$mailheader = "From: My Form <my#form.com>";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Some text";
}
?>
But it doesn't work. When you click on submit button the form does nothing.
I've checked it with success with HTML-only code, so I guess I'm making a mistake with PHP.
For those interested, here's a link to my form: Example
EDIT: I've removed preventDefault, as pointed by #DavidJorHpan, but I'm still stuck. I'm unable to make my form.php send $row[0] to my email.

Because you use preventDefault so it will never submit form until you code for submitting form
$("button").click(function(e) {
e.preventDefault();
});
You can remove that code or add code like
$('form').submit();

As David JorHpan pointed out in the second answer, you've got to remove preventDefault() from the button click event. That prevents the form from being submitted.
For every checkbox you have a corresponding number input field. Although possible, its not a good practice to have spaces in your 'name' attribute values. Try replacing those spaces with dashes or underscores. For example you can do something like below:
name="'.str_replace(' ','_',$row[0]).'"
and same can be done to id attribute values.
Your form submit check should work but it will make more sense if you change that as follows:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
// process here
}
After doing these changes try loading the page and see how it goes.

Related

PHP cant get passed on question mark on clean url

I need some help with my code as I have got a problem with get pass on the if statement. I am working on the clean url to create a function like create_newsletter.php?template=new when I am on the same page.
When I try this:
if(isset($_POST['submit']))
{
sleep(2)
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
if(isset($_GET['template'])
{
echo "hello robert now you are working on the template";
}
}
It will not get pass on this line:
if(isset($_GET['template'])
Here is the full code:
<?php
$template = "";
if(isset($_GET['template']))
{
$template = $_GET['template'];
}
if(isset($_POST['submit']))
{
sleep(2)
$messagename = $_POST['messagename'];
$subject = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
if(isset($_GET['template'])
{
echo "hello robert now you are working on the template";
}
}
?>
<form method="post">
<input type="text" name="messagename" value="">
<input type="text" name="subject" value="">
<input type="submit" name="submit" name="submit" class="btn btn-primary" value="Next Step">
</form>
I have got no idea how I can get pass on the if statement when I am using header("Location:). I have also tried if ($template) but it doesn't get pass.
What I am trying to do is to connect to my php page create_newsletter.php. I want to input my full name the textbox called messagename and input the subject in the subject textbox then click on a button. When I click on a button, I want to redirect to create_newsletter.php?template=new as I want to disable on two textbox controls messagename and subjectthen add the iframe to allow me to get access to another php page so I could write the newsletter in the middle of the screen.
Can you please show me an example what is the best way forward that I could use to get pass on the if statement when I click on a submit button to redirect me to create_newsletter.php?template=new so I could disable these controls and add the iframe?
Thank you.
You are checking if(isset($_GET['template']) inside the if(isset($_POST['submit'])) condition, but the redirect doesn't send a post request.
This should work:
if(isset($_POST['submit']))
{
sleep(2)
$messagename = $_POST['messagename'];
$subject = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
}
if(isset($_GET['template'])
{
echo "hello robert now you are working on the template";
}
But if you need to make a POST request in the redirect, you would need to print a <form> and submit it in the client side, or use $_SESSION in the example bellow:
session_start();
if(isset($_POST['submit']))
{
sleep(2)
$_SESSION['messagename'] = $_POST['messagename'];
$_SESSION['subject'] = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
}
if(isset($_GET['template'])
{
// $_SESSION['messagename'] and $_SESSION['subject'] are available here
echo "hello robert now you are working on the template";
}
When you are checking if(isset($_POST['submit'])), you are redirecting before you can reach the if(isset($_GET['template']).
But I am assuming you would expect this to run because $_GET['template'] will be set. Although, the problem with your code is that when you redirect, $_POST['submit'] will not be set, therefor it will not execute anything in the if(isset($_POST['submit'])) block, including if(isset($_GET['template']).This is because a POST request is not persistant, and will not remain if you reload, or redirect
You should consider the following:
if(isset($_POST['submit']))
{
sleep(2)
$messagename = $_POST['messagename'];
$subject = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
}
if(isset($_GET['template'])
{
echo "hello robert now you are working on the template";
}
?>
Accessing the $messagename and $subject in the if(isset($_GET['template'])
If you want to access the $messagename and $subject in the if(isset($_GET['template']), you can pass them in the URL. Because when you redirect, no $_POST variables will be set, they will go away. You can accomplish this by doing:
if(isset($_POST['submit']))
{
sleep(2)
$messagename = $_POST['messagename'];
$subject = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new&messagename=".$messagename."&subject=".$subject);
}
if(isset($_GET['template'])
{
$messagename = $_GET['messagename'];
$subject = $_GET['subject'];
echo "hello robert now you are working on the template";
}
?>
There are two errors in the OP's code which unfortunately the officially accepted answer reflects as well. A semi-colon needs to be appended to the statement that uses sleep() and an extra parenthesis is needed in the statement that tests for $_GET['template'].
In truth, one does not need to complicate the code with signal processing offered by sleep() in order to delay submission of the POSTed data just to determine the value of $_GET['template']. One could omit sleep() and alter the the code slightly, as follows:
<?php
if( isset($_POST['submit']) )
{
$mess = htmlentities($_POST['mess']);
$subject = htmlentities($_POST['subject']);
header("Location: http://localhost/exp/create_newsletter.php?template=new");
exit;
}
else
if( isset( $_GET['template']))
{
echo "hello robert now you are working on the template";
exit;
}
Also, instead of using $_GET another alternative is to use $_SERVER['QUERY_STRING'], as follows:
<?php
$qs = parse_url($_SERVER['PHP_SELF'], PHP_URL_QUERY);
if( $qs == 'template=new' ){
$template = split("=",$qs)[1];
echo "hello robert now you are working on the template";
exit;
}
else
if(isset($_POST['submit']))
{
sleep(2);
$mess = htmlentities($_POST['mess']);
$subject = htmlentities($_POST['subject']);
header("Location: http://localhost/exp/create_newsletter.php?template=new");
exit;
}
?>
<html>
<head><title>test</title></head>
<body>
<form method="post" action="">
<input type="text" name="mess" value="">
<input type="text" name="subject" value="">
<input type="submit" name="submit" class="btn btn-primary" value="Next Step">
</form>
</body>
</html>
The component parameter of parse_url() enables this function to return the query string. One may also opt instead to employ parse_str(), as follows:
<?php
$queries = "";
parse_str($_SERVER['QUERY_STRING'], $queries);
if( isset($queries['template']) && ($queries['template'] == 'new'))
{
$template = $queries;
echo "hello robert now you are working on the template";
exit;
}
else
if(isset($_POST['submit']))
{
sleep(2);
$mess = htmlentities($_POST['mess']);
$subject = htmlentities($_POST['subject']);
header("Location: http://localhost/exp/create_newsletter.php?template=new");
exit;
}
?>
Note: it is very important to always treat data from a POST or GET as tainted instead of directly assigning the data to a variable and using that variable. Using htmlentities() is one way to attempt to prevent possible security issues.

Match JS string to PHP string

I would like to "export" a JS string to a PHP processing script and match them. When they match, i would like to go through a simple validation process and if the validation is successful, send off an email.
To put this in perspective, here is what my code looks like so far:
I have about 40 divs each represnting an item. The below html is an example of just one
HTML
<div class="Post odd postStyles">
<input class="cheap" data-mail="email#sample.com" name="option" type="radio">
<article>
<h6 class="casinoHeading">Grosvenor Casino Birmingham</h6>
<p class="">84 Hill Street, Birmingham, B5 4AH</p>
</article>
</div>
As you can see, i am using html5 data attributes for the string i want to use.
I then retrieve this string using the Jquery data() function.
Please see below:
$("input").click(function(){
var mail = $(this).data();
console.log(mail);
})
And this is the bit in which i get lost, unfortunately. I would like to be able to pass the variable mail to a php script which then runs a loop and finds the correct string.
Runs through some simple validation and then sends off an email.
Here is the PHP script I've written:
<?php
$emails = array(
"email#sample.com",
"email#sample1.com",
"email#sample2.com",
);
foreach($emails as $val) {
print $val;
}
if(isset($_POST ['Name'], $_POST ['Telephone'], $_POST ['Position'], $_POST['Email'], $_POST ['Noparty'], $_POST ['Message'], $_POST ['Adress'], $_POST ['PostCode'],
$_POST ['Date'], $_POST ['Time'])) {
var errors = array();
$name = htmlentities(mysql_real_escape_string(strip_tags($_POST['Name'])));
$telephone = htmlentities(mysql_real_escape_string(strip_tags($_POST['Telephone'])));
$email = strip_tags(mysql_real_escape_string(htmlentities($_POST['Email'])));
$position = strip_tags(mysql_real_escape_string(htmlentities($_POST['Position'])));
$noparty = strip_tags(mysql_real_escape_string(htmlentities($_POST['Noparty'])));
$message = mysql_real_escape_string(htmlentities(strip_tags($_POST['Message'])));
$address = mysql_real_escape_string(htmlentities(strip_tags($_POST['Adress'])));
$postcode = mysql_real_escape_string(htmlentities(strip_tags($_POST['PostCode'])));
$date = mysql_real_escape_string(htmlentities(strip_tags($_POST['Date'])));
$time = mysql_real_escape_string(htmlentities(strip_tags($_POST['Time'])));
if(empty($name) || empty($telephone) || empty($email) || empty($position) || empty($noparty) || empty($message) || empty($address) || empty($postcode) || empty($date)
empty($time)){
$errors [] = "<span class='error'>Please fill in the required fields!</span>";
}else{
if(strlen($name)<=2 || strlen($name)>25){
$errors [] = "<span class='error'>Sorry, username should be between 2 and 25 Charachters</span>";
}
}
//If all runs through sucessfully - send email
}
?>
Essentially i want to be able to send that variable to PHP(maybe with an AJAX request), check it and then run some validation with it.
Can anyone help out?
Much appreciated,
Antonio
Sorry I truly don't understand your point.You can use $.post to send a form and then return JSON by PHP with errors or status OK.
You can grab attributes this way:
var mail;
$("input").click(function(){
mail = $(this).val();
if(!mail)
mail = $(this).attr("data-mail");
});
$("#submit-button").on("click", function(e)
{
e.preventDefault();
$.post({});
});
You should do this with traditional way: html form, hidden inputs and simple submit button.

PHP form mail to work with invisible form field to filter bots

I read this post: What is a good invisible captcha? about using a hidden field in a web form to stop basic bots from pelting your website with spam mail via your web sites form mail. I'm currently using a php script to process my form mail. I built the script by following a 'bullet proff web form' tutorial I found. It looks like this:
<?php
// Pick up the form data and assign it to variables
$name = $_POST['name'];
$email = $_POST['email'];
$topic = $_POST['topic'];
$comments = $_POST['comments'];
// Build the email (replace the address in the $to section with your own)
$to = 'hello#cipherbunny.com';
$subject = "New message: $topic";
$message = "$name said: $comments";
$headers = "From: $email";
// Data cleaning function
function clean_data($string) {
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
$string = strip_tags($string);
return mysql_real_escape_string($string);
}
// Mail header removal
function remove_headers($string) {
$headers = array(
"/to\:/i",
"/from\:/i",
"/bcc\:/i",
"/cc\:/i",
"/Content\-Transfer\-Encoding\:/i",
"/Content\-Type\:/i",
"/Mime\-Version\:/i"
);
$string = preg_replace($headers, '', $string);
return strip_tags($string);
}
// Pick up the cleaned form data
$name = remove_headers($_POST['name']);
$email = remove_headers($_POST['email']);
$topic = remove_headers($_POST['topic']);
$comments = remove_headers($_POST['comments']);
// Send the mail using PHPs mail() function
mail($to, $subject, $message, $headers);
// Redirect
header("Location: http://foobar/success.html");
I'd like to modify this script so that if a hidden field with the identifier 'other_email' was filled in then the form email wouldn't get sent. I'm guess it's as straight forward as wrapping the above code in an if statement to check if the field is complete. I've tried adding this under the "//Pick up the form data and assign it to variables" code:
$testBot = $_POST['other_email'];
then writing:
if(other_email == "") //If other_email form section is blank then...
{
run all the code above inserted here;
}
else
{
Don't know what I should put here to stop it posting, yet still show the success form so
the spam bot don't know
}
any help much appreciated. I have to say I don't really have a lot of php knowledge, I'm just starting to learn about it and thought form mail would be a good start.
How do I make this work in PhP?
if(other_email == "") //If other_email form section is blank then...
{
run all the code above inserted here;
}
else
{
header("Location: http://foobar/success.html");
}
keeping it very simple, it will work for you..
actually, it will
not submit / mail you anything...so NO SPAM
a simple bot will take it as it did it...
if you can use php on success page, then set a session variable (to make bot think it did its job, something like email_sent=true or success=true) and use that variable in success page, you will do it in else case where bot submitted the form..
Do you mean send message with fields?
Try this:
<?php
// Pick up the form data and assign it to variables
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$topic = $_REQUEST['topic'];
$comments = $_REQUEST['comments'];
// Build the email (replace the address in the $to section with your own)
if($name !== null && $email !== null && $topic !== null && $comments !== null){
$to = 'hello#cipherbunny.com';
$subject = "New message: $topic";
$message = "$name said: $comments";
$headers = "From: $email";
// Data cleaning function
function clean_data($string) {
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
$string = strip_tags($string);
return mysql_real_escape_string($string);
}
// Mail header removal
function remove_headers($string) {
$headers = array(
"/to\:/i",
"/from\:/i",
"/bcc\:/i",
"/cc\:/i",
"/Content\-Transfer\-Encoding\:/i",
"/Content\-Type\:/i",
"/Mime\-Version\:/i"
);
$string = preg_replace($headers, '', $string);
return strip_tags($string);
}
// Pick up the cleaned form data
$name = remove_headers($_POST['name']);
$email = remove_headers($_POST['email']);
$topic = remove_headers($_POST['topic']);
$comments = remove_headers($_POST['comments']);
// Send the mail using PHPs mail() function
mail($to, $subject, $message, $headers);
// Redirect
header("Location: http://foobar/success.html");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=shift_jis" />
<title>Send</title>
</head>
<body>
<form action="#" method="POST">
Name : <input type="text" name="name" /><br />
Email : <input type="text" name="email" /><br />
Topic : <input type="text" name="topic" /><br />
Comments : <textarea name="comments"></textarea><br />
<input type="submit" value="Send" />
</form>
</body>
</html>

Trying To Create A Javascript Alert Window That Doesn't Reload The Page When OK Is Clicked

I have a PHP form that I've set up with a POST method. When all the fields aren't filled out I have a Javascript alert box that pops up and states 'Please fill out all fields!' When I click 'OK' on the alert window it reloads the form behind it clearing all the data that was entered. Is there a function that can keep the alert box's OK button from reloading the entire page? Here's my code:
<?php
if (isset($_POST['brandname']) && isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['email']) && isset($_POST['website'])){
$brandname = $_POST['brandname'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$website = $_POST['website'];
if(!empty($brandname) && !empty($firstname) && !empty($lastname) && !empty($email)){
$to = 'matt#miller-media.com';
$subject = 'Submission Form';
$body = $firstname;
$headers = 'From: '.$email;
if (#mail($to, $subject, $body, $headers)){
}
}else{
echo '<script type="text/javascript">
window.alert("Please fill out all fields!")
</script>';
}
}
?>
You are alerting your user after posting response ... in this case I would re-post the whole form again with its values set to $_POST or variables that were set using it, for example :
<input type='text' name='brandname' value='<?php echo $_POST['brandname'];?>' />
or :
<input type='text' name='brandname' value='<?php echo $brandname; ?>' />
and so on
But in this case I recommend using client-side validation on the form (Using javascript)
Yeah i assume you need something like this:
<script type="text/javascript">
function do_some_validation(form) {
// Check fields
if (! /* Contition 1 */ ) return false;
if (! /* Contition 2 */ ) return false;
if (! /* Contition 3 */ ) return false;
form.submit();
}
</script>
<form onsubmit="do_some_validation(this) return false;" action="script.php" method="post">
// Fields
</form>
This will only submit the form once all JavaScript conditions in do_some_validation are met... Please note this is not advised over and above PHP validation, this should be used purely for comfort for the user not having to submit the page when there's something Javascript can validate against
For any further PHP validation messages, you can either pass variables into GET or SESSION, eg.
<?php
session_start();
if (count($_POST)) {
if (!/* Condition 1 */) $_SESSION['error'] = "Message";
if (!isset($_SESSION['error'])) {
// Proceed
} else header("Location: script.php");
}
?>
On the page:
<?php if (isset($_SESSION['errir'])) {
echo $_SESSION['error'];
unset($_SESSION['error']);
} ?>
Since your code sample is PHP-code, it seems that you are posting the form and validate it server-side, and then you show an alert if any field is empty? In that case, the page has already reloaded, before the alertbox is shown. You are mixing server-side and client-side code.
If you want to show an alert box if the user hasn't filled in all the fields (without reloading the page), you will have to do the validation with JavaScript. You should still keep your PHP-validation as well though!
If you use jQuery for instance, you could do something like this:
$("#your-form-id").submit(function(){
// Check all your fields here
if ($("#input-field-1").val() === "" || $("#input-field-2").val() === "")
{
alert("Please fill out all fields");
return false;
}
});
It can of course be done without jQuery as well. In that case you can use the onsubmit attribute of the form tag to call a JavaScript function when the form is posted, and within that function you do the validation of the form, show an alert box if any field is empty, and then return false from the function to prevent the form from being posted to the server.

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.

Categories