Basic PHP $_REQUEST - php

I'm fairly new with PHP, which the following question will prove:
I have three basic isset() they are:
if (isset($_REQUEST['countries'])) {
echo "yes";
}
else echo "no";
if (isset($_REQUEST["depateDate"])) {
echo "yes";
}
else echo "no";
if (isset($_REQUEST['arrivalDate'])) {
echo "yes";
}
else echo "no";
This is the HTML from the form:
<form action="conversionOutputNew.php" method="GET">
Depart Date:
<input type="text" id="depateDate" name="depateDate" />
Arrival Date:
<input type="text" id="arrivalDate" name="arrivalDate" />
<select multiple="multiple" name="countries[]" style="height:180px;">
<option value="United Kingdom">United Kingdom</option>
<option value="Australia">Australia</option>
</form>
What's happening is the chosen countries are being verified with the isset(), but the two dates are not. The only thing I can think of that might have an effect on the dates are that I have jQuery UI's datepicker() associated with it, but removing that still did not help.
I appreciate your help and input.

It's possible something is causing a blank value (perhaps a whitespace) to get POSTed. Since they are text fields, try doing this:
if (isset($_REQUEST['departDate']) && !empty($_REQUEST['departDate'])) {

The thing is that upon submitting the form, the dates are set (so, the isset returns TRUE), but they are empty. So, you can check for emptyness (with empty($variable) php function), to start with.
Nevertheless, I think that some more specific rules have to be set instead of relying only on isset. Especially for dates, you can check for a specific format with a regular expression (e.g. with preg_match and a regular expression like /^\d{4}-d{2}-\d{2}$/ (to match YYYY-mm-dd, the aforementioned regex can be further improved, but it is just an example).

This will test for a non-empty input and validate as well:
// use a suitable format date for preg_match()
if ($arrivalDate = trim($_REQUEST['arrivalDate']) && preg_match('/\d{4}\-\d{2}\-\d{2}/', $arrivalDate))
echo "My arrival date is $arrivalDate";
else
echo "No valid input";

Related

PHP function echoes unexpected HTML value

I have a piece of php code inside html tag which is supposed to change the tag's style in accordance with the contents of the URL.
There is an html login form which looks like this:
<form class="userdata" action="login.php" method="post">
<input type="text" name="email" placeholder="E-mail" <?php fillin('email'); enlight_unfilled('email');?>><br>
<input type="password" name="pwd" placeholder="Password"><br>
<button type="submit" name="login-submit">Login</button>
</form>
Here are the functions fillin and enlight_unfilled:
<?php
function fillin($key) {
if (isset($_GET[$key])) echo "value=".$_GET[$key];
else echo NULL;
}
function enlight_unfilled($key) {
if (isset($_GET['error']))
if (isset($_GET[$key]) and $_GET[$key] !== "") echo NULL;
else echo "style='border-color: red'";
else echo NULL;
}
?>
If I only apply one of the functions within the tag, they both do what they are expected to – either save the email in the field if it has been already typed in or enlighten the email field if it has been left empty. But if I apply them together, when the field is empty, php assigns the field value 'style='border-color:. I also tried to use functions like print and printf, but the result is the same:
I am a beginner at php coding and mixing it with html, so the question may appear to be dumb, but I did not manage to find any sort of a solution to this issue, so thanks for help and patience in advance!
It looks like you don't properly encase value in quotes, so it just renders the 'style='border-color:.
Let's assume that $_GET[$key] has a value of hello#hello.com. What your PHP & HTML renders is the following:
value=hello#hello.com
See the problem? There are no quotes. That's why the renderer goes forward searching for a valid value. To fix the issue you must add quotes around your $_GET[$key] in the fillin function. Something like this should do the job:
if (isset($_GET[$key])) echo "value='".$_GET[$key] . "'";
It works when ran alone because it reaches the end > and just assumes the value to be hello#hello.com

How to set current date as default value of an input?

I am doing an HTML form with an input type date(datepicker) and what I want to do is the following 'if the user sets any date,the default value is going to be that new date, if it does not happen show the first day of the current year'. How can I achieve it? Here is what I have tried.
<input id="desde" name="desde" type="date" value="<?php
if(isset($_REQUEST['desde'])) { echo $_REQUEST['desde']; } else
if(!isset($_REQUEST['desde'])){ echo '01/'.'01/'.date('Y');}?>">
I have tried doing the following code shown above but if I do not put any date it does not show anything, what have I done wrong?
You are providing the date in the wrong format - https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date#Value:
One thing to note is that the displayed date format differs from the actual value — the displayed date format will be chosen based on the set locale of the user's browser, whereas the date value is always formatted yyyy-mm-dd.
(And if(foo) { … } else if(!foo) { … } is unnecessary redundant, you don’t need that second if that checks for the exact opposite of the first one - else alone provides the same functionality here already.)
The HTML date input type element always returns the date in YEAR-MONTH-DAY format, If you want to set any default date then you need to provide the date in that specific format. Try this way,
if(!isset($_REQUEST['desde'])){ echo date('Y').'-01-01';}?>">
Try this
NOTE : Use yyyy-mm-dd format
PHP Code
<?php
if(isset($_REQUEST['desde']) && $_REQUEST['desde']!='') {
$Date=$_REQUEST['desde'];
}else{
$Date=date('Y')."-01-01";
}
?>
HTML :
<input id="desde" name="desde" type="date" value="<?php echo $Date;?>">
Or
<input id="desde" name="desde" type="date"
value="<?php if(isset($_REQUEST['desde']) && $_REQUEST['desde']!='') {
echo $_REQUEST['desde'];
}else{
echo date('Y')."-01-01";
}?>">
first get the year and then you use it in your code. I have updated your code as below. It might help you.
<input id="desde" name="desde" type="date" value="<?php
$year = date("Y");
if(isset($_REQUEST['desde'])) { echo $_REQUEST['desde']; } else
if(!isset($_REQUEST['desde'])){ echo '01/'.'01/'.$year;}?>">

Allow only numbers and letters in an input box or textarea

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).

