When I sanitize the input fields or text area I face a problem. When someone gave spaces and submit the form, my script accepts the form. But I want not to accept fields until there is not written at least a single character. My code is as follows.
Html
<form action="" method="POST">
<textarea name='text'></textarea>
<input type='submit' name='submit'>
</form>
Php
if(isset($_POST['submit'])){
if(isset($_POST['text']) && !empty($_POST['text'])){
//do whatever but not accept white space
}
}
You can trim whatever you want, just by using
trim()
Which removes characters from both sides of a string.
Documentaion: http://php.net/manual/bg/function.trim.php
trim and preg_replace will do this easily
<?php
echo $text = " this is niklesh raut ";
echo "\n";
$text = preg_replace('/\s+/', ' ',$text);
echo trim($text);
?>
live demo : https://eval.in/818137
OUTPUT :
this is niklesh raut
this is niklesh raut
With new line and tab : https://eval.in/818138
You can either echo out your statement:
<?php
if(isset($_POST['submit'])){
if(empty($_POST['text'])){
echo "Please enter a value.";
}
}
Or, add the required attribute to your input field.
<form action="" method="POST">
<textarea name='text' required></textarea>
<input type='submit' name='submit'>
</form>
Related
I am a beginner and self learner. This might be easy question but it is creating some problem to me. I think I missed something somewhere.
When I write some text in textarea and hit Find and replace button(leaving other two fields empty), the value captured from textarea should appear in the textarea itself and error message should appear outside the textarea. textarea should not be blank. I think message are working fine.
I am not sure if the problem is with the button or action='' in form.
<?php
//find and replace string
//using str_replace(), takes three parameters, $findword, $wordtoreplace, $userinput
if(isset($_POST['text']) && isset($_POST['find']) && isset($_POST['replace'])){
$paragraph=nl2br(htmlentities($_POST['text']));
$find_string=$_POST['find']; //assign the value to be found to the variable
$replace_string=$_POST['replace']; //assign the value to be replaced
if(empty($paragraph)){
echo 'No text to search for.';
}
elseif(empty($find_string)){
echo 'Enter some text to find.';
}
elseif(empty($replace_string)){
echo 'Enter some text to replace with.';
}
else{
echo str_replace($find_string, $replace_string, $paragraph);
}
}
?>
<form action='' method='POST'>
<textarea name='text' rows=20 cols=100 value='<?php echo $paragraph; ?>'></textarea
<br />
<label>Search For</label>
<input name='find' value='<?php echo $find_string; ?>'></input>
<br />
<label>Replace with</label>
<input name='replace' value='<?php echo $replace_string; ?>'></input>
<br />
<button>Find and Replace</button>
</form>
<textarea> doesn't have the value attribute. Provide the content like this:
<textarea name='text' rows='20' cols='100'><?php echo $paragraph; ?></textarea>
Btw, the closing bracket of </textarea was missing
You have to put the output in the midle of textarea open and close tag:
<textarea name='text' rows=20 cols=100><?php echo $paragraph; ?></textarea>
In my php script i have this input field.
<input type="text" name="try" size="10" id="try" maxlength="5" >
What is the easy way to make i require 5 characters and show an error message if they are not only letters.
With HTML5 you can use the pattern attribute:
<input type="text" name="try" size="10" pattern="[A-Za-z]{5}" title="5 alphabetic characters exactly">
This will allow exactly 5 characters, which can only be uppercase or lowercase alphabetic characters.
You can probably do that in jQuery on the client side. You will also need to do it on the server side, since JavaScript can (and will) be bypassed by an attack vector. A regular expression like this will do the server-side validation in PHP.
$rgx = '/[A-Z]{5,}/i';
Combining the approach...
http://www.laprbass.com/RAY_temp_axxess.php?q=abcde
http://www.laprbass.com/RAY_temp_axxess.php?q=ab
http://www.laprbass.com/RAY_temp_axxess.php?q=abcdefg
<?php // RAY_temp_axxess.php
error_reporting(E_ALL);
// A REGEX FOR 5+ LETTERS
$rgx = '/^[A-Z]{5,}$/i';
if (isset($_GET['q']))
{
if (preg_match($rgx, $_GET['q']))
{
echo 'GOOD INPUT OF 5+ LETTERS IN ';
}
else
{
echo "VALIDATION OF {$_GET['q']} FAILED FOR REGEX: $rgx";
}
}
// CREATE THE FORM
$form = <<<ENDFORM
<form>
<input type="text" name="q" pattern="[A-Za-z]{5,}" title="At least 5 alphabetic characters" />
<input type="submit" />
</form>
ENDFORM;
echo $form;
<input type="text" pattern=".{5,}" required />
try this
Assuming the page submits to itself.
Quick and Dirty.
<?php
$errors = array();
if (isset($_POST['try']) & strlen($_POST['try']) != 5 & ctype_alpha( $_POST['try'] != true) {
$error['try'] = "This field must contains 5 characters and contain only a-z and A-Z";
// stop whatever you normally do if submitted.
}
?>
Later on the page where you show this field.
<?php if (isset($errors['try'])) { echo $errors['try']; } ?>
<input type="text" name="try" size="10" id="try" maxlength="5" >
validate your form before view like this and use strlen to check the length of input:
if(isset($_POST['mySubmit'])) {
if(strlen($_POST['try']) < 5) {
$error = "Too short";
}
else {
$valid = true;
//Do whathever you need when form is valid
}
}
else {
if(isset($error)) {
echo "<p>$error</p>";
}
//echo your form here
echo "<form method='post' action='thisPhpScript.php'>
<input type='text' name='try' size='10' id='try' maxlength='5' >
</form>";
}
Haven't tested this so might have syntax errors.
I have a simple php file with a GET from a form to throw up some files from a directory. Quite simple code but I just need to strip from the string ANY characters that are NOT lowercase alpha. How would I go about doing that? (I'm a novice).
Here 'tis:
<?php $text = $_GET['text_string']; ?>
<form method="GET" action="index.php">Please enter some letters: <input type="text" name="text_string" value=""/> and hit <input type="submit" value="enter" />
</form>
<?php /* Split characters into an array */ $array = str_split($text); ?>
<?php foreach($array as $char) : ?>
<img src="glyphs/<?php print ($char); ?>.jpg"/>
<?php endforeach ; ?>
Thanks!
To lowercase (note that you also can use mb_strtolower for better charset handling, but in this case you're only going to keep ASCII chars anyway so strtolower is enough):
$text = strtolower($text);
To remove all non-alpha chars using preg_replace:
$text = preg_replace('/[^a-z]/', '', $text);
I am just starting to learn php, how would I initiate a echo statement after a submit button is pushed, or even a anchor tag.
Here is my code so far
form name="myform" method="get" actions="madlib01.php"
Name: <input type="text" name="name" /> <br />
<input type="submit" name="submit" />
form
<?php
$Name = $_GET['name'];
$hello .= "Hello $Name";
echo $hello //I would prefer the echo to happen after the submit button is hit
?>
the correct attribute for your form tag is "action", not "actions"
When the form is submitted, a new request is sent to the server (in your case, using GET).
So to do it all in one page:
form.php:
<form action="form.php" method="GET">
<input type="text" name="name"/>
<input type="submit">
</form>
<?PHP
if (! empty($_GET['name'])){
echo 'Hello, ' . $_GET['name'];
}
?>
You will first need to check if PHP has received your GET parameter using isset or array_key_exists:
if(isset($_GET['name']) && !empty($_GET['name'])) {
$Name = $_GET['name'];
echo "Hello $Name";
}
or:
if(array_key_exists('name', $_GET) && !empty($_GET['name'])) {
$Name = $_GET['name'];
echo "Hello $Name";
} else {
//example: default to something if nothing has been passed
echo "Hello Guest";
}
Also note, if you're submitting to the same page, you can omit the action attribute from your form tag altogether:
<form method="GET">
echo $hello
You've just gained an HTML-injection vulnerability. If someone sends your user to:
http://www.example.com/madlib01.php?name=<script>stealYourCookies()</script>
you've got problems.
Yes, this is a My First PHP Script. That doesn't make security optional. This is a mistake every tutorial makes: teaching bad practice from the start, treating correctness (and security, which is a subset of correctness) as an optional extra.
The result is that most PHP code out there is full of holes. But there's no need for yours to be! Every time you place a pure-text string into a surrounding HTML context, escape it properly:
echo htmlspecialchars($hello);
I tend to define a function with a shorter name than ‘htmlspecialchars’ to do that for me, as I'm lazy.
<?php
function h($text) {
echo(htmlspecialchars($text, ENT_QUOTES));
}
$name= '';
if (isset($_REQUEST['name']))
$name= trim($_REQUEST['name']);
?>
...
<?php if ($name!=='') { ?>
<p> Hello, <?php h($name); ?>! </p>
<?php } ?>
<form method="get" action="madlib01.php">
<p>
<label for="namefield">Name:</label>
<input id="namefield" type="text" name="name" />
</p>
<p>
<input type="submit" />
</p>
</form>
Now if you say your name is Mister <script>, the page will greet you exactly as such, angle brackets and all, instead of trying to run JavaScript. This is the correct output and thus also secure.
I have two variables containing some html code, and another variable containing code for a html form. I am trying to expand a string within the second to pass it as a parameter to a function, however this causes some errors.
My make popup function is very simple:
function popup(htmlcode){
child1 = window.open ("about:blank");
child1.document.write(htmlcode);
child1.document.close();
}
The code that uses the above function
<?php
$blah = "<h1>Well</h1>"; $test = "<h2>Done</h2>";
echo '<script type="text/javascript" src="fetchlayers.js"></script>';
$formcode = "<form action=\"process.php\" method=\"post\" enctype=\"multipart/form-data \">
<label for=\"file\">Filename:</label>
<input type=\"file\" name=\"file\" id=\"file\"/>
<br />
<input type=\"submit\" name=\"submit\" value=\"Submit\" onclick=\"setTimeout(function() { sendInfo(\"".$blah."\", \"".$test."\"); } ),1250);\" />
</form>";
echo "<h1>hello</h1>
<div id='form'>
<a href='#' onclick=\"popup('" . htmlentities($formcode) . "'); return false;\">
click here</a>
</div>";
This produces decent enough html code, however firebug gives me an error that I have an unterminated string lateral. I cannot find where this is. I understand the way I have done this is not ideal, but I am learning and do not know a better way at present. I appreciate any input
edit: OK, so the problem was that I had unterminated string literals, which were \n characters. I made the string into one line and it called the function correctly.
Is it not possible to break one echo statement into multiple lines?
Now the problem is with the html generated in the popupwindow. Some of the code is actually printed to the screen, why is this?
<form action="process.php" method="post" enctype="multipart/form-data "><label for="file">Filename:</label><input name="file" id="file" type="file"> <br><input name="submit" value="Submit" onclick="setTimeout(function() { sendInfo(" type="submit"><h1>Well</h1>", "<h2>Done</h2>"); },1250);" /></form>
See the image here:
A better way to do this is to open an HTML or PHP page that already has the form code in it, instead of opening about:blank and passing it dynamically.
There is no reason you should ever have to pass HTML into a Javascript function just so it can be directly written to document.
If you absolutely have to keep the popup function as is, I found a solution with help from this answer to "How do I escape a string inside javascript inside an onClick handler?".
<?php
$blah = "<h1>Well</h1>"; $test = "<h2>Done</h2>";
echo '<script type="text/javascript" src="fetchlayers.js"></script>';
$formcode = '<form action="process.php" method="post" enctype="multipart/form-data ">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"/>
<br />
<input type="submit" name="submit" value="Submit" onclick="setTimeout(function() { sendInfo(\\x27'.$blah.'\\x27, \\x27'.$test.'\\x27); }, 1250);" />
</form>';
echo "<h1>hello</h1>
<div id='form'>
<a href='#' onclick='popup(\"" . addslashes(str_replace("\n", ' ', $formcode)) . "\"); return false;'>
click here</a>
</div>";
?>
Before edit:
Maybe you can do it differently.
Javascript functions:
function popup(id, params){
var html = document.getElementById(id).innerHTML;
if (params != undefined) {
html = findAndReplaceStrings(html, params);
}
var child1 = window.open ("about:blank");
child1.document.write(html);
child1.document.close();
}
function findAndReplaceStrings(text, json) {
for (var x in json) {
text = text.replace(x, json[x]);
}
return text;
}
HTML hidden code:
<div style="display:none;" id="process">
<form action="process.php" method="post" enctype="multipart/form-data ">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"/>
<br />
<input id="submit" type="submit" name="submit" value="Submit" onclick="setTimeout(function() { sendInfo('{param1}', '{param2}'); } ), 1250);" />
</form>
</div>
HTML link with json:
<a href="#" onclick="popup('process', {'{param1}':'<h1>Well</h1>', '{param2}':'<h2>Done</h2>'}); return false;">
click here</a>
You must escape the carriage returns (\n) by doing
$formcode = str_replace("\n", "\\n", $formcode);
You also have to escape the quotes
$formcode = str_replace("'", "\\'", $formcode);
You can combines those two lines into a single one:
$formcode = str_replace(array("\n", "'"), array("\\n", "\\'"), $formcode);
The submit button has an extra ) which closes the setTimeout function too early. The specific spot is inside:
} ),1250
you should also probably think about using single quotes inside the php string to make it all easier to read. And because you're using double quotes you don't have to break out of the string to insert the content of the variables $blah and $test.
something like this should work:
$formcode = "...
<input type='submit' name='submit' value='Submit'
onclick='setTimeout(function() { sendInfo(\"$blah\", \"$test\"); },1250);' />
...
";
EDIT:
looks like it's closing the onclick too early now. Matching these as the start and end quotes:
onclick=\"setTimeout(function() { sendInfo(\"
I changed the sendInfo line to the following, ran it and looks like it's working. The single quote is escaped here so it doesn't prematurely close the call to popup().
sendInfo(\'".$blah."\', \'".$test."\');