<label for="first_name">* First Name </label>
<input type="text" name="first_name" maxlength="64" value=<?php echo formatPhone(clean_input($_POST['first_name']); ?>>
I have a form where I want to enter a first name. I want the fields to take only alphabets(no numbers). Also when a user enters something like John Doe separated by multiple white spaces, I want it to separate the two words only by a single space. I am not sure how this is done in php.
This will let pass only ascii names and split the input properly:
if (preg_match("~^([A-Z][a-z]+\s*)+$~gm", $value)) {
// valid
$array_of_names = preg_split("~\s+~gm", $value);
// or
$normalized_name = preg_replace("~\s+~", " ", trim($value));
}
Related
I am creating a social site and in the registration code someone can enter only spaces in the input fields.
I don't want them to enter any spaces in the fields except for the password one.
I have tried a bunch of things, empty, trim, htmlentities !trim and some more I forgot. None of them worked. Some of them gave the first name the value of 1.
What am I missing?
Below is a list of things I have tried (not at the same time).
$first_name = trim(strip_tags(filter_var($_POST['first_name'], FILTER_SANITIZE_STRING)));
str_replace(' ', ' ', $first_name);
if (empty($first_name)) {
echo "Fill in first name to sign up";
}
if (!ctype_alnum($first_name)) {
echo "Invalid first name, it only may contain letters or digits";
}
$first_name = $_POST['first_name'] ?? '';
if (empty($first_name)) {
echo "Fill in first name to sign up";
}
if (!ctype_alnum($first_name)) {
echo "Invalid first name, it only may contain letters or digits";
}
$first_name = htmlentities(trim(strip_tags(filter_var($_POST['first_name'], FILTER_SANITIZE_STRING)));
if (empty($first_name)) {
echo "Fill in first name to sign up";
}
if (!ctype_alnum($first_name)) {
echo "Invalid first name, it only may contain letters or digits";
}
Use regular expressions. The following checks it to be at least 5 symbols and contain just letters and digits;
$firstName = trim($_POST['first_name']);
if (!preg_match("/^[a-zA-Z0-9]{5,}$/", $firstName)){
echo 'Invalid';
}
More information on preg_match() can be found here.
Hey i have simple solution regarding your question try one
If you want to submit only text and whitespace than use this one
<input type="text" name="Name" required pattern="[a-zA-Z ]+" >
If you want to submit number and whitespace than use this one
<input type="text" name="Name" required pattern="[0-9 ]+" >
If you want to insert text not whitespace than use this one
<input type="text" name="Name" required pattern="[a-zA-Z]+" >
Use any line according to your requirements no extra line of code or condition simple and secure
I am pushing ids to an array but there might be only one single id too, I then need to send this value to an input text:
<input class="form-control" type="text" id="portfolioTitle" value="<?php echo implode(", ", $ids); ?>">
The problem is that if I only have 1 single id, I get this as value:
<input class="form-control" type="text" id="portfolioTitle" value=", 128545">
How can I remove the comma if I only have a single value, like the following?
<input class="form-control" type="text" id="portfolioTitle" value="128545">
Though of doing a foreach for the array before to echo the values but I am wondering if there is a better way.
Using implode() on your array as you're doing now is the correct way to display it as a string. The output you're seeing suggests you might have an empty element in your array which is where filtering comes in.
<?php echo implode(', ', array_filter($ids)); ?>
array_filter() is going to remove any elements from your array that are equal to false. This will strip out your blank elements leaving you wish just the values you need.
I'm doing some tests with learning purpose. I have a PHP script in which I used some functions to see how they work:
First I used isset to make sure a var exist
Then empty to make sure if a var has some value
Finally I used trim to remove whitespaces
After some testing I realized that trim function is not working properly.
For example I can still write whitespaceCHARwhitespace, then I used strlen function and I get a 3 as a result. What's wrong with my script?
Btw I would like to know how acceptable is this form validation I would like to avoid some sqlinjection.
Thanks in advance.
<span><?php echo $msg;?></span>
<form method="POST">
<label for="name" class="white-headers">NAME</label>
<input type="text" name="name" id="name" class="form-control">
<label for="last_name" class="white-headers">LAST NAME</label>
<input type="text" name="last_name" id="last_name" class="form-control">
<input type="submit" class="btn btn-success" name="submit">
</form>
$msg="";
if(isset($_POST["submit"])){
$name = $_POST["name"];
$last_name = $_POST["last_name"];
if(!empty(trim($name)) && !empty(trim($last_name))){
$name_len=strlen($name);
$last_name_len=strlen($name);
$msg="<div class='alert alert-success'>
both fields are set and have some value name =".$name." with ".$name_len." chars and last_name =".$last_name."
with ".$last_name_len. "chars</div>";
}
else{
$msg="<div class='alert alert-danger'>
both fields are set but one or both are empty name =".$name." and last_name =".$last_name."</div>";
}
}
The only times you're using trim there are when you check whether or not there's anything left after you trim the variables:
if(!empty(trim($name)) && !empty(trim($last_name))) {
That doesn't affect $name and $last_name.
trim returns a string with the whitespace removed, but it doesn't change the value of the variable given as an argument. If you want those to be trimmed for later use in your code, you need to set them to their trimmed values, like $name = trim($name), etc.
In your case, you could probably trim them when you set them from $_POST initially.
$name = trim($_POST["name"]);
$last_name = trim($_POST["last_name"]);
Then you can check if there's anything left more simply:
if ($name && $last_name) {
empty isn't necessary because you know they're set, and zero-length strings evaluate to false.
As specified in the documentation, trim only removes whitespaces at the beginning or at the end of a string. Whitespaces in the middle are not affected (using _ to mark a whitespace):
__string will become string
string__ will become string
s_t_r_i_n_g will remain s_t_r_i_n_g
Plus, as pointed in Don't Panic's answer, you are checking the strings after the trim, not its return value.
About the form validation: if you want to clean your inputs before using them in your application, simply trimming them isn't enough. There are many ways to sanitize inputs, every framework offers some options, but since you specifically spoke of sqlinjections, my suggestion is to start by reading PHP's mysqli.real_escape_string
I am trying to take the contents of a form and i want to display them using PHP. The way the form is structured is the following:
There is a list of checkboxes, which when they are clicked, a JavaScript function will create another <input> tag. The JS then sets the name of the new input to <input name="value of checkbox">.
What I need to do is get my PHP to take the value of the <input> I created.
Here is my HTML of the checkboxes.
<input name="product[]" value="value of Check 1" id="id-check-1" type="checkbox" onclick="id-check-1"/><input name="product[]" value="value of Check 2" id="id-check-2" type="checkbox" onclick="id-check-2"/><input name="product[]" value="value of Check 3" id="id-check-3" type="checkbox" onclick="id-check-3"/>
Here is my HTML of the inputs created by the JS.
<input name="value of Check 1" type="text"/><input name="value of Check 2" type="text"/><input name="value of Check 3" type="text"/>
PHP:
$aProduct = $_POST['product];
$product1 = $aProduct[0];
$product2 = $aProduct[1];
$product3 = $aProduct[2];
$input1 = $_POST[$product1];
$input2 = $_POST[$product3];
$input3 = $_POST[$product3];
I tried using this PHP to obtain the value inputted to the crated inputs. This shouldwork, since the name of the inputs = the value of the checkboxes, so in short, this is what I've done:$_POST[$_POST['product']]
Unfortunately, it doesnt work and the variables $input1, $input2 & $input3 dont return any value. So I'd like to know: A) Can i put a _POST within a _POST? and B) What can I do to make my code work?
First of alll the $_POST Variable is one Super Global in PHP i dont think it makes any sense to use $_POST[$_POST...
http://php.net/manual/en/language.variables.superglobals.php
Also i dont think you have to create extra inputs just use $_POST['product'] (array of values which are selected)
try var_dump($_POST['product']) to see whats stored in it
If I understand correctly otherwise guide me in the right direction.
First: You have given the name product[]. Then it should be $_POST['product[]'] which I don't know if that is possible.
Second: If you are writing the value of the checkbox to an input field than why not just check the checkboxes by name. For example:
<input name="check1" value="checkbox 1 value" type="text"/>
<input name="check2" value="checkbox 2 value" type="text"/>
<input name="check3" value="checkbox 3 value" type="text"/>
then in php do:
$check1 = isset($_POST['check1']) ? $_POST['check1'] : "";
This way if the checkbutton is checked you get the value of check1 and otherwise it's empty.
Potentially, you are having issues because you can't have whitespace in the name attribute.
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
https://www.w3.org/TR/html401/types.html#type-name
I have s form and I want to make it safe so I want to validate each input value before I save it in my database. For example I have this input field:
<input type="text" name="username" value="" />
and now for example, someone fills it with something other than numbers and letters like
myusername12|\/+*()!#$%^#^&_-+=.,';"
which might be dangerous values. So I want to check first if the field contains only letters and numbers and echo "letters and numbers only" otherwise. How can I do that?
PHP has a handy built in function to perform this test.
http://php.net/manual/en/function.ctype-alnum.php
Check this function returns true before attempting to save the data but make sure you're running DB prep anyway.
How about:
if (preg_match('/^[a-z0-9]+$/', $username) {
echo "Looks good\n";
} else {
echo "Invalid character\n";
}
And, if you want to be unicode compatible:
if (preg_match('/^\p{Xan}+$/', $username) {
echo "Looks good\n";
} else {
echo "Invalid character\n";
}
Where \p{Xan} stands for any alpha-numeric.
Not a complete answer for your problem, but html5 can do this for you:
<input type="text" name="username" pattern="![^a-zA-Z0-9]" title="Only digits and letters" />
If the users blurs the input, it will highlight red (in FF at least). Be aware though, this is clientside. You can use the exaxt same regex in php to validate.
You can also save the regex and use it in both:
$regex = "[a-zA-Z0-9]";
if(isset($_POST['username'])){
echo preg_match('/'.$regex.'/', $_POST['username']) ? 'match' : 'no match';
}
echo '<input name="username" pattern="'.$regex.'" title="Only digits and letters" />';
Small note: I dont know if browsers do complex regexes (or do them differently).