How to implement code checking into my submit form - php

i have the following form
<form action="/wp-content/themes/wallstreet/welcome.php" method="post" class="basic-grey">
<h1>Form
<span>Please fill all the texts in the fields.</span>
</h1>
<label>
<span>Your Nickname* :</span>
<input id="name" type="text" name="name" placeholder="It will appear in the text" />
</label>
<label>
<span>Your Email* :</span>
<input id="email" type="email" name="email" placeholder="Valid Email Address" />
</label>
<label>
<span>Message* :</span>
<textarea id="messagebook" name="messagebook" placeholder="The text that will appear" maxlength="80"></textarea>
</label>
<label>
<span>Code* :</span>
<input id="code" type="text" name="code" placeholder="The Code That we sent to your email" maxlength="8" />
</label>
<label>
<span> </span>
<input type="submit" class="button" value="Send" />
</label>
</form>
which uses the following php, this php basically posts the message value into a txt file
<?php
$var = $_POST['messagebook'];
file_put_contents("/var/www/wordpress/wp-content/themes/wallstreet/data.txt", $var . "\n", FILE_APPEND);
exit();
?>
but i want the submit button only work if my code field matches with the codes that are stored in a txt file like this
zACHAS5r
rKUzob3X
omqYjVQZ
BeF375BG
rFKQomMX
y8EVBTGH
Z7icxNoD
wnZ5qBvK
ftbPiCZa
sXJKDETK
wYDVLDPd
AjURjBdZ
LZR4fbtk
gmFY89TV
BAWDxpZ2
bGLLd9Az
qg4C93wN
YJnrDh2c
jwH6hV9h
tm3S4f5j
MU2ikfbu
ZXnUpfmY
hijZPTk4
C2oWha3T
irTg9oUA
jmjLDvL3
jUbiBtJo
gCCAQx6Z
Theorically i could make it work with this code, but i dont know where to implement it
function is_valid($code)
{
return in_array($code , explode(' ',file_get_contents('coderoute')));
}
EDIT1: Currrently i have this, and i get this error
<?php
function is_valid($code)
{
return in_array($code , explode(' ',file_get_contents("/wp-content/themes/wallstreet/codes.txt")));
}
$code = $_POST['code'];
if (is_valid($code)) {
$var = $_POST['messagebook'];
file_put_contents("/var/www/wordpress/wp-content/themes/wallstreet/data.txt", $var . "\n", FILE_APPEND);
}
exit();
?>
PHP Warning:
file_get_contents(/wp-content/themes/wallstreet/codes.txt): failed to
open stream: No such file or directory in
/var/www/wordpress/wp-content/themes/wallstreet/welcome.php on line 4,

$code = $_POST['code'];
$message_book = $_POST['messagebook'];
if(is_valid($code)) {
file_put_contents('/var/www/wordpress/wp-content/themes/wallstreet/data.txt', "{$message_book}\n", FILE_APPEND);
exit();
}
function is_valid($code) {
$codes = file('/var/www/wordpress/wp-content/themes/wallstreet/codes.txt', FILE_IGNORE_NEW_LINES);
return in_array($code, $codes);
}
You've mentioned PHP Warning of No such file exists. You could provide absolute path of codes.txt to check if it works right.

Code you need to check is in $_POST['code'].
So pass it as argument to is_valid function:
<?php
$code = $_POST['code'];
if (is_valid($code)) {
$var = $_POST['messagebook'];
file_put_contents("/var/www/wordpress/wp-content/themes/wallstreet/data.txt", $var . "\n", FILE_APPEND);
}
exit();
?>

You can use a JavaScript array with the codes, this array will be filled with PHP, if the entered code is not in the array, the submit button will not submit the form.
Copy-paste next code in a PHP file and open it in your browser :
<html>
<head>
<script type="text/javascript">
function check_code () // ◄■ FUNCTION CALLED FROM THE FORM.
{ var arr = [ <?php // ▼ FILL JAVASCRIPT ARRAY WITH CODES FROM FILE ▼
$arr = explode( PHP_EOL,file_get_contents('coderoute.txt') );
echo "'" . implode( "','",$arr ) . "'";
?> ];
var code = document.getElementById("code"); // ◄■ FIELD IN FORM.
if ( arr.indexOf( code.value ) == -1 ) // ◄■ SEARCH CODE IN ARRAY.
{ alert("Code not found.");
return false; // ◄■ FORM WILL NOT BE SUBMITTED.
}
return true; // ◄■ FORM WILL BE SUBMITTED.
}
</script>
</head>
<body>
<form action="somescript.php" onsubmit="return check_code()"> <!-- ◄■ JS FUNCTION -->
<input type="text" id="code" name="code"/> <!-- ◄■ CODE FIELD -->
<br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Notice how the JavaScript array is filled with PHP, the PHP script reads the codes from the file and echo them as the array items of the JavaScript array. Right click the page to see the source code and watch how the JavaScript array was filled.

