/    Sign up×
Community /Pin to ProfileBookmark

Why Php Not Checking Input On Form ?

Folks,

For the time being, I removed this “required” from the input fields on the html form as I want to check via php if all fields got filled-in or not. Doing this for my learning purpose ofcourse on how php checks for user inputs.
Is this code ok or not ?

““
<?php

?>
<form method=”POST” name=”textfield” id=”textfield” action=””>
<fieldset>
<label for=”email”>Email:</label><br>
<input type=”email” name=”email” id=”email_address” maxlength=”255″ size=”20″>
<br>
<label for=”domain”>Domain:</label><br>
<input type=”text” name=”domain” id=”website_domain” maxlength=”255″ size=”25″>
<br>
<label for=”text”>Url:</label><br>
<input type=”text” name=”url” id=”website_address” maxlength=”255″ size=”50″>
<br>
<label for=”text”>Text:</label><br>
<input type=”text” name=”text” id=”test” value=”” maxlength=”255″ size=”60″>
<br>
<label for=”description”>Description:</label><br>
<textarea name=”description” id=”website_description” cols=”50″ rows=”10″></textarea>
<br>
<label for=”table”><b>Database:</b></label><br>
<select name=”database” id=”db” multiple>
<option value=””></option>
<option value=”searchengine”>Searchengine</option>
<option value=”classifieds”>Classifieds</option>
</select>
<br>
</fieldset>
<fieldset>
<b>Terms & Conditions:</b>
<input type=”radio” name=”tos_agree” id=”yes” value=”Agree to TOS: Yes:”><label for=”yes”>Agree to TOS: Yes:</label>
<input type=”radio” name=”tos_agree” id=”no” value=”Agree to TOS: No:”><label for=”no”>Agree to TOS: No:</label>
<br>
<b>Newsletter:</b>
<label for=”newsletter_subcribe:yes”>Newsletter Subcribe:Yes</label>
<input type=”checkbox” name=”newsletter_subcribe:yes” id=”newsletter_subcribe:yes” value=”Newsletter Subcribe:Yes”>
</fieldset>
<fieldset>
<input type=”reset”><br>
<button type=”reset”>Reset 2!</button>
<br>
<input type=”submit”><br>
<button type=”submit”>Submit 2!</button><br>
</fieldset>
</form>

<?php

if($_SERVER[‘REQUEST_METHOD’]==’POST’)
{
$errors = array();
$labels = array(“email”=>”required”,”domain”=>”required”,”url”=>”required”,”text”=>”required”,”description”=>”required”,”database”=>”required”,”tos”=>”required”);

foreach($labels as $key=>$value)
{
if($value==”required”)
{
if(empty($_POST[“$key”]))
{
$errors[] = “<b>$key</b> ” .’is required!’;
}
else
{
echo ‘<b>Line ‘ .__LINE__ .’: </b>’; echo ‘ ‘ .$_POST[$key]; echo ‘<br>’;
}
}
}

if(!empty($errors))
{
foreach($errors as $error)
{
echo ‘<b>Line ‘ .__LINE__ .’: </b>’; echo ‘Error Alert: ‘ .$error; echo ‘<br>’;
}
}

if(!filter_input(INPUT_POST,’email’,FILTER_VALIDATE_EMAIL))
{
echo ’email wrong’;
}

if(!filter_input(INPUT_POST,’domain’,FILTER_VALIDATE_DOMAIN))
{
echo ‘domain wrong’;
}

if(!filter_input(INPUT_POST,’url’,FILTER_VALIDATE_URL))
{
echo ‘url wrong’;
}
}

//TEST RESULT:
//$_POST[”] outputs the value of value=””.
//For php to extract user input, the radio html needs to have the value=””. Php cannot extract without it.

?>
““

Anyway, can this code can be shortened as much as possible your way or not ? If yes then let’s see your way!

Thanks!

to post a comment
PHP

19 Comments(s)

Copy linkTweet thisAlerts:
@developer_webauthorSep 05.2021 — @NogDog

Does my code look familiar ? I made use of your code on one of my other threads.
Copy linkTweet thisAlerts:
@NogDogSep 05.2021 — Be careful with empty(). Note that for $foo = '0', if you do empty($foo) it will return true, but for $foo = ' ' you would get false. You may find it better to check...
[code=php]
if(trim($field) === '') { // note use of "is identical" === operator
// it's "empty".
}
[/code]

