Do not want Html after php is executed - php

I have the following code:
<?php
...
?>
<script>
....
</script>
<html>
...
</html>
After displaying HTML form, JavaScript should validate and then PHP should save in database and give a confirmation message.. but what happens is, after PHP is executed and success message is echoed, the HTML form also displays as it is below message..
What can I do to avoid this?

I prefer to set a variable if a form submission was successful. Something like the following:
<?php
$success = false;
if (isset($_POST['submit'])) {
// process form submission
// if submission validates; set $success to true
}
?>
<!DOCTYPE html>
<html>
<head>
…
</head>
<body>
<?php if ($success): ?>
<p>Thank you for your submission!</p>
<?php else: ?>
<form action="" method="post">
…
</form>
<?php endif; ?>
</body>
</html>

if(isset($_POST['name'])){
//your insert query
//your thanks message
}
else{
// Your html form
}

Simply use a flag variable :-
if(isset($some_var))
{
// do something
}
else{
// show html form
}

You could end the script after progressing the data with exit(); (See docs)
Like #Shomz said, you could wrap your HTML output in a if-statement to prevent it from being printed after processing your form data.

You can use the 'action' of your form to send the post to another file where there is the confirmation message.
Or you cant put a condition if(!$_POST) before your html

put PHP in a different file (you can include HTML files)
return;
die();
exit();
Use ob_start() and functions alike to buffer HTML and _clean to flush it to nirvana when you don't need it.
Submit to a different file (nearly the same as first point).
Use prepend in php.ini to start ob before script, and append in php.ini to kill output under certain circumstances (maybe using isset() on a variable to check if there has been a submit or just $_POST / $_GET ).
You might also want to look at PRG pattern which someone else has already asked about for php here: Simple Post-Redirect-Get code example

Related

For a Single-Page-Website with a form at the end: Do I have to convert the index.html into index.php?

I am working on my first Website! Its a Single Page Design with a simple contact form (two input fields, a textarea and a checkbox and submit button) at the end of the page! The page is ready... the only thing that´s missing is the PHP for the contact form. When the contact form is submitted I would like to show a message (message delivered) on the same page!
My Question: For this purpose do I need to convert the whole index.html to index.php ??
It seems to be the only way for the action attribute of the form to stay on the same page! Or is it better to add also Ajax for this purpose? All tutorials use the index.php...
Please help!
I would say yes, make it a .php file. A PHP file can have plain HTML in it. Your index.php could look something like this:
<?php
if ( isset( $_POST['submitted'] ) ) {
$message = 'Your email has been sent!';
// Process your form and send email here
}
?>
<html>
<head>
...
</head>
<body>
<?php
if ( $message ) {
echo "<div class='message'>$message</div>";
}
?>
<!--The rest of your body...-->
</body>
</html>
when you write one line in PHP language in your page you must convert to page.html to page.php
to show a message try to use this
echo "<script> alert('message delivered '); window.location.href='index.php';</script>" ;

PHP Redirect after form submit

I have a question how can I redirect in PHP after a form insert.
Example: I have the file insertMedia.php
The HTML:
<form method="POST" action="insertMedia.php">
</form>
and after the html the php script:
<?php
code_for_mysql_insert(); // dummy placeholder function for the MySQL insert
header('Location: otherSite.php');
?>
But this doesn't work. What do I have to change?
Thanks for your help
Lingo
You can try using JavaScript
<?php echo '<script>window.location = "http://www.google.com/" </script>';?>
If your form action link is like such
<form action="localhost/index.php?redirect=index2" method="post">
You can use this solution:
<?php $link = "http://localhost/".$_GET['redirect'].".php";
echo '<script>window.location ="'.$link.'"</script>';?>
There is no problem with the script. As long as your MySQL insert placeholder doesn't echo anything out.
Soon as headers are sent , the PHP header function stops working.
<?php
count([]);
header('Location: local.com.php');
Above is a script I tested. Count function doesn't echo anything out. I used it in place of the MySQL insert.
Javascript Solution is
<script type="text/javascript">
window.location.href = "otherSite.php";
</script>
But yout form isn't submited this way. You can add a GET to the URL.
Or you can use Javascript to send your form by calling the submit function of your form.
just use header('Location: otherSite.php'); remove insert

How do i go about echoing back to a form from a form post action?