Related

How do you make button save form data on a csv file and redirect you to a new page at the same time?

I am trying to make a button that saves form data on a file and redirects you afterwards, but although the save function works just fine, the redirection doesn't happen. I've tried only href and formaction so far. Any suggestions?
Paste bin : pastebin
Thank you for your time reading this !
the code:
<html>
<head></head>
<footer>
<form method="post">
<input type="radio" id="html" name="fav_language" value="private_number" checked="checked">
<label for="html">private_number</label><br>
<input type="radio" id="css" name="fav_language" value="clieant_number">
<label for="css">clieant_number</label><br>
<input type="text" id="fname" name="fname" maxlength="11" autocomplete="off" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" required >
<button type="submit" name="BUY"><i class="arrow right"></i></button>
</form>
</footer>
<?php
$numurs = $_POST['fname'];
$Partners = $_POST['fav_language'];
if ($numurs){
$f = fopen('numurs.csv', 'w');
fputcsv($f, Array($numurs, $Partners));
fclose($f);
}
?>
</body>
</html>
You can use PHP's header() function for this. Change the PHP part to this
<?php
$numurs = $_POST['fname'];
$Partners = $_POST['fav_language'];
if ($numurs){
$f = fopen('numurs.csv', 'w');
fputcsv($f, Array($numurs, $Partners));
fclose($f);
header('Location: '.$_SERVER['REQUEST_URI']);
exit;
}
?>

send a php webpage to folder and dispay the content as html

would it be possible to have a html/php template on index.php say for example (a news webpage template and then anyone can edit the title, paragraphs only, then on submit it then sends the webpage with the data stored to a paste bin like url so who ever visits that url say http://localhost/news/jjeh3bndjks they would only be able to view to content and not edit.
I would like to use something like this
<?php
if ($_POST) {
$pasteID = uniqid();
$paste = fopen("pastes/".$pasteID.".php", "w");
$contents = $_POST['pasteContents'];
fwrite($paste, $contents);
header('Location: /pastes/'.$pasteID.'.php');
}
?>
<form action="" method="POST">
<input type="text" name="pasteContents" placeholder="write here" />
<button type="submit" tabindex="0">submit</button>
</form>
but for some reason when i add another input box or try to send anymore data it fails or just gives me the last input given is there a way to send a whole page this way?
any help would be appreciated
You can use file_get_contents with the following code:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
parse_str(file_get_contents('php://input'));
echo param1 . '<br />' . param2;
} else {
?>
<form method="post">
<input type="text" name="param1" value="param1" />
<input type="text" name="param2" value="param2" />
<input type="submit" value="submit" />
</form>
<?php } ?>
(You can test it here)
Although, I did success to use $_POST too:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo $_POST['param1'] . '<br />' . $_POST['param2'];
} else {
?>
<form method="post">
<input type="text" name="param1" value="param1" />
<input type="text" name="param2" value="param2" />
<input type="submit" value="submit" />
</form>
<?php } ?>
Here

HTML Form not posting to PHP file

