Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
After reading a lot of tutorials I just want to be sure to be on the safe side.
I made a contact formular which looks like this
<form name="contakt" accept-charset="UTF-8" method="post" action="./mail.php">
<input type="text" name="name" />
<input type="text" name="email" />
<input type="text" name="tel" />
<input type="submit" value="Send" name="submit" />
<textarea name="message"></textarea>
</form>
I validate via jQuery if the name and message is not empty and not only full of spaces
and I check the email via jquery with the following script
function ismailornot(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
Now when my variables get passed and I am on my mail.php is it more then enough to check on top my of script the $_SERVER['HTTP_REFERER'] and look if those variables came from my own script ? Or can you modify $_SERVER variables too ?
Or do I have basicly to check EVERY passed variable again to be on a safe side ?
For example : http://www.w3schools.com/php/php_secure_mail.asp
is this script 1oo% safe from injections ?
Thanks for helping me out :)
The way: Check EVERY passed variable again to be on a safe side
Try this after some mods to fit your needs its a piece from Larry Ullman book :
function spam_scrubber($value) {
// List of very bad values:
$very_bad = array('to:', 'cc:', 'bcc:', 'content-type:', 'mime-version:','multipart-mixed:',
'content-transfer-encoding:', '<script>');
// If any of the very bad strings are in
// the submitted value, return an empty string:
foreach ($very_bad as $v) {
if (stripos($value, $v) !== false){ return '';}
}
// Replace any newline characters with spaces:
$value = str_replace(array( "\r", "\n", "%0a", "%0d"), ' ', $value);
//remove html tags:
$value = htmlentities($value,ENT_QUOTES);
// Return the value:
return trim($value);
} // End of spam_scrubber() function.
// Clean the form data:
$scrubbed = array_map('spam_scrubber', $_POST);
if(isset($from)) {
$from = $scrubbed['from'];
}else{
$from = '';
}
// Minimal form validation:
if (!empty($from) && !empty($scrubbed['comments']) ) {
// Create the body:
$body = "Name: {$from}\n\nComments: {$scrubbed['comments']}";
$body = wordwrap($body, 70);
// Send the email:
mail('YOUR_EMAIL', 'Contact Form Submission', $body, "From: {$from}");
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
Improve this question
I need someone to help me with php guides on how i can echo every user input to the screen...
Example:
Html
<form action"bot.php" method="POST">
<input type="text" name="name">
<input type="submit" name="submit" value="submit">
</form>
Php Code
<?php
//request name from form
$username = $_REQUEST['username'];
//create function
function msg()
{
$username = $_POST['username'];
echo "$username";
echo "\r\n";
}
//echo input to screen
if (isset($_POST['submit']))
{
msg();
}
If I click submit button it will display my input text to the screen, that's fine, If I input another username click on submit button again to display under my previous output to screen...Instead PHP overide my previous output with new username submitted..
Will be glad if anyone can help
This example uses a session. You don't need anything external other than a working PHP installation. I've added comments in the code, but the basic flow is,
start a session
read the names from the session. If this is a new session, default the names to an empty array
read the submitted name
append the submitted name to the existing names
write the existing names to the session
<form action="bot.php" method="POST">
<input type="text" name="name">
<input type="submit" name="submit" value="submit">
</form>
<?php
// Always start the session
session_start();
// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Read the existing names from the session. Default to an empty array if none are set
$existingNames = $_SESSION['names'] ?? [];
// Grab the submitted name
$name = $_POST['name'];
// Add it to the end of the list
$existingNames[] = $name;
// Overwrite the entire session's list
$_SESSION['names'] = $existingNames;
// Output something interesting
echo 'Welcome ' . $name;
echo '<br>';
echo 'There are ' . count($existingNames) . 'name(s).';
echo '<br>';
foreach ($existingNames as $storedName) {
echo $storedName;
echo '<br>';
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm currently coding a website in html and CSS. I have learned, php well at least enough for the thing i'm currenly trying to make. So I basically have the following,
How do you accomplish getting a number/constant 40 and subtracting that from a user inputted number. In a html document
<form action="welcome.php" method="post">
$string = "cool";
Hours:<input type ="text" name ="name"<br>
$string = "cool"
Hours: <input type="text" name="name"><br>
<input type="submit">
echo 40-"$cool";
</form>
this is wrong and will return the echo and original php code. If i wrap it in php it will display an error
The $cool should not be quoted. Also, why are you setting the $string two times with same value?
<form action="welcome.php" method="post">
<?php $string = "cool"; ?>
Hours:<input type ="text" name ="name"><br>
Hours: <input type="text" name="name"><br>
<input type="submit">
<?php echo 40-$cool; ?>
</form>
Also, the file itself has to be php, not html.
Firstly, you're injecting PHP inside HTML, you can't do that. It will produce a parse error, if your file is indeed a .php extension.
Edit: As noted in comments, you can inject PHP inside HTML, just as long as you include PHP tags and enclosed using <?php ?> or <?= ?>; the latter being short open tag syntax.
Now, as I understand it, you want another field where a user will enter a number, then substract (from user input) your number 40 being a constant, and add on the word "cool" after the result.
Here's how and with the user's name echo'd also if filled and checking if it's a number using is_numeric().
Sidenote: Using the number 2 in the input and with the name John, will output "38 cool John".
<?php
if(isset($_POST['submit'])){
if(isset($_POST['number']) && is_numeric($_POST['number'])){
$string = "cool";
$name = $_POST['name'];
$number = $_POST['number'];
$constant = 40;
$total = $constant - $number;
echo "$total $string $name";
} // brace for if(isset($_POST['number'])...
else{
echo "It's not a number";
}
} // brace for if(isset($_POST['submit']))
?>
<form action="" method="post">
Name:<input type ="text" name ="name"<br>
Number: <input type="text" name="number"><br>
<input type="submit" name="submit" value="Submit">
</form>
Footnotes:
You can also use an alternate method to echo the variables, such as:
echo "$total $string $name"; with a space between
echo "$total-$string-$name"; with a hyphen seperator
as noted in comments
The dot concatenation is just force of habit on my part.
Sidenote: You must use double quotes for this, since variables only get parsed inside double quotes.
Otherwise, you would get the following parse error using echo $total $string $name;:
Parse error: syntax error, unexpected '$string' (T_VARIABLE), expecting ',' or ';'...
Using echo $total-$string-$name; would work, but it will only echo the value from the substraction, instead of the intended echo'd string(s).
You don't need PHP for this at all. You can just use some basic java script. To use php, you need to set this whole page up differently.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to create a new CSV File with some values in it and store under my upload directory. Can anyone guide me how I can create a CSV and what code to be written in PHP. Also I want the CSV file with name of input parameter of the form and with current date.
Example: Test_24-04-2014.csv.
Also It will great if you can advise me how I can define a Column Header.
Example:
----------------------------------------
Sr. No Name Invt.
----------------------------------------
Consider this as an example, first off, of course you need a form:
Sample Form:
<!-- HTML -->
<form method="POST" action="processes_the_form.php">
Sr No.: <input type="text" name="srno" /><br/>
Name: <input type="text" name="name" /><br/>
Invt.: <input type="text" name="invt" /><br/>
<input type="submit" name="submit" value="Add to CSV" />
</form>
Then process it in PHP:
<?php
// set delimitter (tab or comma)
$delimitter = chr(9); // this is a tab
$newline = "\r\n"; // CRLF or whatever you want
// handle form submit
if(isset($_POST['submit'])) {
// gather values
$srno = $_POST['srno'];
$name = $_POST['name'];
$invt = $_POST['invt'];
// check for the csv file
$directory = ''; // sample: path/to/csv/
$prefix = 'Test_';
$date = date('d-m-Y');
$file_path = $directory . $prefix . $date . '.csv';
// initial creation
if(!file_exists($file_path)) {
$file = fopen($file_path, 'w');
// add the headers
$headers = array('SrNo', 'Name', 'Invt');
fputcsv($file, $headers, $delimitter);
fclose($file);
}
$formatted_data = array($srno, $name, $invt);
// put them inside the file and append on end
$file = fopen($file_path, 'a');
fputcsv($file, $formatted_data, $delimitter);
fclose($file);
}
?>
Note: You may need to set your permissions to that PHP to create/write on that particular path
To define column headers in CSV, you imply add one line at the beginning containing your columns headers. For example:
"First name", "Family name", "Age"
"John", "Doe", "21"
"Jack", "Smith, "34"
To generate CSV files from PHP, you can use the fputcsv function
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
My problem is that i have a form which i made in HTML which contains 5 fields which are always required (name, city, adres, house number and phone number)
Then I have 11 fields where only 1 field is required.
My question is specific to those 11 fields only.
So basically when the user submits the form (first 5 are filled in properly) it needs to give some kind of error.
But when 1 or more of those 11 input fields are filled in it needs to go through.
I tried countless of different things. And i just read something about placing those 11 input fields in a class="" and make a custom validator of some kind.
I don't know if this is the correct solution (and if it is what does a custom validator look like)
I'm not experienced in php or JQ or JS that's why this is such a big problem for me.
I hope my question is formulated correctly, if not let me know!
If I'm understanding you correctly, you have 11 fields and at least one of them must be filled.
This will require some custom validation, yes.
First, I would suggest having the fields like this:
<input type="text" name="options[]" />
The name can be whatever you want, but the important thing is those square brackets. They define input as an array, so with 11 inputs you'll have 11 items. If you need to tell them apart, try:
<input type="text" name="options[something]" />
Now, the server-side validation. This is the most important part - JS validation is secondary.
To validate this field in PHP, do this:
$completedFields = array_filter($_POST['options']);
if( !$completedFields) die("You did not fill in any of the 11 inputs!");
Simple!
And finally, some JS validation. Presumably you have some kind of submit handler, but if not have your form like this:
<form action="..." method="post" onSubmit="return validationFunction(this);">
Now your JS can be like this:
function validationFunction(form) {
// if you're using name="options[]":
var options = form['options[]'];
// if you're using named options like options[something]
var options = (function() {
var elms = form.elements, l = elms.length, i, ret = [];
for( i=0; i<l; i++) {
if( elms[i].name.match(/^options\[.*\]$/)) ret.push(elms[i]);
}
return elms;
})();
// then do this:
var l = options.length, i;
for( i=0; i<l; i++) {
if( options[i].value != "") return true;
}
alert("Please fill out at least one of the options.");
return false;
}
Hope this helps!
For a server-side validation, use a quick count check
$completedFields = 0;
if (!empty($_POST['fieldName1'])) $completedFields++;
if (!empty($_POST['fieldName2'])) $completedFields++;
// and so on...
if ($completedFields > 0) {
// validated
} else {
// error
}
You could also use a POST array depending on how the fields are conventionally named and then foreach through each check in a similar manner
HTML:
Field 1 <input type="text" name="extra_field[]" value="" /><br />
Field 2 <input type="text" name="extra_field[]" value="" /><br />
Field 3 <input type="text" name="extra_field[]" value="" /><br />
...
Field 11 <input type="text" name="extra_field[]" value="" /><br />
Then in PHP:
<?php
$valid = FALSE;
$extra_fields = isset($_POST['extra_field']) ? $_POST['extra_field'] : array();
foreach ($extra_fields as $field) {
if (!empty($field)) {
$valid = TRUE;
break;
}
}
if ($valid == FALSE) {
echo 'Ooops, you must complete at least one of the 11 fields';
}
?>
if (!empty($_POST['field1'])OR !empty($_POST['field2']) OR !empty($_POST['field3'] ))
{
// SUBMIT FORM
} else {
// display error message
}
This is for 3 fields , you can extend it to 11. Hope this helps.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Simple PHP Mailer Script
i run a small website and we have had requests for a mailing list....
i have found a simple free script to add email addresses to a txt file - "email.txt" (which is protected) is csv format (email1#yahoo.com,email2#yahoo.com,blah,blah,blah)
this script works flawlessly.....
however it is a nuciance to go through this text file to manually remove email addresses when users cancel their subscription to the mailing list.....
i am having trouble creating a simple script to remove email addresses....
so far i have ....
<html>
<body>
<form method="post" action="">
<p>Email Address: <input type="text" name="email"></p>
<input type="submit" value="Cancel Newsletter" name="submit">
</form>
<?php
$email = $_POST["email"];
$text = file_get_contents("email.txt");
$oldWord = "$email";
$newWord = "";
$text = str_replace($oldWord , $newWord , $text);
$fp = fopen('email.txt', 'w');
fwrite($fp, $text);
fclose($file);
?>
</body>
</html>
this works perfect to remove the email address from the list.....
however i cannot figure out how to echo a comment dependant on whether
str_replace($oldWord , $newWord , $text);
is successful at replacing the email address with an empty space....
if the code removes email address i would like "You Have Been Removed From The Flying Shuttle Newsletter."
and if the email address isnt there (code doesnt replace email with empty space)
"The Email Address You Specified Is Not On The Mailing List!"
thanks in advance for any help
You could just compare the length of the returned string.
$newText = str_replace($oldWord, $newWord, $text);
if (strlen($newText) < strlen($text)) {
// Success
} else {
// Failure
}