I have a form containing a textarea for inputing text into. The form also contains a submit button. After pressing the submit button it posts the text within the textarea into my php document. Within my php document the text is added to a database. Once it has been added to the database I would like it to echo back a response telling the user that it has added the text to the database successfully.
However, if i make it echo that response back to the home page, there is nowhere declared for it to display the echoed message. Has anyone got an idea of what i should be doing in order to get this working? Many Thanks.
Normally i wouldn't use a post straight from the form and i would use ajax and then display the data within a paragraph or something on it's return, however since the form is doing the post it's self i am not sure where to then declare where the response should show up.
The bellow displays my html form code and shows it's action to post to a php file.
<div id="userban2"><form id="bannable" action="/onlineusers.php" method="post"><p> Type username to ban bellow:</p>
<textarea name="banned" id="banned" maxlength="255"></textarea><br/>
<input type="submit" value="Send" class="extrabuttons" onclick="return false; preventDefault();">
<div id="cancelban" class="extrabuttons"><p> cancel</p></div>
</form>
However when in my php file i write ....
echo "the information has been added to the database successfully";
It might send the echo back however it isn't declared to display anywhere how can i change this to make it display the response within my form?
As requested return from my php
if(isset($_POST["banned"])){
$ban_name = $_POST["banned"];
bannedd($ban_name);
}
function bannedd($ban_name) {
$query1 = mysql_query("INSERT INTO banned_users (username,firstname,lastname,email,password,ip_address,sign_up_date,last_logged_in,about,sta rr,userpref) VALUES('$usernameb','$fnameb','$lnameb','$emailb','$passwordb','$ip_addressb','$sign_up_date b','$last_logged_inb','$aboutb','$starrb','$userprefb')") or die("Could not insert your informaion");
echo "This user has successfully been banned";
}
The form posts what is written in the form due to it having the action and method of post to my php. However should i then have any return i am not sure how i declare where the returned information should then show (The echoed message).
If I understand you correctly, your form is in some index.php file and sends the data to other file - onlineusers.php, and you want to display the message in the original page?
If this is the case, the most simple way I can think of is redirect back to the original page with a URL parameter, instead of echoing.
Do this at the end of onlineusers.php:
<?php
// insert text into DB ...
header("Location: index.php?result=ok");
?>
This redirects the browser back to the original page with the form. There you check if the status variable is set:
<html>
<head></head>
<body>
<?php if(isset($_GET["result"]) && $_GET["result"]=="ok") { ?>
<p>The information has been added to the database successfully</p>
<?php } ?>
<form> ... </form>
</body>
</html>
As you can probably see, you could set other results, such as "error" this way.
If you don't like the extra string in your URL, then create a cookie after processing the form in onlineusers.php and back at the original page, check if such cookie has been set. If you need more detail on that, let me know. And if you're asking something completely different, well, never mind :)
Your form is being submitted to /onlineusers.php
This is where you would want to add your echo statement.
If you require the info on the same page you technically return to the same page with the form action being $_SERVER['PHP_SELF'].
<form id="bannable" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Then you can put in a conditional statement prior to the load of your document, and include the PHP script.
<?php
$testVar = false;
$msg = '';
if($_POST) {
include '/onlineusers.php';
//... do something e.g post to database and return true.
}
if($testVar) {
$msg = 'Successful writing to DB!';
} ?>
<html>
<body>
<?php echo $msg; ?>
</body>
</html>
This will check to see if you have any post data, if you do, then it includes the script you specify. Maybe set $testVar to true if the writing to DB is successful, and then return $msg in your HTML.

How to combine this PHP code with HTML and Javascript?

for example, this is my PHP code:
<?php
if($country_code == 'US')
{
header('Location: http://www.test.com');
}
else
{
header('Location: http://www.test.com/');
}
?>
I'm trying to use a Javascript code for tracking, it has to be above the </body> tag.
I have tried different ways of combining the PHP code with HTML, I have tried placing the HTML separately below the PHP also, one example:
<html>
<head></head>
<body>
<?php
?>
<script></script>
</body>
</html>
The furthest I got was, it tracked the click but it didn't redirect giving me this error:
`Warning: Cannot modify header information - headers already sent by`
Will appreciate any suggestions and help, thank you!
Put the php redirect code at the begining of your document before anything is outputted. Check for spaces after the ?> tag and before the <?php tag because these will be printed out and the response header will be sent therefor you will not be able to modify the header to redirect.
You have to try something like the following to track:
<?php
if($country_code == 'US')
{
header('Location: http://www.test.com/?us=yes');
}
else
{
header('Location: http://www.test.com/?us=no');
}
?>
And then in your index page check for the value of the us parameter. Also you should Notice that there is no any output should be printed before the header function to void the warning :
Warning: Cannot modify header information - headers already sent by
The trouble is that PHP run before JavaScript. So you need to geet the PHP variable inside a JavaScript.
<?php
// your normal code here, like connection to DB
?>
<script>var test = <?php> echo $thatVariable; <?> </script>
You may not send an output to the client before a header() tag of php.
So you can generate a redirect page which gets the country information via js and send it to the php (using e.g form submit). after that you can redirect to the accoording page via php header()
<?php
if($country_code === 'US'){
echo "<script> window.location.href='http://www.test.com1'</script>";
}
else{
echo "<script> window.location.href='http://www.test.com2/'</script>";
}
?>

header(location) on form does not work after submit button clicked

This is my code for my submit button. Once data submitted to mysql i want it to redirect to page.html.
<form name="gender."; action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
I have added
<?php
header("location:page.html");
exit; }
<?
to the very top of my form page. However it just loads page.html rather loading after submit button is clicked.
1) Please don't use PHP_SELF, it is vulnerable to exploitation. If you want the action to be the same page, just leave it empty.
2) The header(), which I assume is at the top of the page since it works, has no control on it.
EDIT1: Expanding based on question in comment below.
3) The header() directive will forward the browser to the new page and stop any further processing. Because of this, all the MySQL processing should be complete before redirecting.
4) The $_POST array gets the key names from the name attribute of the inputs, so be sure that your <input type="submit" name="submitbtn" ... matches the $_POST['submitbtn']
<?php
if(isset($_POST['submit'])){
// MySQL stuff goes here
header("Location: page.html");
exit;
}
?>
you'll have to add the condition before header to check if data is submitted or not.
eg:
if(isset($_POST['btnname'])
{header("location:page.html");
exit; // this is unnecessary
}
Also, if you want to use form for submission, you'll need to post it on page.php.
as this code will redirect the page without saving the form's data anywhere.
My main suspect is that your PHP is set up to suppress warnings and errors. Turn them on in the php.ini file and see what the message is.
Most likely it will say something along the line like "html headers cannot be sent as there is already output in line so and so..."
The PHP hear function cannot work if there is any output already echoed from the page.
<?php
ob_start();
error_reporting(E_ALL & ~E_NOTICE);
if(isset($_POST['button'])){
header('Location:page.html');
exit;
}
?>
Can you modify the code like this ?

Categories