Probably not what I'd actually do, and it's missing a piece to avoid trying values of $_POST that don't exist at all, but this might show you how to think about organizing your code to avoid repetition (i.e. keep it D.R.Y.), and to leverage the use of functions to compartmentalize narrowly focused tasks:
[code=php]
<?php

// test input
$_POST = [
'name' => ' ',
'email' => 'bad.email',
'domain' => 'www.example.com'
];

// example code

// input config:
$inputs = [
'name' => [
'required' => true,
'filter' => null
],
'email' => [
'required' => true,
'filter' => FILTER_VALIDATE_EMAIL
]
,
'domain' => [
'required' => false,
'filter' => FILTER_VALIDATE_DOMAIN
]
];

// validate the inputs...
$messages = [];
foreach($inputs as $key => $attributes) {
if(!is_valid($_POST[$key], $attributes['required'], $attributes['filter'], $msg)) {
$messages[$key] = $msg;
}
}

if(!empty($messages)) {
foreach($messages as $key => $msg) {
echo "<p class='error'>".ucfirst($key)." is $msg</p>n";
}
} else {
// go ahead and process the input...
}

/**
* Validate a form input
*
* @param string $var
* @param boolean $required
* @param int $validation
* @param string $message
* @return boolean
*/
function is_valid($var, $required=false, $validation=null, &$message='') {
if($required) {
if(trim($var) === '') {
$message = 'empty';
return false;
}
}
if(!empty($validation)) {
if(!filter_var($var, $validation)) {
$message = 'not valid';
return false;
}
}
return true;
}
[/code]

Outputs:
[code=html]
<p class='error'>Name is empty</p>
<p class='error'>Email is not valid</p>
[/code]
Copy linkTweet thisAlerts:
@developer_webauthorSep 13.2021 — @NogDog#1636521

Thanks NogDog!

This D.R.Y code would be very handy!

I forgot about the D.R.Y terminology. On my latest threads when I talk about asking you people to shorten my codes, I was meaning about D.R.Y.

So, like you have done here, could you be kind enough to D.R.Y my codes in my other threads too ?

Atleast these 2:

https://www.webdeveloper.com/d/396413-how-to-check-for-sub-array-keys-values

https://www.webdeveloper.com/d/396080-mystery-code-continued

I'd appreciate if you D.R.Y these too ...

I think you already did D.R.Y on this one but if you still can do further then be my guest!

https://www.webdeveloper.com/d/395644-how-to-check-url-params-with-min-code-possible/10

Can this one be D.R.Y too ?

https://www.webdeveloper.com/d/395742-is-this-valid-array/5
Copy linkTweet thisAlerts:
@developer_webauthorSep 13.2021 — I do know difference between these:

"="

"=="

"==="

But I don't understand why the === is needed here:
<i>
</i>if(trim($field) === '') { // note use of "is identical" === operator
// it's "empty".
}


What's wrong with this ...
<i>
</i>if(trim($field) == '') { // note use of "is identical" === operator
// it's "empty".
}


I am sure the '0' would be counted as false here. Right ?
Copy linkTweet thisAlerts:
@ginerjmSep 14.2021 — Can't you read up on these basic things in the official php manual?
Copy linkTweet thisAlerts:
@developer_webauthorSep 17.2021 — @ginerjm#1636976

**I said ....

I do know difference between these:

"="

"=="

"==="

But I don't understand why the === is needed here:
<i>
</i>if(trim($field) === '') { // note use of "is identical" === operator
// it's "empty".
}


Reading the manual would just teach me what I know already. Duh!

Don't understand why identical operator is needed here and don;t understand what would go wrong if I don't use it. I have a feeling you don;t know the answer.
Copy linkTweet thisAlerts:
@NogDogSep 17.2021 — In this specific case it may not be "necessary", but it makes things very explicit and unambiguous, and does not hurt in any way. In some situations the loose typing of PHP might treat certain non-empty strings as being false, so the above makes sure that does not happen, just in case.
<i>
</i>$ php -a
Interactive shell

php &gt; $foo = '0';
php &gt; $bar = (boolean) $foo;
php &gt; var_export($bar);
false
php &gt; $foo = '1';
php &gt; $bar = (boolean) $foo;
php &gt; var_export($bar);
true
Copy linkTweet thisAlerts:
@developer_webauthorSep 21.2021 — @NogDog#1636521

I know the difference between "==" and "===".

