I have a username textbox. It should only accept between 3 and 10 characters and it should only accept (0, 9) and (A , Z ) values or maybe (- and _),
nothing more.
And if the user inputs a value like $%^# it should give an error
I want to do this with PHP, not Jquery. Can anyone help me with this?
I know I can use
<input name="1" type="text" value="1" maxlength="10" />
But it doesn't give an error to the user and just filters the input value.
Thank you.
regular expression could work
if (preg_match("%^[A-Za-z0-9-_]{3,10}$%", $_POST["1"])) {
// OK
} else {
// ERROR
}
When the value is submitted to your PHP script, you can look at it via the $_REQUEST global variable. In this case, you would reference $_REQUEST["1"]. To make sure the value it contains is of a certain size, use the strlen() function. To make sure that the value only contains certain characters, you can use preg_match_all() and an appropriate regular expression like the following:
[A-Za-z0-9]
Related
I'm new to the Swift language and until this point i only worked in web development.
I tried to grasp the idea of optionals, but every time they present some situation where to use it, I still can't understand why they do so (or I might have a little idea, but still not sure.)
I read several articles about this and maybe I just got too confused about it along the way and got lost.
So let's present some examples. Let's say I have a registration form with a textfield for an e-mail. After the form is sent, in PHP I could do something like:
$mail = $_POST['mail'];
if($mail == "") {
echo "ERROR: The E-mail is empty";
} else {
// Do something more
}
If the textfield is empty, the value of $_POST['mail'] is an empty string. I can work with that and check if it is empty or not.
Now, if I understand correctly, in swift the value of that textfield wouldn't be an empty string, but actually a nil, right? Is this that kind of a difference why we need optionals? Because in comparison to PHP, in Swift I have to declare the type of that information each time and it doesn't know if that textfield passes strings or numbers?
Let's talk about another example. Lot of people in swift just declare a string as an optional, even if they put a value in it, like so:
let name:String? = "Gabriel"
If it already has a value, why make it an optional then? For me, it is just a normal constant with a value and I don't see the point of wrapping it into an optional.
If I don't know the name at the declaration, why can't i just type this?
let name:String = ""
and after that, I can use an if statement to check if it is empty or not
if name == "" {
print("ERROR: name is empty")
} else {
//Do something else
}
Did I get the idea with the textfield right or not?
Is there something I'm missing?
Thank You for any help!
EDIT (What got me understanding the concept):
What I got confused about the most was the simple fact, that for example a String can store only "text" and that if nil was something, it wouldn't be of type String, so therefore it couldn't be "stored" inside String of course.
Just in the same way, as I can't store text into an Integer — I can't "store" nil into a String.
But with Optional String I can use this "wrapper" that actually CAN "store" both types: string or nil. And that is what distinguish regular String from Optional String. It is this "wrapper" that has the ability to "hold" both these types until I need to use the actual value. (Now of course I understand, that nil is actually an absence of any value. I just used it in this way to illustrate the point)
Thank You everyone for Your help!
Imagine you ordered a playstation from ebay. The first thing you see is not the playstation, but a box. So, in this instance, the box is an optional. Let's write it down.
var playstation: Playstation?
The box can of course be empty. In order to use the playstation, we need to open the box. We have several ways to do that.
The safe way:
if let ps = playstation {
// if the box is not empty, and the PS is there
ps.play()
} else {
print("The box was empty :(")
}
The other way:
playstation?.play()
In this other scenario, we're only calling the play() method if the contents of playstation box are not empty. Downside is that you cannot display an error in case it fails.
What if you promised your friend that you'll play together on your playstation that will be here today. You're giving a guarantee that the playstation will be in the box. That's when you use this:
playstation!.play()
Problem with this approach, in actual programs, is that your app will crash if the contents of the optional are empty. Use "!" only if you can guarantee that it will not be empty (i.e. you assigned a value to the variable right before this)
So, to conclude, optionals are variables whose value can be either a specific type (i.e. String) or nil. You cannot assign nil to strongly typed variables.
var a: String?
var b: String
a = nil // this is ok
b = nil // this will not compile
Think of optionals like this :
An optional is a variable which can be empty something in the future or even now.
Making a variable an optional means it is wrapped as an enum.
Suppose there is a variable : var x : Int?, this means a variable named x of type Int, is not yet initialised and an optional.
This typically can be represented in layman terms as
Enum x(optional) // name of the variable{
case T: // some value
case nil: // no value
}
So when we assign a variable we can just assign it normally, but the value is stored in the case T of the optional enum variable of x.
x = 10 //
enum x(optional){
case T = 10
case nil
}
When we want to use it(get the value) we use a (?) or an (!)
These can be farther explained as
print(x?) // If there is any value inside of x, give it to me(in this case give me the value of x's case of T)
print(x!) // I dont care if there is any value inside of x or not, just give it to me anyway.
Hence if x has no value then printing (x!) will produce a crash, as x does not have a value inside of it.
? - safely unwrapping the optional
! - force unwrapping the optional
P.S - I know there are certain things I missed but this is the jist of Optional is this is meant only for explanatory purpose. Once you grasp this concept you can farther check out more documents on Apple's documentation here
Effectively,
let name:String? = "Gabriel"
is not very useful.
But
var name:String? = "Gabriel"
does make sense, as you can further on set to nil.
Optionals are very useful for returning value from function.
Consider a func that returns an Int.
If the value is not found, you could return a number (like very large negative) to notify value was not found. But there is a risk some day that the func does return this value (even unlikely).
Returning a nil let the function make it clear it did not find the value.
My understanding of optionals is that they are a type just like String, or an Int, or a Double. Optionals have associated values so an String? is an optional with a String associated to it. The optional can either contain a value which is a string, even an empty string or nothing at all, which to me is null. Check out the Stanford U IOS course on iTunes. Optionals are explained much better then I am able to.
This question already has answers here:
Weak typing in PHP: why use isset at all?
(9 answers)
Closed 7 years ago.
I'm beginner in PHP and was wondering what's the difference between this
$variable = "text";
if($variable){
echo $variable;
}
and this
$variable = "text";
if(isset($variable)){
echo $variable;
}
Sometimes you want to know if a variable is set or not e.g. for security reasons of for debugging reasons.
The function isset() is used to determine if a variable is set and is not NULL and is accordingly returning true or false.
The expression if($variable) {} instead will evaluate to false if $variable is set but is zero or if $variable is set but its current value is false (=counterexample)
Assume:
isset($variable): Evaluates to true if a variable is set and not null
if($variable): Evaluates to true depending on the value of a variable or the result/value of an expression
The most important feature of functions like isset(), empty(), etc. to me is, that they do not throw errors when a variable is not set, like Marc B already mentioned.
PS: I strongly recommend to turn on strict mode and all error reporting during development.
isset is used to check whether input you receive contains what you expect - this is a very, very loose definition and I wrote that trying to explain easily when you'd use it.
When you set a variable yourself, then it doesn't make sense to use isset, you know it's set and that it contains some value.
However, many languages, not just PHP, deal with user input. User in this case could be a human, another computer service etc. You usually store that input inside a variable. A great example is PHP's $_POST, $_GET, $_SERVER, $_SESSION.
When you receive an input that user made via HTML form, you want to check whether certain values have been populated - in that case, you use isset.
An example HTML form:
<form method="POST" action="your_file.php">
<input type="text" name="first_name" />
<input type="text" name="last_name" />
<button type="submit">Send</button>
</form>
Someone can submit that form, they can fill in both inputs. Or only one of them, or even none. You don't know what they've done, but regardless - PHP will provide you with a variable that might contain correct input.
If I submitted that form with nothing filled in, and if you tried to access a value for first_name - you would get a PHP warning - and you don't want PHP warnings.
Therefore, before working with user input (in this case with a $_POST superglobal array), you would check whether I filled in everything properly and you'd do that with:
if(isset($_POST['first_name']) && isset($_POST['last_name']))
{
echo "Form was filled in correctly";
}
else
{
echo "Form wasn't filled in correctly! Please fill in both fields";
}
Hopefully that clears it up a bit. Just once more, I used very trivial but real-world examples.
Perhaps you example is a bit skewed. However. if you were to ignore the first line of each code segment, perhaps you will see this differently. Consider the code segments
if($variable){
echo $variable;
}
If $variable has not been initialised and assigned a value, then the is statement will result in an error.
On the other hand, if you initialise the variable
$variable = "text";
if($variable){
echo $variable;
}
will test is the variable is true, or non zero.
The isset() function will ignore the value, and tell you if the variable is initialised.
In the following code segment, the if() statement will return true.
$variable = "text";
if(isset($variable)){
echo $variable;
}
while, in this code
<?php
if(isset($variable)){
echo $variable;
}
the if() statement will return false.
Please excuse my ignorance. I want to always retain the current value (that I have supplied by changing the default value) in the input box when I click outside the text box. But the following code returns to the default value if after modification I again click the text box and then click outside the text box. But I want to retain the most updated value always in the textbox.
Perhaps I have to make changes in the area this.value=' <?php echo "$r1[MAJORS1]" ?>';, but not understanding how to do that.
Any help please
onfocus="if(this.value!=''){ this.value=''; this.style.color='#000';}"
onblur="if(this.value==''){ this.value='<?php echo "$r1[MAJORS1]"?>'; this.style.color='#000';}"
I believe you're looking for:
<input type="text"
data-value="<?php echo htmlentities("$r1[MAJORS1]"); ?>"
placeholder="<?php echo htmlentities("$r1[MAJORS1]"); ?>"
onfocus="if(this.value!=''){
this.value='';
this.style.color='#000';
this.setAttribute('placeholder',this.getAttribute('data-value'));
}"
onblur="if(this.value==''){
this.value=this.getAttribute('data-value');
this.style.color='#000';
}else{
this.setAttribute('data-value',this.value);
}"
value="<?php echo htmlentities("$r1[MAJORS1]"); ?>">
Not exactly pretty though. Messing with the default functionality of the user's browser has a tendency to confuse. I believe my placeholder usage, though, will make it less confusing for the user that their input will revert to whatever the placeholder reads.
See my jsfiddle here: http://jsfiddle.net/3Lvs77bv/
I don't, however, know if MAJORS1 is supposed to be a constant or a key in your $r1 array, though. If it's a key, make sure to quote it to prevent warnings otherwise PHP will think it's a constant. But PHP will fallback, in any case, if the constant isn't defined and treat it as a key in the array, although will generate warnings.
Edit:
If you'd like to allow for blank values, you could either add a button to clear the field like so:
http://jsfiddle.net/3Lvs77bv/1/
Or, as I'd suggest, simply get rid of all the clutter you're trying to code, which affect the user's default browser functionally, and simply use this.select() instead when the field is focused:
http://jsfiddle.net/3Lvs77bv/2/
Hey guys I am learning PHP now and actually w3schools does not have listed what is the purpose if these things. Sorry I am not familiar with the names and conecepts as well, so was hoping someone can kind go over it with me. I searched youtube videos, but they usually do not call it by the correct name. They just say "place "post in here because it needs to call what you have in HTML" but what is $_POST? a variable? ect
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<!-- The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the currently executing script.'
So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself,
instead of jumping to a different page. This way, the user will get error messages on the same page as the form.-->
Name: <input type="text" name="name"> <br>
E-mail: <input type="text" name="email"> <br>
Website: <input type="text" name="website"> <br>
<input type="submit" value="send!">
</form>
<?php
// $name = $email = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo ($_POST["name"]);
echo ($_POST["email"]);
echo ($_POST['website']);
}
// function test_input($data) {
// $data = trim($data);
// $data = stripslashes($data);
// $data = htmlspecialchars($data);
// }
?>
wondering in the bottom what is trim, stripslashes, and why is it calling or whatever its doing "htmlspecialchars" again if its located in the action""> line?
$_POST is a reserved "superglobal" variable, meaning it is:
Created automatically by the server and
Available everywhere.
It automatically contains all data sent to the server with an HTTP POST request. Technically, it is (from the manual):
An associative array of variables passed to the current script via the HTTP POST method.
So if you have a form with name and email input fields, $_POST is an array with keys named name and email, which contain the data submitted by the user. You could access these with $_POST['name'] and $_POST['email'], respectively.
There are several other superglobal variables, namely:
$GLOBALS
$_SERVER
$_GET
$_POST
$_FILES
$_COOKIE
$_SESSION
$_REQUEST
$_ENV
You can learn much more about this by reading the manual entry on $_POST or the manual entry on superglobal variables.
To answer your other questions:
trim() removes white space (like spaces, tabs, and new lines) from the beginning and end of a string. For example, trim(' foo ') produces just foo without the spaces. You can also make it remove other characters. Say you have xxxfooxxx. trim('xxxfooxxx', 'x') will take away the xs and leave you just foo.
stripslashes() removes slashes from a string that has escaped characters. For example (from the manual):
$str = "Is your name O\'reilly?";
// Outputs: Is your name O'reilly?
echo stripslashes($str);
htmlspecialchars() turns special characters into HTML "entities." Specifically, it changes the following:
& (ampersand) becomes &
" (double quote) becomes " when ENT_NOQUOTES is not set.
' (single quote) becomes ' (or ') only when ENT_QUOTES is set.
< (less than) becomes <
> (greater than) becomes >
$_POST is part of the "superglobal" family.
I quote from the manual:
Superglobals are built-in variables that are always available in all
scopes.
Several predefined variables in PHP are "superglobals", which means
they are available in all scopes throughout a script. There is no need
to do global $variable; to access them within functions or methods.
These superglobal variables are:
$GLOBALS
$_SERVER
$_GET
$_POST
$_FILES
$_COOKIE
$_SESSION
$_REQUEST
$_ENV
Then in your PHP handler, the form's element would be accessed in this fashion:
A basic example:
<?php
$name = $_POST['name']; // taken from <input type="text" name="name">
echo $name; // would echo the entered name from the form.
Something important to remember:
When using superglobals, they must be in uppercase letters.
$_post and $_Post for example are considered invalid. Use $_POST < exactly like this etc.
Some have/do that mistake, and will not work if not using the proper syntax (uppercase).
Also, the underscore _ between the $ and the superglobal name POST for example, is also required. $POST < being invalid. Again, use $_POST - $_GET - $_REQUEST etc.
About certain functions and predefined variables
trim()
Strips whitespace (or other characters) from the beginning and end of a string
stripslashes()
Un-quotes a quoted string
htmlspecialchars()
Converts special characters to HTML entities
$_SERVER["PHP_SELF"]
Executes from the same location of the originating script. Using action="" does the same job.
$_SERVER["REQUEST_METHOD"]
Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'
Eventual/potential database work
Should you later want to adventure yourself in databases, you could use these variables as shown below, using mysqli_* as an example:
<?php
// DB connection credentials
$name = mysqli_real_escape_string($con,$_POST['name']);
// rest of DB query
//
$con being something to the effect of:
$con = new mysqli("host","username", "password", "database");
$_POST[] is one of PHPs Superglobals.
From the PHP Manual:
Superglobals are built-in variables that are always available in all scopes
These are:
$_SERVER - Contains information about the Server & Execution Enviroment
$_GET - Contains HTTP GET variables
$_POST - Contains HTTP POST variables
$_FILES - Contains HTTP File Upload variables
$_COOKIE - Contains HTTP Cookies
$_SESSION - Contains Session variables
$_REQUEST - Contains HTTP Request variables
$_ENV - Contains Environment variables
They contain information about the enviroment that PHP is running in as well as information passed to the script etc.
As others have said $_POST is a super global variable.
With regards to your other questions, you are better off going onto php.net and searching for the function name specifically.
trim()
stripslashes()
htmlspecialchars()
So, $_POST has been covered enough by the other answers.
trim, stripslashes and htmlspecialchars are used to format strings and those 3 are rather basic, you'll probably use them often.
trim cuts off leading and trailing whitespaces, so that your resulting string starts and ends with an actual visible character. This is usually used to clean up user-submitted data and remove parts that don't really hold any information. It can also be used for some tricky formatting in combination with concatenation (.) though.
stripslashes reverses the addslashes function. The latter is important to sanitize user-entered data and take a big step towards avoiding injection-type attacks, where a user enters executable code in a way that makes your server actually execute it. Usually though, you don't want to output data in this "safe" form because it looks strange, so you'll call stripslashes just before creating your output in order to revert the string to its original form.
htmlspecialchars is necessary for creating html output that contains some characters used or reserved by html, such as < and &. Since PHP usually creates html code, those characters are transmitted in a way that makes html understand them as if you wrote a source file with them. But sometimes, you want to just display the character ("Romeo & Juliet"). In those cases, you need htmlspecialchars to transform your string into a 'clean' string that will show on the user's screen exactly the way it shows in your script (minus the quotation marks).
Here's my newbie explanation:
$_POST is an array of all the POST data sent by the client to the server
To see it, use this:
var_dump($_POST);
You can also see the GET data with
var_dump($_GET);
And finally everything (including cookies):
var_dump($_REQUEST);
Want to use both GET and POST methods
Say you have a form:
<form method="POST">
<label>Username: <input type="text" name="username" ></label><br>
<label>Password: <input type="password" name="password" ></label><br>
<input type="submit">
</form>
There's two important things going on here:
each input (of the text-input type, not the submit button at the bottom) has a name
the form has an attribute 'method' that says "POST"
If you submit this form, the browser will send the data as an associative array to the webserver using the POST-method. This array will then be passed to this PHP variable: $_POST (which is one of the super global variables, look that up if you want to know more).
In PHP you can then use what was entered as follows:
echo "The username you entered is: ".$_POST["username"];
You can do the same with $_POST["password"], obviously.
Now there's also the GET-method. The form would look like this:
<form method="GET">
<label>Username: <input type="text" name="username" ></label><br>
<label>Password: <input type="password" name="password" ></label><br>
<input type="submit">
</form>
The only thing that changed was the 'method' attribute of the form. Now, when you submit this, there will be two differences with using the POST-method:
The data you send will be visible in the url in the following form: website.com*?username=jack&password=ilikepotatoes* (the ? indicates the start of the data)
The data will be given to PHP in same form, but under a different name: $_GET in stead of $_POST
So in PHP, you can access this data this way:
echo "The username you entered is: ".$_GET["username"];
Which one you use, is up to you, but for things like logon-forms it's better to use the POST-method as this doesn't show the data in the url like the GET-method does.
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 10 months ago.
I have a web form that takes 2 string values and 2 integer values from a user and stores them in a database.
How can I ensure that the ints are actually ints and sanitze input so that Bobby Tables doesn't pay me a visit?
Here is my forms code:
if(isset($_POST['submit']))
{
$formTitle = $_POST['title'];
$formAuthor = $_POST['author'];
$formPagecount = $_POST["pagecount"];
$formCurrentpage = $_POST["currentpage"];
}
<form method="post" action="index.php">
Title: <input type="text" size="25" maxlength="250" name="title" />
<br/>
Author: <input type="text" size="25" maxlength="250" name="author" />
<br/>
Page Count: <input type="text" size="25" maxlength="25" name="pagecount" />
<br/>
Current Page: <input type="text" size="25" maxlength="25" name="currentpage" />
<br />
<input type="submit" value="Add new book" name="submit" />
</form>
There are several things you may want to check / do :
Verify the form has been submitted : isset on the $_POST component will help
Chechking your data are "valid" :
did the user enter data in each field ?
do the required field contain data ?
don't forget to trim before checking, so a field containing " " doesn't count as a field with data in it
Chechking your data is actually the way you want :
do the title and author contain strings ? Longer than X characters ? Short that Y characters ? Any "fordibben" character or value ?
do the two other fields contain numeric data ? Positive ? Only numbers (nothing like 3E5 or the like) Not bigger than what you consider as OK ?
There are frameworks that can help you with all that.
For instance :
PEAR::Validate
Zend_Validate
(The more you re-use existing great code, the better for your application, I'd say : less risk to introduce bugs with your new, un-tested, code ;-) )
Once you made sure your data is OK, you can insert it into the database.
Which means you must escape it properly.
Depending on the functions / classes you're using, you'll take a look at
mysqli_real_escape_string for strings
intval for integers (forcing them into integers, to be sure)
if use PDO : PDO::quote
Or you may use prepared statements, that will do most of the escaping work for you ;-)
I'd go with those, I think, btw :
see mysqli_prepare,
and PDO::prepare
Finally, if the data was not successfully validated, you may want to re-echo the form, with the fields already containing what the user typed in the first time.
There, you need to escape data to HTML format, to avoid XSS. Take a look at htmlspecialchars
Same thing, btw, if you want to display those data on another screen somewhere else in your application...
The only safe ways to check if user input data only consists of digits are (1) to use regular expressions or (2) use the ctype-extension (preferable).
if (ctype_digit($_POST['pagecount'])) {
// ...
}
If you insert integer values into your database you don't have to escape them but make sure they really are integers (cast them); for strings you should use mysql_real_escape_string but it is never wrong (but usually better) to use prepared statements.
By the way: It's not safe to check for the submit-button because IE <= 6 only sends it if it's clicked to submit the form (not if the form is submitted via the enter key).
PDO and its prepared statements will save you headaches, even if they look more complex at first. For integers you can use intval($input), but keep in mind that PHP will -- in its infinite wisdom -- turn non-numeric input into 0.