How $_POST variable/operation is managed in PHP?

When I do something like:
foreach($_POST as $post_key => $post_value){
/* Any code here*/
}
So, something like:
$varSomething = $_POST['anything'];
$varSomethingElse = $_POST['somethingElse'];
Is it possible? When I catch a $_POST[' '], isn't that variable already consumed?
The main reason why I would do this is because after a form submission, I want to check wether some items of some type got certain value or not.
Is there aything else more appropiate?
Firstly the html code don't use variable types, for example, if you have
<input id="check" type="checkbox" />
without a established value, after that you have echo $_POST['chek'], you could think that the result would be a boolean value (false or true), but the correct result will be "on" or "off", you can coding this case. Also, if you want to know the type of your data, you can use regular expression on server side, for example:
<input type="text" id="number" value="1350" />
.....
PHP code
$data = $_POST['number'];
$regularExpression = "/^\d{1,10}$/";
if (preg_match($regularExpression, $data)) {
echo "Is numeric";
}
Good lucky.
if you don't know what is the name of element which is sending the data. the first method is ohk . but if know the name like password or username you can use second one
in html
<input type="password" name ="password" />
in php
$pass_recvd=$_POST['password'];
there is no way to check the type i.e. text/password/checkbox/select etc. you have to do it on client side BEST WAY IS USING Jquery
if you wanna check whether a variable is set or not simple check by using isset method
if( isset($_POST['someVariableName'])) {}else{}

php validation concept