But I'm puzzled to why I should use "===" here:
<i>
</i> if(trim($var) === ' ')


What's wrong with this ?
<i>
</i> if(trim($var) == ' ')
Copy linkTweet thisAlerts:
@developer_webauthorSep 21.2021 — @NogDog#1637168

Ok. Then, I better stick to "===" then. ;)

Care to aid me here, mate ?

https://www.webdeveloper.com/d/395304-how-to-validate-inputs-in-html-5-form-with-php-7/6
Copy linkTweet thisAlerts:
@developer_webauthorSep 21.2021 — @NogDog,

Check this test:

1
<i>
</i>&lt;?php

$url = 'http://www.google.com/?search=cars';

if(strpos($url,'?'))
{
echo '1. contains: ' .'?'; echo '&lt;br&gt;';
}

?&gt;


2
<i>
</i>&lt;?php

$url = 'http://www.google.com/?search=cars';

if(strpos($url,'?')==TRUE)
{
echo '2. contains: ' .'?'; echo '&lt;br&gt;';
}

?&gt;


3
<i>
</i>&lt;?php

$url = 'http://www.google.com/?search=cars';

if(strpos($url,'?')===TRUE)
{
echo '3. contains: ' .'?'; echo '&lt;br&gt;';
}

?&gt;


4
<i>
</i>&lt;?php

$url = 'http://www.google.com/?search=cars';

if(strpos($url,'?')!==FALSE)
{
echo '4. contains: ' .'?'; echo '&lt;br&gt;';
}

?&gt;


I get echoed:
  • 1. contains: ?

  • 2. contains: ?

  • 4. contains: ?


  • Why didn't number 3 echo. The one with the "===" ?

    Can you explain that to me, if you do not mind ? I need to learn this from you.
    Copy linkTweet thisAlerts:
    @NogDogSep 21.2021 — strpos() never returns a Boolean true. It returns an integer of the position in the string where the match was found, or else a Boolean false if the string is not found at all. So it will never === true, thus why !== false is the best way to detect that the substring exists (since it will return 0 if it's at the very start of the string, which would be evaluated as false if you did a == comparison).
    Copy linkTweet thisAlerts:
    @developer_webauthorSep 21.2021 — @NogDog#1637346

    I didn't know that some functions do partial boolean. I thought if a function returns boolean then it would either return TRUE or FALSE. But in this case it seems it can return FALSE but not TRUE. Partiality here.

    Ah! Now I understand what you mean! If the needle is in pos 0 then it would return FALSE and we don't want that and so we don;t compare with ==. But how does using === still help here ?

    I know === compares data type and so don;t tell me to read the manual as I just did again.

    Maybe an example code would enable me to understand things better ? ;)
    Copy linkTweet thisAlerts:
    @ginerjmSep 21.2021 — The manual gives all that you are looking to know.
    <i>
    </i>stripos(string $haystack, string $needle, int $offset = 0): int|false


    It is saying that the result can be either an integer (the position!) or false (a boolean), both of which are answers. What more can you want?
    Copy linkTweet thisAlerts:
    @developer_webauthorSep 21.2021 — @ginerjm#1637359

    I know that. What I'm saying is before today, I didn't know some functions return partial boolean. Oh nevermind! NogDog understood what I meant.

    Now, will you have the honours to answer my question which I just asked NogDog above ?
    Copy linkTweet thisAlerts:
    @ginerjmSep 21.2021 — What question did you ask? I see you made a statement with poor puncuation on it, but no question. And if that is your supposed question, my answer is no. Write your own code sample and see what happens.
    Copy linkTweet thisAlerts:
    @developer_webauthorSep 21.2021 — I now found what I really needed:

    https://www.php.net/manual/en/function.str-contains.php
    Copy linkTweet thisAlerts:
    @ginerjmSep 21.2021 — Isn't research a wonderful thing?
    Copy linkTweet thisAlerts:
    @developer_webauthorSep 21.2021 — @ginerjm#1637363

    Sometimes I do not understand technical jargon.

    Need people like you, NAY "YOU", to explain things in layman, NAY "Lay Boy" terminology.

    Ok ? :)
    Copy linkTweet thisAlerts:
    @ginerjmSep 21.2021 — With practice it becomes meaningful knowledge, not jargon.
    ×

    Success!

    Help @developer_web spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 3.28,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,

    tipper: Anonymous,
    tipped: article
    amount: 10 SATS,
    )...