I'm finding that echo isn't working in my scripts.
The stripped down script below is what I've been using to debug this, but the result has been the same.
Perhaps you can see something simple I've overlooked. Any help appreciated.
Additional details:
Location: http://www.example.com/include/sandbox.php
The web-server can execute php-scripts: phpinfo(); presents PHP Version 5.3.24.
No header lines to worry about.
(I'm wanting to check that a field is not empty before submitting to a database, and provide prompts or an echo on submit.)
<?php
if($_SERVER['REQUEST_METHOD'] == 'post'){
if(!isset($fieldA)){
echo "Error: Submission field empty.";
}
else{
echo "Success! Submitted field wasn't empty.";
}
}
?>
<h1> Example Title </h1>
<form method="post" action="sandbox.php" >
<input type="text" name="fieldA" value="" />
<br />
<input type="submit" name="submit" />
</form>
if($_SERVER['REQUEST_METHOD'] == 'POST'){
..........
}
Try this one. or change the if condition like,
if(!isset($_POST['fieldA'])){
if(empty($_POST['fieldA'])) {
echo "Error: Submission field empty.";
}
}
else{
echo "Success! Submitted field wasn't empty.";
}
Related
I want to implement a post update system like twitter where users can update their status in 160 charecters. I want to add some restrictions like If a user entered characters more then 160 ,then the update_post.php file must show him/her a warning and the extra characters(+160) inside HTML del tag. **Bellow is my code that I have tried so far. but it outputs nothing!**Any help is much appriciated! thanks
sample_update.php
<form action="<?php echo $_SERVER['PHP_SELF'];?>"method="post">
<textarea name="msg"></textarea>
<input type="submit"value="Post">
</form>
<?php
if(strlen($txt)>160) {
echo "Your post couldn't be submitted as it contains more then 160 chrecters!";
$txt=$_POST['msg'];
$checking=substr($txt,160);
echo "<del style='color:red;'>$checking</del>";
}
?>
$txt is set inside of your if statement you need to move it outside
$txt=$_POST['msg'];
if(strlen($txt)>160)
{
echo "Your post couldn't be submitted as it contains more then 160 chrecters!";
$checking=substr($txt,160);
echo "<del style='color:red;'>$checking</del>";
}
You should be getting notices about an undefined variable. This being $txt as from what I/we can see, $txt is defined inside your if loop. I have modified your code to be minimal lines but just as effective.
if (isset($_POST['msg'])){
if (strlen($_POST['msg']) > 160){
echo "Your post could not be submitted as it contains more than 160 characters!";
echo "<del style='color:red;'>".substr($_POST['msg'],160)."</del>";
}
}
I have also wrapped your $_POST around an isset statement, which will check if it's set before doing anything else.. If nothing is set, then the code will not execute and trigger some annoying error messages
This should work for you:
($_SERVER['SELF'] doesn't exists only $_SERVER['PHP_SELF'] Also you have to first assign the variable before you can check the length)
<form action="<?= $_SERVER['PHP_SELF'];?>"method="post">
<textarea name="msg"></textarea>
<input type="submit"value="Post">
</form>
<?php
if(!empty($_POST['msg'])) {
$txt = $_POST['msg'];
if(strlen($txt) > 160) {
echo "Your post couldn't be submitted as it contains more then 160 chrecters!";
$checking = substr($txt,160);
echo "<del style='color:red;'>$checking</del>";
}
}
?>
First of all you have to use $_SERVER['PHP_SELF'] instead of $_SERVER['SELF']
You might want to move some of your conditions up, so you can use the check for something else. Furthermore, inserting the user typed text into the textarea is a good practice so the user dosnt have to retype the text again.
<?php
$maxlen = 160;
$txt=(isset($_POST['msg'])) ? $_POST['msg'] : "";
$check = strlen($txt) > $maxlen;
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<textarea name="msg"><?php echo $txt; ?></textarea>
<input type="submit" value="post">
</form>
<?php
if ($check){
echo "Your post couldn't be submitted as it contains more then $maxlen chrecters!";
$checking = substr($txt,$maxlen);
echo "<del style='color:red;'>$checking</del>";
} else {
echo "You are good to go ma man - do something";
}
?>
I have been trying to get the PHP code to submit an email to a mysqlDB, but for some reason it is not working:
This is the form code in the HTML
<form class="header-signup" action="registration.php" method="post">
<input name="email" class="input-side" type="email" placeholder="Sign up now">
<input type="submit" value="Go" class="btn-side">
<p class="hs-disclaimer">No spam, ever. That's a pinky promise.</p>
</form>
For the PHP, I did the following (DB connection infos set to xxxxx):
<?php //start php tag
//include connect.php page for database connection
$hostname="xxxxxx";
$username="xxxxxx";
$password="xxxxxx";
$dbname="xxxxxx";
mysql_connect($hostname,$username, $password) or die ("<html><script language='JavaScript'>alert('Unable to connect to database! Please try again later.'),history.go(-1)</script></html>");
mysql_select_db($dbname);
//Include('connect.php');
//if submit is not blanked i.e. it is clicked.
If(isset($_POST['submit'])!='')
{
If($_POST['email']=='')
{
Echo "please fill the empty field.";
}
Else
{
$sql="INSERT INTO MailingList (MAIL) VALUES('".$_POST['email']."')";
$res=mysql_query($sql);
If($res)
{
Echo "Record successfully inserted";
}
Else
{
Echo "There is some problem in inserting record";
}
}
}
?>
Do you know what might be the problem?
The php file is in the same folder than the webpage.
Thanks for your time
Regards
$_POST['submit']
does not exist, you have to specify the name for the submit button
<input type="submit" name="submit"........>
Please try this
You could also use this conditional for a POST request
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
And check the input with a var_dump($_POST); to see if the value exists in the array.
This is only if you're expecting one form. If you want multiple forms on the page you could make use of naming your submit button in the HTML code
<form class="header-signup" action="registration.php" method="post">
<input type="submit" name="action1" value="Go" class="btn-side">
</form>
You could also use this if you set an name on the submit button
if(isset($_POST['action1']))
{
var_dump("hit");
}
This may be a simple question for some of you but i've been investigating it for the last hour and couldn't find the answer. I have a simple login form/script that has the following structure;
<?php
PHP code here to check for token (if true) and then check the db for username and password
if the token is false display error message
?>
<HTML>
HTML logon form here that sets the token
</HTML>
Now if there is an issue with the logon, i.e the password is incorrect the php will output the error message, trouble is that it will echo the output at the top of the form. I'd like to be able to insert it at another point of the form. i have a vague idea that i could inject it into the html with something like {logon_error} but i don't know what method thats called or how to use it.
You can store the error message in a php variable , for e.g. $error_msg = "Error! ... ";
And display that wherever you want in the html page like this:
<html>
...
<body>
...
<span><?= $error_msg; ?>
</body>
</html>
Store the error message in a variable, and use it afterwards.
Here's a working example to help you understand:
<?php
if (isset($_POST['FormSubmit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if ($username === 'admin' && $password === 'hunter2') {
# success
} else {
$error = 'Invalid credentials';
}
}
?>
<html>
<div id="errorContainer">
<?php echo (isset($error)) ? $error : ''; ?>
</div>
<form action="" method="post">
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" name="FormSubmit" value="Submit!" />
</form>
</html>
If you have multiple checks, and want different error messages to be output, then you could store the error messages in an array instead. Your validation code should look like:
if (condition) {
$error[] = '...'
}
elseif (condition) {
$error[] = '...'
}
else (condition) {
$error[] = '...'
}
And then, to output it in your HTML, you can use a foreach construct with the alternate syntax:
<div id="errorContainer">
<?php foreach($errors as $error): ?>
<p class="error-content">
<?php echo $error; ?>
</p>
<?php endforeach; ?>
</div>
Note that this is a very basic example and is just for demonstration purposes. You should never trust user input. Your original form should contain all the necessary validation and should not be just a couple of if statements.
You would have to store the message in the session or take a look at https://github.com/plasticbrain/PHP-Flash-Messages
the main idea is $error_mesage = 'your error mesage here';
loadView('your-view')->with($error_message);
It's really simple, if you give more information about what kind of framework you are working with we may be able to assist you further.
You can do like this:
PHP:
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["username"]))
{$userErr = "Username is required";}
}
HTML:
<span class="error">* <?php echo $userErr;?></span>
You can do whatever you like using <?php echo ""; ?> in php to call it on your html.
Good day!
I am a newbie in php..
I made a form using html where I can input the grade of the student.
Then a php page to know if they pass or not.
My problem is how can i send back the reply on the html page. Example how can I send the You Failed status on my html page under the form.
My code is as follows:
<HTML>
<BODY>
Please enter your grade (0-100 only):
<FORM ACTION="grade2.php" METHOD="POST">
<table border = "1">
<tr>
<td>Grade</td>
<td><input type="text" name="grade" /></td>
</tr>
</table>
<INPUT type="submit" name="submit" value="grade">
</BODY>
</HTML>
<?php
$grade = $_POST['grade'];
IF ($grade>=0 && $grade<=50){
print "You failed";
} ELSE IF ($grade<=60){
print "You Passed! But Study Harder!";
} ELSE IF ($grade<=70){
print "Nice";
} ELSE IF ($grade<=80) {
print "Great Job";
} ELSE IF ($grade<=90){
print "Excellent";
} ELSE IF ($grade<=100){
print "God Like!";
} ELSE {
print "Invalid Grade!";
}
?>
Just use one PHP page containing both the form and message. For example (assuming your file is grade.php)
<form action="grade.php" method="post">
<!-- form elements, etc -->
</form>
<?php
if (isset($_POST['grade'])) {
$grade = (double) $_POST['grade'];
// if statements, print message, etc
}
?>
The only issue I see that may prevent it from showing up now is that the print statements are outside the <body> tags.
Move
</BODY>
</HTML>
to the very end of the file
There's two ways that you can use.
You can echo the script filename:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Or just leave the action field blank. The page will then re-load on itself.
<form action="" method="post">
At the top of your script, test for the presence of POST variables on the reload:
if (isset($_POST['submit'])) {
And that's it.
If you mean send as in email, use the mail() function.
If you mean just print the result to the screen, use echo.
<?php
$grade = $_POST['grade'];
IF ($grade>=0 && $grade<=50){
echo "You failed";
} ELSE IF ($grade<=60){
echo "You Passed! But Study Harder!";
} ELSE IF ($grade<=70){
echo "Nice";
} ELSE IF ($grade<=80) {
echo "Great Job";
} ELSE IF ($grade<=90){
echo "Excellent";
} ELSE IF ($grade<=100){
echo "God Like!";
} ELSE {
echo "Invalid Grade!";
}
?>
Also, i'm not sure if this is a standard or not (I usually don't see it that way), but having all caps in your IF / ELSE statements really annoys me for some reason.
I am generating form and handling the submit event in the same file.
If user has not entered the title, I want to display the form again and include an error message (e.g. "You forgot the title.").
That means that I have to duplicate code twice - once to diplay empty form and second to display form with body and ask user to enter title:
<?php if(strlen(strip_tags($_POST['posttitle'])) == 0):
// Display the form with question body that user has entered so far and ask user to enter title.
?>
<label for="title"><b>Title:</label><br/>
<input type="text" name="posttitle" id="posttitle" />
<?php endif;?>
<?php elseif ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action']) && $_POST['action'] == 'post') : ?>
<!-- Everything ok - insert post to DB -->
<?php else :
// just display form here (again ouch!)
<label for="title"><b>Title:</label><br/>
<input type="text" name="posttitle" id="posttitle" />
?>
I would do it like this:
If REQUEST_METHOD is POST I will validate the input and collect messages in an array ($errors in my code).
Then I would just print the form and if there was an error the code will print it.
<?php
$errors = array();
function print_value_for($attr) {
if (isset($_POST[$attr]))
echo $_POST[$attr];
}
function print_error_for($attr) {
global $errors;
if (isset($errors[$attr]))
echo $errors[$attr];
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// do validation here and add messages to $errors
// like $errors['posttitle'] = "The title you entered is bad bad bad";
if (empty($errors)) {
// update database and redirect user
}
}
?>
<!-- display the form and print errors if needed -->
<form>
<?php print_error_for('posttitle'); ?>
<input name="posttitle" type="text" value="<?php print_value_for('posttitle') ?>">
<?php print_error_for('postauthor'); ?>
<input name="postauthor" type="text" value="<?php print_value_for('posttitle') ?>">
<?php print_error_for('postbody'); ?>
<textarea name="postbody">
<?php print_value_for('posttitle') ?>
</textarea>
<input type="submit">
</form>
PS. Consider using MVC to separate code and templates.
Here is a quick way to do that.
<form>
<input type="text" name="title" value="<?php echo $_REQUEST['title']; ?>"/>
<input type="text" name="field_a" value="<?php echo $_REQUEST['field_a']; ?>"/>
....
</form>
But I can also advise you to display a var called $title which is the result of a check on $_REQUEST['title].
You could use an output buffer to grab the form and then assign it to a variable like so:
<?php
ob_start();
include('path/to/your/form');
$form = ob_get_flush();
// then later you can just go
print $form;
?>
Hope this helps
When you display the form, use the possibly empty $_POST values as default field values for both the title and question body. If either is empty, the form will display the second time with the other already filled in:
<?php
$message = "";
if (empty($_POST['title'])) $message .= " Please enter a title.";
if (empty($_POST['body'])) $message .= " Please enter a body.";
?>
<form action='me.php'>
<input name='title' type='text' value='<?php if (!empty($_POST['title'])) echo htmlentities($_POST['title'], ENT_QUOTES); ?>' />
<textarea name='body'><?php if (!empty($_POST['body'])) echo $_POST['body']; ?></textarea>
</form>
Read this MVC
Your can write form in view, handler in controller, and business logic in model