I am currently creating an HTML form that has 2 fields; name and an address. It also has a way of selecting one of 2 options. The form will either be used to look up the address of a person. In this case, only the name field is required to be filled out. The other option is to add a person to the file. In this case both fields need to be filled out. For some reason, I am not able to get the values that inputted from the form into my PHP file. Please help.
Here is my HTML Form
<html>
<head>
<title> Form </title>
</head>
<body>
<form action="action_page.php" method="post">
<div>
<label for="name">Name: </label>
<input id="name" type="text" name="name"><br>
</div>
<div>
<label for=address">Address: </label>
<input id="address" type="text" name="address"><br>
<input type="radio" name="action" value="lookup">Lookup<br>
<input type="radio" name="action" value="add">Add<br>
<input type="submit" name="submit"><br>
</form>
</body>
</html>
Here is my PHP file
<html>
<head>
<title> PHP </title>
</head>
<body>
<?php
$name = $_POST['name'];
echo "<p>",$_POST["name"],"</p>";
echo "<p>",$_POST["action"],"</p>";
echo "<p>",$_POST["address"],"</p>";
$address = array();
if($_POST["action"]=="lookup"){
$fh = fopen("address.txt","r") or die("No such file found.");
while(!feof($fh)) {
$line = fgets($fh);
$info = explode("|",$line);
$address[$info[0]]=$info[1];
}
if(array_key_exists($_POST["name"],$address)) {
echo "<p>",$_POST["name"],"<p>";
echo "<p>",$address[$_POST["name"]],"</p>";
}
?>
<body>
</html>
The error was in
echo "<p>",$_POST["name"],"</p>";
It should be
echo "<p>".$_POST["name"]."</p>";
and same for others

PHP Form Validation - displaying errors on the same page

I have a form and I'm wanting to display error messages at each input if it's not filled in correctly.
Here is the code so far:
HTML:
<form id="contactForm" action="contact.php" method="post">
<div>
<input type="text" name="name" id="name" placeholder="Your Name" maxlength="65" tabindex="1">
<label for="name">Name</label>
<span class="error"><?php include 'contact.php'; echo "$nameErr";?></span>
</div>
<div>
<input type="email" name="_replyto" id="email" placeholder="Your Email" maxlength="30" tabindex="2">
<label for="email">Email</label>
<span class="error"><?php include 'contact.php'; echo "$emailErr";?></span>
</div>
<div>
<textarea name="message" id="message" rows="10" placeholder="Your Message..." maxlength="1000" tabindex="3" ></textarea>
<label for="message">Your Message</label>
<span class="error"><?php include 'contact.php'; echo "$commentErr";?></span>
</div>
<div>
<input type="submit" value="Send" tabindex="4">
</div>
</form>
PHP:
<?php
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
/* The function takes one argument: a string.
* The function returns a clean version of the string.
* The clean version may be either an empty string or
* just the removal of all newline characters.
*/
function spam_scrubber($value) {
// List of very bad values:
$very_bad = array('to:', 'cc:', 'bcc:', 'content-type:', 'mime-version:', 'multipart-mixed:', 'content-transfer-encoding:');
// 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);
// Return the value:
return trim($value);
} // End of spam_scrubber() function.
// Clean the form data:
$scrubbed = array_map('spam_scrubber', $_POST);
$nameErr = $emailErr = $commentErr = "";
$name = $email = $comment = "";
// Form validation:
if (empty($scrubbed['name'])){
$nameErr = "Please tell me your name";
}
} // End of main isset() IF.
?>
I have a span in the html that contains a variable from the PHP file. The variable is meant to diaply an error message if the field isn't completed. At the moment however, if I click send without any fields being filled in, it just goes to a blank page. This blank page is the contact.php. I want it to stay on contact.html and display the errors.
The above code is only validating the name field at the moment.
Any help with this would be highly appreciated.
Thanks.
You are getting a blank page because the form is submitting. You need to prevent it from submitting until the validation is complete.
In JavaScript, use a onsubmit="return validateForm()". Make this function return true if the fields are valid, false if not, and in there you can set the content of your error spans.
So,
<form id="contactForm" action="contact.php" onsubmit="return validateForm()" method="post">
and you will need to write the validateForm function.
This should be a good place to start!

How do you create a php file editor in php

I am trying to create a php file that can edit other php files on my website. I am able to do this except for when there is html in the php file that I want to edit. Since I am using a textarea to display/edit the php file contents, what I have built does not work when there is a textarea tag in the php file that I want to edit. What I have so far is below. The solution does not need to resemble this.
<?php
if ($_POST['file_text']){
file_put_contents($_POST['filename'], $_POST['file_text']);
$filename = $_POST['filename'];
echo "<script>
window.location = '_editor.php?filenm=$filename'
</script>";
}
else {
$myfilename = $_GET['filenm'];
if(file_exists($myfilename)){
$file_text= file_get_contents($myfilename);
}
echo "
<h3>$myfilename</h3>
<form name='input' action='_editor.php?filenm=$myfilename' method='post'>
<textarea name='contrib_entrybox' id='contrib_entrybox' rows='50' cols='180'>
$file_text
</textarea>";
?>
<?php
// configuration
$url = 'http://domain.com/backend/editor.php';
$yourfilePath = '/path/to/txt/file';
// check if form has been submitted
if (isset($_POST['text'])){
// save the text contents
file_put_contents($yourfilePath, $_POST['text']);
// redirect to form again
header(sprintf('Location: %s', $url));
printf('Moved.', htmlspecialchars($url));
exit();
}
// read the textfile
$text = file_get_contents($yourfilePath);
?>
<!-- HTML form -->
<form action="" method="post">
<textarea name="text"><?php echo htmlspecialchars($text) ?></textarea>
<input type="submit" />
<input type="reset" />
</form>
<div id="sample">
<script type="text/javascript" src="http://js.nicedit.com/nicEdit-latest.js"></script> <script type="text/javascript">
bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });
</script>
<h4>
Second Textarea
</h4>
<textarea name="area2" style="width: 100%;">
Some Initial Content was in this textarea
</textarea><br />
</div>

Categories