First of all, I don't want to use any framework but I am looking for a good way to use whitelist validation. I am going to apply it on all the user input I receive, I need validation for XSS protection and I also want to apply different formats for example:
Example 1 XSS.
<input type="text" name="test" value="<script>alert('test');</script" />
Example 2 Date.
<input type="text" name="test" value="31-05-2012" />
Example 3 Time.
<input type="text" name="test" value="15:00" />
Example 4 Max length.
<input type="text" name="test" value="short description" />
Example 5 Min length.
<input type="text" name="test" value="min description" />
Example 6 Alphabetic and default symbols only
<input type="text" name="test" value="hello world. This is à ö text input :P :) :S :$ =D !! ??" />
Example 7 Numeric only
<input type="text" name="test" value="1234567890" />
My idea is to build a clientside and server site validation, if the user gets passed through the clientside validation (jQuery) they will get marked as hacker, since it is impossible for default users to pass through the clientside validation.
My question is: What would be the best way to apply client+serverside validation to prevent XSS and apply regular expressions on fields. Are there any lightweight PHP libraries for validation?
I have looked at:
ctype_alpha
preg_match
But I am not quit sure what would be the best one to use, and ctype_alpha is not allowing default symbols etc.
Any advises? Examples? Thanks for your time and reading, and sorry for the hectic question.
It seems you just need some basic validation, not "whitelist" one.
the idea is quite simple.
Create a server-side validation. with ctype_alpha, preg_match and such. (I hope that your question is not about teaching you these functions from scratch).
Create cleint-side validation if you want, by making AJAX calls to the very same validation routines you've used for the (1).
Of course, you have to use both anyway.
Marking users as a hackers seems not the best idea. What you gonna do with marked users?
I've had a similar problem and ended up writing my own "Input-Datatype" classes. This might be a bit excessive if you only use them for validating input though. But you could build validation functions that use a mix of PHP functions such as preg_match, is_numeric, strtotime etc...
An example for date validation would be:
public function validate(&$value) {
$date = strtotime($value);
if($date === false){
//Error no valid date
}else{
if(isset($this->maxDate)){
if($date>strtotime($this->maxDate)){ //maxDate being the maximal date allowed
//Error max date exceeded
}
}
if(isset($this->minDate)){
if($date<strtotime($this->minDate)){ //minDate being the minimal date allowed
//Error date too low
}
}
$value = strftime($this->format,$date); //format being the format in which the date should be saved
}
Another example for validating text could be:
public function validate(&$value) {
if (isset($value) && $value != "") {
if(isset($this->maxLength)&&$this->maxLength!= ""){ //maxLength being the maximal number of characters
if (strlen($value) > $this->maxLength) {
//Error max length exceeded
}
}
} else {
if (!$this->allowNull) { //allowNull being a boolean: true if text can be empty
//Error value is empty
}
}
if(isset($this->regex)&&$this->regex!= ""){ //regex can be any regular expression, e.g: /[A-Za-z]/ for letters only
if(!preg_match($this->regex, $value)){
//Error value does not match expression
}
}
}
As far as XSS goes, make sure you use prepared statements when interacting with a database and use htmlentities when displaying user inputted data.
Hope this helps.
Some time ago, i've written a lightweight-validation class. Maybe you can use it.
For example:
$oValidator = new Validator();
$oValidator->setLanguage('en');
$oValidator->isValid('short description', 'max_length[4]');
echo $oValidator->getLastErrorMessage();
//The input can not exceed 4 characters in length.
$oValidator->isValid('min description', 'min_length[5]');
$oValidator->isValid('hello world. This is à ö text input :P :) :S :$ =D !! ??', 'min_length[5]');
$oValidator->isValid('1234567890', 'digits');
Rule definition:
/**
* #ErrorMessage[lang=de] Die Eingabe muss mindestens %d Zeichen lang sein.
* #ErrorMessage[lang=en] The input must be at least %d characters in length.
*/
public function check_min_length($mValue, $aParams)
{
return (strlen($mValue) >= $aParams[0]);
}
Example:
http://sklueh.de/2013/01/lightweight-php-validator-neue-version/
github:
https://github.com/sklueh/Lightweight-PHP-Validator

Categories