I have a basic form, which i need to put some validation into, I have a span area and I want on pressing of the submit button, for a predefined message to show in that box if a field is empty.
Something like
if ($mytextfield = null) {
//My custom error text to appear in the spcificed #logggingerror field
}
I know i can do this with jquery (document.getElementbyId('#errorlogging').innerHTML = "Text Here"), but how can I do this with PHP?
Bit of a new thing for me with php, any help greatly appreciated :)
Thanks
You could do it it a couple of ways. You can create a $error variable. Make it so that the $error is always created (even if everything checks out OK) but it needs to be empty if there is no error, or else the value must be the error.
Do it like this:
<?php
if(isset($_POST['submit'])){
if(empty($_POST['somevar'])){
$error = "Somevar was empty!";
}
}
?>
<h2>FORM</h2>
<form method="post">
<input type="text" name="somevar" />
<?php
if(isset($error) && !empty($error)){
?>
<span class="error"><?= $error; ?></span>
<?php
}
?>
</form>
If you want change it dynamically in client-side, there is no way but ajax. PHP works at server-side and you have to use post/get requests.
Form fields sent to php in a $_REQUEST, $_GET or $_POST variables...
For validate the field param you may write like this:
if(strlen($_REQUEST['username']) < 6){
echo 'false';
}
else{
echo 'true';
}
You can't do anything client-side with PHP. You need Javascript for that. If you really need PHP (for instance to do a check to the database or something), you can use Javascript to do an Ajax call, and put the return value inside a div on the page.
Related
I am passing values from HTML form to a php file for processing
$to_do = $_POST['action'];
Then i can say
<?php
if( $to_do == "delete") {
echo "i will delete for you";
}
?>
Difficulty i am having is when the HTML value is unicode ✘ for a delete symbol.
instead of the value "delete".
In php i cannot tell how to test it.
<?php
if( $to_do == "✘") {
echo "i will delete for you";
}
?>
is not working.
Any one to help me out?
How are you sending this value to begin with - via something like <input type="submit" value="✘">?
In that case, I would recommend you switch to a button element - that can have a separate submission value and display text. So you can keep sending delete, and show ✘ to the user at the same time.
<button type="submit" value="delete">✘</button>
More details on the button element can be found in the MDN, https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
I need to redirect the user to a site that gets the "Short_proj_name" information. So i did this:
<form action="Main.php?short_proj_name=<?=$_REQUEST['short_proj_name']?>" method="post" name="formProjName" target="_blank" id='frmProjName'>
However, upon searching, i found out that there are several reasons NOT to use $_REQUEST, one of them being security and all that. However, simply doing $_POST['short_proj_name'] or $_GET['short_proj_name'] never returns the information i need.
Basically, how would i go about doing an if statement that checks if the $_GET is empty, and does a $_POST instead? Can i do that in the action method of my form?
EDIT:
Adittionally, is it possible that maybe using both $_POST and $_GET return null, yet using $_REQUEST doesnt? As far as i know, $_REQUEST is both get and post together, but none of them returns any information
It works if i do it as so:
if(!empty($_POST['short_proj_name']))
{
$projName = $_POST['short_proj_name'];
}
elseif (!empty($_GET['short_proj_name']))
{
$projName = $_GET['short_proj_name'];
}
else
{
$projName = $_REQUEST['short_proj_name'];
}
But i'm not sure if that solves the security problem at all
I think the answer here is to always use _GET.
A form can actually send both _GET and _POST data based on what you use in the "action" attribute of the form. The action part doesn't care what you set the "method" attribute as.
From what you are showing above, the params are all in the "action" part of the form so these are always passed into _GET anyway. If the inputs were inside the form then those would be received via _POST
Here's an example.
In PHP I would receive $_GET['monkey'] = '1' and $_POST['lion'] = 1
<form method='post' action='receive.php?monkey=1'>
<input type='text' name='lion' value='1' />
<input type='submit' />
</form>
There shouldn't really ever be an instance where you need to check if the answer is in _GET or _POST and as mentioned in a comment, it's quite a security risk to use $_REQUEST or check if it's in _GET or _POST.
Most times, you can just push the page request URL back into the form "action" to ensure all the same _GET params are included on the form _POST.
The big mistake most people do is try to move them from _GET into hidden input fields inside a form thinking they need to do that to carry all that data through.
However, this type of function call might help you but I wouldn't approve of it.
function getRequestParam($param){
if(isset($_GET[$param])){return $_GET[$param];}
if(isset($_POST[$param])){return $_POST[$param];}
return "";
}
you can like
<?php
if(!empty($_POST))
{
$projName = $_POST['short_proj_name'];
}
else
{
$projName = $_GET['short_proj_name'];
}
?>
<form action="Main.php?short_proj_name=<?=$projName ?>" method="post" name="formProjName" target="_blank" id='frmProjName'>
but i think it's ugly
Here is a simple code :
<?php
if (isset($_GET) && $_GET['short_proj_name'] != '')
echo $_GET['short_proj_name'];
else if (isset($_POST) && $_POST['short_proj_name'] != '')
echo $_GET['short_proj_name'];
else
echo $_REQUEST['short_proj_name'];
?>
But if you get the value from a post or get, it can be anything so be careful...
If the "short_proj_name" is a file name, a nasty person can get access to other files just by guessing their names...
I'm trying to write my first PHP script (hopefully). I want to send user input from a form inside an HTML page to a PHP script and validate them inside script. then, if there is any problem with input data, return to first page and highlight wrong fields. else go to another page (something like successful).
How do i send feedback from second script to first page without using forms?
In short, you'd have something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
$name = $_POST['name'];
if ($name !== 'Fred') {
$errors[] = 'Please enter "Fred"';
}
... validate more fields ...
if (count($errors) == 0) {
... form is ok ...
header('Location: everything_is_ok.php');
exit();
}
}
?>
<form action="<?php echo $_SERVER['SCRIPT_NAME'] ?>" method="POST">
Enter 'Fred': <input type="text" name="name" value="<?php echo htmlspecialchars($name) ?>" /><br />
<input type="submit" />
</form>
Basically: Have the form page submit back to itself. If everything's ok, redirect the user to another page. Otherwise redisplay the form.
Just make your Form POST to itself, then in your PHP check the values and if they are valid, don't display your form and do your submit code. If they are invalid, display the form with the values and errors displaying.
Reload the first page and send the feedback in the session, for example. If session['errors'] exist, echo them. Note you'll have to include some php tags in your html page anyway.
Use a session... here's a link to help you get started: http://www.tizag.com/phpT/phpsessions.php
I am having problems figuring out how to retain users data when the validation fails. I am somewhat new to PHP so I might be making some huge mistakes in my logic.
Currently if the validation fails all the fields are wiped clean and $_Post data is also gone.
Here is some code assuming the user enters an invalid email I want the Name field to be retained. This code is not working.
<?php
if($_POST['doSubmit'] == 'Submit') {
$usr_name = $data['Name'];
$usr_email = $data['Email'];
if (isEmail($usr_email)==FALSE){
$err = "Email is invalid.");
header("Location: index.php?msg=$err");
exit();
}
//do whatever with data
}
if (isset($_GET['msg'])) {
$msg = mysql_real_escape_string($_GET['msg']);
echo "<div class=\"msg\">$msg</div><hr />";
}
if (isset ($_POST['Name'])){
$reusername = $_POST['Name'];}
else{$reusername = "NOTHING";}//to test
?>
<form action="index.php" method="post" >
<input name="UserName" type="text" size="30" value="<?echo $reusername;?>">
<input name="Email" type="text" size="30">
<input name="doSubmit" type="submit" value="submit">
</form>
}
You can use AJAX to submit your form data to your PHP script and have it return JSON data that specifies whether the validation was successful or not. That way, your fields won't be wiped clean.
Another way is to send back the recorded parameters to the posting page, and in the posting page, populate the fields using PHP.
However, I think the first solution is better.
UPDATE
The edit makes your code clearer and so I noticed something. Your input field is called UserName in the HTML, but you are referring to Name in PHP. That's probably why it's not working. Is your field always being filled with the value NOTHING? Make sure the name of the input field and the subscript you are using in $_POST are the same.
Also, there's no need to redirect to another page (using header) if you have an error. Maintain an $errors array or variable to print error messages in the same page. But like I mentioned before, it's probably better to use the JSON approach since then you can separate your view layer (the html) from the PHP (controller layer). So you'd put your HTML in one file, and your PHP in another file.
EDIT:
Vivin had commented that my assumption regarding the header was incorrect and he was right in that. Further more it looks like what the OP is doing is essentially what i layed out below albeit in a less structured fashion. Further Vivin - caught what is likely the actual problem here - the html name and the array key $_POST do not match.
Its wiped clean because you are using header to redirect to another page. Typicaly you would have a single page that validates the data and if ok does something with it and returns a success view of some sort, or that returns an error view directly showing the form again. By using header youre actually redirecting the browser to another page (ie. starting up an entirely new request).
For example:
// myform.php
if(strtolower($_SERVER['REQUEST_METHOD']) == 'get')
{
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
elseif(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
$form = santize($_POST); // clean up the input... htmlentities, date format filters, etc..
if($data = is_valid($form))
{
process_data($data); // this would insert it in the db, or email it, etc..
}
else
{
$errors = get_errors(); // this would get our error messages associated with each form field indexed by the same key as $form
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
}
so this assumes that your form.inc.php always has the output of error messages coded into it - it just doesnt display them. So in this file you might see something like:
<fieldset>
<label for="item_1">
<?php echo isset($error['item_1']) ? $error['item_1'] : null; ?>
Item 1: <input id="item_1" value="<?php echo $form['item_1'] ?>" />
</label>
</fieldset>
Could do something similar to if failed then value=$_POST['value']
But vivin's answer is best. I don't know much about AJAX and wouldn't be able to manage that.
Ok, firstly header("Location: index.php?msg=$err"); is not really required. It's best practice not to redirect like this on error, but display errors on the same page. Also, redirecting like this means you lose all of the post data in the form so you can never print it back into the inputs.
What you need to do is this:
<input name="Email" type="text" size="30" value="<?php print (!$err && $usr_email ? htmlentities($usr_email, ENT_QUOTES) : '') ?>">
Here I'm checking whether any errors exist, then whether the $usr_email variable is set. If both these conditions are matched the post data is printed in the value attribute of the field.
The reason I'm using the function htmlentities() is because otherwise a user can inject malicious code into the page.
You appear to be processing the post on the same page as your form. This is an OK way to do things and it means you're nearly there. All you have to do is redirect if your validation is successful but not if it fails. Like this
<?php
if( isset( $_POST['number'] ) ) {
$number = $_POST['number'];
// validate
if( $number < 10 ) {
// process it and then;
header('Location: success_page.php');
} else {
$err = 'Your number is too big';
}
} else {
$number = '';
$err = '';
}
?>
<form method="POST">
Enter a number less than 10<br/>
<?php echo $err ?><br/>
<input name="number" value="<?php echo $number ?>"><br/>
<input type="submit">
</form>
I'm new to forms and post data ... so I don't know how solve this problem!
I've a php page (page1) with a simple form:
<form method="post" action="/page2.php">
<input type="search" value="E-Mail Address" size="30" name="email" />
<input type="submit" value="Find E-Mail" />
</form>
How you can notice ... this form post the 'email' value to the page2. In the page2 there is a small script that lookup in a database to check if the email address exist.
$email = $_POST['email'];
$resut = mysql_query("SELECT * FROM table WHERE email = $email");
.
.
.
/* do something */
.
.
.
if($result){
//post back yes
}
else{
//post back no
}
I don't know how make the post back in php! And how can I do to the post back data are read from a javascript method that shows an alert reporting the result of the search?
This is only an example of what I'm trying to do, because my page2 make some other actions before the post back.
When I click on the submit button, I'm trying to animate a spinning indicator ... this is the reason that I need to post back to a javascript method! Because the javascript function should stop the animation and pop up the alert with the result of the search!
Very thanks in advance!
I suggest you read up on AJAX.
Here's a PHP example on W3Schools that details an AJAX hit.
Hi i think you can handle it in two ways.
First one is to submit the form, save the data in your session, check the email, redirect
back to your form and display the results and data from session.
Like
session_start();
// store email in session to show it on form after validation
$_SESSION['email'] = $_POST['email'];
// put your result in your session
if ($results) {
$_SESSION['result'] = 'fine';
header(Location: 'yourform.php'); // redirect to your form
}
Now put some php code in your form:
<?php
session_start();
// check if result is fine, if yes do something..
if ($_SESSION['result'] == 'fine) {
echo 'Email is fine..';
} else {
echo 'Wrong Email..';
}
?>
More infos : Sessions & Forms
And in put the email value back in the form field
<input type="search"
value="<?php echo $_SESSION['email']; ?>"
size="30"
name="email" />
Please excuse my english, it is horrible i know ;)
And the other one the ajax thing some answers before mine !
As a sidenote, you definitly should escape your data before using it in an SQL request, to avoid SQL injection
As you are using mysql_* functions, this would be done with one of those :
mysql_escape_string
or mysql_real_escape_string
You would not be able to post in this situation as it is from the server to the client. For more information about POST have a look at this article.
To answer your question you would want to do something like this when you have done your query:
if(mysql_num_rows($result)){ //implies not 0
$data = mysql_fetch_array($result);
print_r($data);
}
else{
//no results found
echo "no results were found";
}
The print_r function is simply printing all the results that the query would have returned, you will probably want to format this using some html. $data is just an array which you can print a single element from like this:
echo $data['email'];
I hope this helps!
<?php
echo " alert('Record Inserted ');"
OR
echo " document.getElementByID('tagname').innerHtml=$result;"
?>
OR
include 'Your Html file name'