When I test to see if the textarea in my form is empty to do a redirect so it doesn't submit it in php, it doesn't work.
The textarea is named $_POST['message'], I know the variable exists because if I do this statement;
if (isset($_POST['message'])) {
header('Location:/');
exit();
}
Then it always redirects back to the index page so the variable must exist, although if I do this;
if (empty($_POST['message'])) {
header('Location:/');
exit();
}
It does not work, also tried with all three combos of =/==/===
if ($_POST['message'] === '') {
header('Location:/');
exit();
}
And also...
if (empty(trim($_POST['message']))) {
header('Location:/');
exit();
}
Any ideas why this is happening? And how I can prevent it, I really need to stop it as I do not want empty values in my mysql table.
I did some research and it seems some other people have had this problem, but I have seen no answer as of yet.
You probably have some whitespaces in the string, which isn't stripped by trim().
Do a strlen() on it to see what's up, and then log it byte by byte (http://stackoverflow.com/questions/591446/how-do-i-get-the-byte-values-of-a-string-in-php).
One thing you could think about is to make sure your textarea doesn't have any content in the markup (spaces, linkebreaks, whatever), like this:
<textarea></textarea>
I'm pretty sure your last try would work if you'd do it correctly, this:
if (empty(trim($_POST['message']))) {
// ...
}
...is a syntax error. empty is a language construct and does not accept expressions. Try:
$message = isset($_POST['message']) ? trim($_POST['message']) : '';
if (empty($message)) {
// $_POST['message'] is empty
}
This will ignore all input lengths below 3 chars:
if (isset($_POST['message']) && strlen(trim($_POST['message'])) < 3) {
header('Location:/');
exit();
}
However, if you just want to check, if a form was submitted, ask for the submit-button:
<input type="submit" name="submit" value="send" />
the php code would be
if (!array_key_exists('submit', $_POST)) {
header('Location:/');
exit();
}
Related
I have an HTML form with PHP error checks. The form has several different types of fields (one for name, email, phone number, a checkbox, a drop down, etc.) and I have a PHP function written for each that runs when you hit the submit button, and checks that the form is filled in correctly and fully. If a field is left empty, or is filled in incorrectly, an error message appears. However, after I got that running, I tried to add a redirect, so that after the form is completed and submit is pressed, it brings the user to a confirmation page, if the errorchecks are passed. I wrote it like this:
if(isset($_POST['submit']) ){
header("Location:confirmed.php");}
It does what it's supposed to--bring the user to a new page--but it doesn't take into consideration any errorchecks. So, when submit is pressed, rather than run through the error checks, it immediately goes to the new page. I tried adding a variable named "errorcount" so each function so that the number of errors that occur when the form is submit will be either counted, or removed from the count, and then considered when changing the page...
if(isset($_POST['submit']) ){
if ($errorcount == 0){
header("Location:confirmed.php");}}
This didn't work either. I realized that $errorcount wasn't actually being updated at all; for what reason, I'm not sure. I set it up so each function returns $errorcount, and then called each function in the snippet of code above before running the second if statement, but it still does nothing.
I feel like I'm approaching this the wrong way, but I'm not really sure how else to do this. Please tell me if there's an easier way to achieve this, or maybe you have an idea what I'm doing wrong in the first place.
EDIT:
I am passing the variable $errorcount as global in each function, like so:
function validateName ($name, $submit){
global $errorcount;
if( empty( $submit )) {
return '';}
if (empty ($name)){
return "You didn't enter your name!";
$errorcount = $errorcount+1;
}
if (!preg_match("/^[a-zA-Z \-]*$/",$name, $matches)){
return "Please enter a valid name";
$errorcount = $errorcount+1;
}
else{
$errorcount = $errorcount-1;
}
return $errorcount;
}
However, $errorcount still does not actually change with the if loop I posted above. If I take that out (the section of code that causes the page to change) then the functions work as intended; once you click submit, the page refreshes, and error messages appear where the user did not fill out the form properly. But once all the form areas are filled out properly, clicking submit does... nothing.
EDIT 2:
I got it working. It's honestly not very efficient but it does what I need it to do. Thanks to all who helped!
You don't really need to count the errors, and you don't need to use global. Just write your validator functions so they return an error message if there is an error, or nothing if there is no error. Like this, for example:
function validateName($name) {
if (!$name) {
return 'name is required';
}
if (!preg_match("/^[a-zA-Z \-]*$/", $name)) {
return "Please enter a valid name";
}
}
Then when you run your validators, add any error messages you get to an array.
if ($error = validateName($_POST['name'] ?? '')) {
$errors['name'] = $error;
}
After you run all the validators, if the error array is empty, then there were no errors so you can redirect. And if it's not empty, then you have an array of errors keyed by field name, so you can display any errors next to the problematic fields, which your users will prefer rather than getting one error at a time in some generic location.
if (empty($errors)) {
// redirect
} else {
// stay here and show the errors
}
You're needlessly complicating things. Defining functions are only useful if you plan on re-using that code elsewhere. Try this instead:
if ( isset($_POST['submit']) )
{
if ( empty($name) )
{
echo "You didn't enter a name!";
sleep 3;
// redirect or re-load the form
}
elseif ( !preg_match("/^[a-zA-Z \-]*$/", $name, $matches) )
{
echo "Enter a valid name!";
sleep 3;
// redirect or re-load the form
}
header("Location:confirmed.php");
}
is it possible to do this , im trying to validate a form then, it will redirect using header() if TRUE.. but it seems not to be working? or my method is completely wrong ?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST["clientEmail"];
if ($email != $sentEmailClients) {
echo 'Please enter a valid email';
} else {
$newURL = "http://www.myurl.com";
header('Location: ' . $newURL);
}
}
Give us more details about what actually happens when you run your code. You're likely facing one of the following problems:
You're using header() after you've already sent output to the browser. Headers must be sent before any other output. Check out the docs. If you change that line with die('redirecting') and that text shows up, then this is your problem.
Request method is not POST. Add die($_SERVER['REQUEST_METHOD']). If something other than POST is printed, then this is your problem.
$_POST['clientEmail'] is not set, or is not equal to $email
$email is not what you expect (where does it come from?)
$sentEmailClients is not what you expect (where does it come from?)
Basically, "why doesn't it work?" is not a good question because it doesn't give us much info with which to help you. Be more specific about what is happening.
Show enough of your code that we understand the origin of the variables you use.
Hi It seems that Your outermost if condition is not working thats why your header function is not working i just tried this and it woks fine. That means either your first if condition is false or either second if condition becomes true every time just try to echo your values before checking them.
<?php
if (1) {
$email = $_POST["clientEmail"];
if (0) {
echo 'Please enter a valid email';
} else {
$newURL = "http://www.google.com";
header('Location: ' . $newURL);
}
}
check this print_r($_SERVER["REQUEST_METHOD"]); is POST or not and
$email != $sentEmailClients true or false
I would like to accept only small and capital letters from the user.
I tried the below code, it echoes the invalid character message but doesn't work. I mean it doesn't check. It just displays the message. Any help?
<form action="" method="post">
<input type="text" name="fname">
<input type="submit" value="Send" name="submit">
</form>
Update: this is what I have to check and insert the name to database. if numbers found in the name reject the name by displaying the error message else if the name contains only letters insert it into database. That's all I want to acheive.
<?php
if ( isset( $_POST['submit'] ) ) {
$fname = $_POST["fname"];
if(!preg_match ('/^([a-zA-Z]+)$/', $fname)){
echo "Invalid characters";
}
if (empty($fname)) {
echo '<span> First name is required</span>';
}
else{
$mysqli = new mysqli("localhost", "root", "", "test");
$stmt = $mysqli->prepare("INSERT INTO test (firstname) VALUES (?)");
$stmt->bind_param("s", $fname);
$stmt->execute();
$stmt->close();
$mysqli->close();
}
}
?>
If you just want to check you could use ctype_alpha() but you said you want to ACCEPT only letters so if you choose to accept the input you could:
$fname=preg_replace('/[^a-z]/i','',$fname);
better after the check
if(!isset($_POST['fname']) || !ctype_alpha($_POST['fname'])){
// can i haz alpha letters only?
}
(reference)
There are several issues with the code, and the one you are stuck with is probably that you have the form and its processing in the same PHP file. That’s possible, but it requires a different approach. For a starter, it’s probably better to separate them.
What happens with the code posted is that the PHP processor tries to process the form data when no form has been submitted, without even checking for the presence of the data. Now $fname is undefined, so the test always fails.
The test is wrong, too. Now it only checks whether $fname contains at least one letter. For example, if(!preg_match ('/^[a-zA-Z]+$/', $fname)) would test that $fname consists of one or more Ascii letters and nothing else.
use this , this is giving me correct answer
if(!preg_match ('/^([a-zA-Z]+)$/', $fname)){
echo "Invalid characters";
}
else{
echo "correct";
}
The general idea of checking for characters that don't match the [a-zA-Z] pattern is a good one.
However, the "not" part of your if condition is in the wrong place if you want this to work. What you've got now just makes sure that any single character in fname is an upper- or lower-case Latin letter.
You want to push the "not" part of the logic into the pattern:
if (preg_match('/[^a-zA-Z]/', $fname)) {
This checks if any character in fname is not a Latin letter, which is what you're trying to do.
Edit: Your new update has a different test that also works (it appears to be from sourcecode's updated answer, but you've got several tests from the different answers here that will work equally well). But, your updated post makes it clear that your problem isn't really with the pattern for testing the name.
Your code looks like this:
if (/* invalid fname */) {
echo "Invalid characters";
}
if (/* empty fname */) {
echo '<span> First name is required</span>';
}
else {
/* insert into database */
}
That else clause only depends on the the if that comes immediately before it: the check whether fname is empty. In other words, regardless of the result of your check against the characters of fname, you insert it into the database whenever it's not empty.
One easy way to fix this is to just change your second if to an elseif. This will chain all three conditionals together, so the final else block will only occur if both of the earlier conditionals that print error messages weren't triggered.
if (/* empty fname */) {
echo 'First name is required.';
}
elseif (/* invalid fname */) {
echo 'Invalid characters';
}
else {
/* insert into database */
}
I wish some help .
I need a php script using session id to redirect a specific username and password log in
to a specific html form as no one except that user can reach links without logging in by this username and password (i.e no one can copy the link after logging in at another browser and proceed) . Something like admin area or something.
(note : i'll specify name and password by myself not by retrieving it from database ,So no SQL scripts needed)
I searched too much in that and couldn't find something helps .
appreciate ur effort in advance .
On special_form.php and/or other similar pages put something like this:
check_login();
Where check_login() is something like this:
function check_login() {
if ($_SESSION['login'] == true AND !empty($_SESSION['user_id')) {
if ($_SESSION['username'] != 'MyUser' OR $_SESSION['password'] != 'MyPass') {
header('Location: http://www.domain.com/login.php');
}
} else {
header('Location: http://www.domain.com/login.php');
}
}
Now, on login-process.php write something like this:
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
if ($_SESSION['username'] == 'MyUser' AND $_SESSION['password'] == 'MyPass') {
header('Location: http://www.domain.com/special_form.php');
}
// normal login process code
I just hope that I've understood your problem correctly. Give me some hints if I'm wrong somewhere. :)
Put this on top of all pages to check if logged in:
if(!isset($_SESSION['loggedin'] ||
!$_SESSION['loggedin']==1) header('Location: http://website.com/login.php');
Html form on login.php
<?php
//And just check post variables from form:
if(isset($_POST['submit'])) {
if(strcmp($_POST['username'], 'Your username') == 0 &&
(strcmp($_POST['password'], 'Your password') == 0) {
$_SESSION['loggedin'] = 1;
header('Location: http://website.com/youareloggedin.php');
}
}
?>
<form action="" method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
Some tips:
do not write anything to page before calling header function, it will break it.
A blank action on form will send data to itself, make sure php is on top (it is generally easier to keep all php on top and use inline php when needed e.g. <?=functionorvariable()?>
strcmp compares two strings, if they are equal it will give you zero as a return value.
always use isset to check if form was actually submitted on page instead of checking values.
you should add in error checking for checking post values, to see if they are empty or whatever, it is good practice.
learn by doing, please study the structure of this program and see how it is clearly written, it's intentions are clear. Always follow the clarity route when coding.
Good luck
I have script when I will input data from a textbox.
For example: In the textbox, we may input anything string excepting(admin, Admin, ADMIN, AdmiN). I am using this script, but i think my script is so long
Can you show me other ways, regex possibly, to do this?
<?php
$nama=$_POST['name'];
$pesan=$_POST['pesan'];
if(isset($_POST['submit'])){
if($nama== ("admin") || $nama==("Admin") || $nama==("AdmiN") || $nama=("ADMIN"))
{
echo "Masukkan nama yang lain";
}else{
$sql="insert into table1(nama,pesan)values('$nama','$pesan')";
$result_sql=mysql_query($sql);
header('Location:index.php');
}
}
?>
Convert the string to lower case:
if (strtolower($nama) === 'admin')
Try something like:
//make an array of your restricted words, all in lowercase
$restrictedWordsArr = array("admin"); //and more you want
//then check
if(in_array(strtolower($yourWordToCheck), $restrictedWordsArr)) {
//restricted word
}
else {
//valid
}
No need for regex, simply: strtolower($nama) == "admin"