I'm trying to write a simple PHP web page that asks the user to input a domain and then click the SUBMIT button. When the user clicks SUBMIT the page should display the name of the domain that they typed in.
I have XAMPP installed on my computer and I have a file named test234.php in my htdocs directory. This PHP file contains the following PHP and HTML code:
<?php
$message = "";
if (!isset($domain)) {
$message = "<br>Enter a domain<br>";
} else {
$message = "You typed in $domain as the domain";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Some title</title>
</head>
<body>
<h1 align="center">
Some title
<?php print $message ?>
</h1>
<form method="POST" align="center">
Domain: <input type="text" name="domain"><input type="submit" align="center"><br>
</form>
</body>
</html>
When I type in a domain and click SUBMIT it just reloads the same page asking for the user to type in a domain. I want it to output the text "You have typed in $domain as the domain" but can't seem to get it to work. Any help would be appreciated.
The value of $domain was never declared. If you would like to get form data you need to use the $_GET, $_POST, or $_REQUEST object(s), in your case you are using the post method in your form so instead of $domain use $_POST["domain"]:
<?php
$message = "";
$domain = $_POST["domain"];
if (!isset($domain)) {
$message = "<br>Enter a domain<br>";
} else {
$message = "You typed in $domain as the domain";
}
?>
Related
I am trying to configure a basic contact POST form with one checkbox input and server-side validation. This means the form must submit to itself, so a self-serving contact form. The problem I'm having is when refreshing the page, the form is submitted again.
I am using session data to store form validation as this form is an initial popup to which the user must tick and confirm to enter the page. The page has two contact forms on it but I am showing one and I think the implementation should be the same for both (correct me if I'm wrong). Once the user ticks the box and submits the form, the popup form will hide allowing the user to see the page.
To solve this, I believe the POST/REDIRECT/GET design pattern should prevent this, however, I don't think my implementation is correct and I don't know what is wrong in my code.
index.php code below:
<!DOCTYPE html>
<html lang="en">
<?php
session_start();
include('form_process.php');
?>
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="assets/css/main.min.css" />
</head>
<body>
<section id="selfCertOverlay" <?=$_SESSION['closeSelfCert']?>>
<div class="blurOverlay">
<form id="selfCert" method="post">
<label for="self_cert">I have read and confirm the statement.
<input type="checkbox" name="self_cert" id="self_cert">
<span id="checkmark" class="<?= ($_SESSION['self_cert_checkbox_error']) ? 'inputError' : ''; ?>"></span>
<span class="error"><?= (isset($_SESSION["self_cert_error"])) ? $_SESSION["self_cert_error"] : ''; ?></span>
</label>
<input type="submit" name="submit_self_cert" value="Confirm & Proceed">
</form>
</div>
</section>
</body>
</html>
form_process.php code below:
<?php
$_SESSION["self_cert_error"] = "";
$_SESSION["self_cert_checkbox_error"] = false;
if (!isset($_POST["self_cert"])) {
$_SESSION["self_cert_error"] = "Please read and accept the statement to proceed";
$_SESSION["self_cert_checkbox_error"] = true;
} else {
unset($_SESSION["self_cert_error"]);
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value) {
$keyOutput = str_replace('_', ' ', $key);
$keyOutput = ucwords($keyOutput);
$message_body .= "$keyOutput: $value\n";
}
$to = 'example#mailprovider.com';
$subject = 'Email Subject';
if (mail($to, $subject, $message_body)){
$_SESSION["closeSelfCert"] = 'style="display: none;"';
// Redirect to itself.
header( "Location: {$_SERVER['REQUEST_URI']}", true, 303 );
return;
}
}
?>
The refresh button on the browser resends the last HTTP request that was sent by the client. This is why when you refresh the page, it re-submits the form.
The only way to get around this is to use the POST/REDIRECT method.
To setup a POST/REDIRECT method, use an intermediate page to do the operations and then redirect to the original form afterwards.
For example:
index.php --> the page with the form on - make sure the form has action="form_process.php" declared, so it will POST the data to the form_process.php script
form_process.php --> receives the form data and carries out your operations, then redirects back to the index.php page at the end.
So your final code should look something like the below;
index.php
I have removed the include('form_process.php'); at the top
I have added action="form_process.php" to the <form> tag
<!DOCTYPE html>
<html lang="en">
<?php
session_start();
?>
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="assets/css/main.min.css" />
</head>
<body>
<section id="selfCertOverlay" <?=$_SESSION['closeSelfCert']?>>
<div class="blurOverlay">
<form id="selfCert" method="post" action="form_process.php">
<label for="self_cert">I have read and confirm the statement.
<input type="checkbox" name="self_cert" id="self_cert">
<span id="checkmark" class="<?= ($_SESSION['self_cert_checkbox_error']) ? 'inputError' : ''; ?>"></span>
<span class="error"><?= (isset($_SESSION["self_cert_error"])) ? $_SESSION["self_cert_error"] : ''; ?></span>
</label>
<input type="submit" name="submit_self_cert" value="Confirm & Proceed">
</form>
</div>
</section>
</body>
</html>
form_process.php
I have added session_start(); at the top so you can access the $_SESSION data
I have added header( "Location: index.php", true, 303 ); within your first IF statement
I have altered your header() routing which takes place after you send your email, so this redirects back to index.php
<?php
session_start();
$_SESSION["self_cert_error"] = "";
$_SESSION["self_cert_checkbox_error"] = false;
if (!isset($_POST["self_cert"])) {
$_SESSION["self_cert_error"] = "Please read and accept the statement to proceed";
$_SESSION["self_cert_checkbox_error"] = true;
header( "Location: index.php", true, 303 );
exit;
} else {
unset($_SESSION["self_cert_error"]);
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value) {
$keyOutput = str_replace('_', ' ', $key);
$keyOutput = ucwords($keyOutput);
$message_body .= "$keyOutput: $value\n";
}
$to = 'example#mailprovider.com';
$subject = 'Email Subject';
if (mail($to, $subject, $message_body)){
$_SESSION["closeSelfCert"] = 'style="display: none;"';
// Redirect back to the form page.
header( "Location: index.php", true, 303 );
exit;
}
}
?>
Which has higher security?
Including the PHP file on a web page for form use, or directing the user to a PHP file when they press a form button?
Example 1: include 'filename';
Example 2: form action="sendingtheuserhere.php" method="post"
Thank you
Generally, it wouldn't matter whether you include the PHP code that handles form data into the file that contains the form or to have a separate PHP file for the same purpose.
What would matter is how you handle the form data. Below is an example:
form.php - has the HTML form
<html>
<head></head>
<body>
<form action="send.php" method="post">
<input name="subject" />
<textarea name="message"></textarea>
<button>Send</button>
</form>
</body>
</html>
send.php - handles form data
<?php
$user_subject = $_POST['subject'];
$user_message = $_POST['message'];
$send_to = 'myemail#gmail.com';
mail($send_to, $user_subject, $subject_message);
?>
Now with the above code, there are a couple things you should know.
The send.php file has unsafe code.
Visiting the send.php will send an email to the $send_to address whether someone files the form or not.
Now if you were to have to separate files, every time you visit the send.php file, an email would be sent. That is whether you fill in the form or you simply visit send.php link.
Second, if you were to combine the two files, you would have an email sent to you every time someone opens your form. That is because the mail(); function is triggered every time.
To combat this, you have to make sure the mail function triggers only when the form is submitted. You can do so by changing the code in send.php to the following:
new send.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { // checks whether a POST request actually exists or not.
$user_subject = strip_tags(trim($_POST['subject']));
$user_message = strip_tags(trim($_POST['message']));
$send_to = 'myemail#gmail.com';
mail($send_to, $user_subject, $subject_message);
} else {
echo 'form not filled';
}
?>
Now, in the above code, the first thing we did is to check whether a POST request actually existed. If not, you'll see "Form not filled". After that, to make the request a little more secure to any sort of code injections we used the PHP trim(); and strip_tags(); function.
You can combine the two PHP files like so:
form.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { // checks whether a POST request actually exists or not.
$user_subject = strip_tags(trim($_POST['subject']));
$user_message = strip_tags(trim($_POST['message']));
$send_to = 'myemail#gmail.com';
mail($send_to, $user_subject, $subject_message);
}
?>
<html>
<head></head>
<body>
<form action="form.php" method="post">
<input name="subject" />
<textarea name="message"></textarea>
<button>Send</button>
</form>
</body>
</html>
Now I have Simple email Login form
<form action="one.php">
<input type="email" name="email"/>
</form>
one.php is email filter gmail users and header them to a custom path
<?php
$email = $_POST['email'];
if (stripos($email, '#gmail.com') !== false) {
header('Location: ../gmail/index.html');
} else {
header('Location: /unknownusers');
}
?>
now we done with the first page
my question is
how can I email name to another page' example in /gmailusers
<html>
<head>
</head>
<body>
<div>
<font>Welcome back,</font>
<?php
include 'one.php';
echo $email; ?>
</div>
</body></html>
$email will not work in this because one.php doesn't have saved info
how I can make this
welcome back 'User.Email#gmail.com'
in index.html file
Can any body help me with the php code.
The easiest way to do this is to not use location redirection, but just include the file you want to show.
one.php
<?php
$email = $_POST['email'];
if (stripos($email, '#gmail.com') !== false) {
include "gmail.php";
} else {
header('Location: /unknownusers');
}
gmail.php
(This file would replace gmail/index.html because most server configurations won't pass .html files to the PHP processor.)
<html>
<head>
</head>
<body>
<div>
<font>Welcome back, <?php echo $email; ?></font>
</div>
</body></html>
In this case, one.php shows the gmail user what gmail.php dictates, and redirects other users to the unknownusers page.
If you want the 'login' to be persistent (so your server remembers who this person is), you'll need a session.
What you're doing doesn't make sense, but to get it working, in two.php replace...
echo $email;
with
echo $_POST['email'];
HOWEVER You're reloading the page in one.php, so the code change above should never be executed. (Why are you doing that?) Anyway, if security is not an issue, in one.php you can pass the email to the other pages by doing this...
header('Location: ../gmail/index.html&email='.$_POST['email']);
then, in the index.html file, you access the variable $_GET['email'].
If security is an issue, this gets more complicated.
I have a short sample php code above:
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<title>Check for perfect palindrome</title>
</head>
<body>
<h1>Check for perfect palindrome</h1>
<form method="post">
<label for="stringInput">String:</label><input type="text" id="stringInput" name="stringInput"><br/>
<br/><input type="submit" name="submit" value="Check"/>
</form>
</body>
<?php
if(isset($_POST['stringInput']))
{
$string = $_POST['stringInput'];
if ($string =="")
{
echo "Please fill the form";
} else if ($string == strrev($string))
{
echo "You entered: <b>'$string'</b> is a perfect palindrome.";
} else
{
echo "You entered: <b>'$string'</b> is NOT a perfect palindrome.";
}
}
?>
</HTML>
Imagine that the code is saved under file sample.php and located at localhost/sample.php.
I want to fill the form and trigger the submit button through this link:
localhost/sample.php?stringInput=abc&submit=Check
How can I do that? Thanks for help.
I need to use POST method because the actual form has many inputs not just one and I want to know how it will work with POST. And using PHP only if possible. (Javascript, jQuery are not the first choices). Cheers.
This is a good example to demonstrate what I need.
http://image.online-convert.com/convert-to-jpg?external_url=jhjhj&width=333
I tried GET method and the form doesn't display value.
If you want to include the parameters in the URL you cannot use POST
From wikipedia:
the POST request method requests that a web server accept the data enclosed in the body of the request message
Whereas in a GET request (from w3schools):
the query string is sent in the URL of a GET request
Try this:
You can assign your post values to variables & echo them in your input.
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<title>Check for perfect palindrome</title>
</head>
<body>
<?php
$string = "";
if(isset($_POST['stringInput']))
{
$string = $_POST['stringInput'];
if ($string =="")
{
echo "Please fill the form";
} else if ($string == strrev($string) )
{
echo "You entered: <b>'$string'</b> is a perfect palindrome.";
} else
{
echo "You entered: <b>'$string'</b> is NOT a perfect palindrome.";
}
}
?>
<h1>Check for perfect palindrome</h1>
<form method="post">
<label for="stringInput">String:</label><input type="text" id="stringInput" name="stringInput" value="<?php echo $_REQUEST['stringInput'];?>"><br/>
<br/><input type="submit" name="submit" value="Check" />
</form>
</body>
</HTML>
You are using the wrong http method instead of POST you should use GET
"Note that the query string (name/value pairs) is sent in the URL of a
GET request"
Check more about these two methods here: POST vs GET
I'm learning web design and have run into a difficulty that I can't figure out by myself.
I want to dynamically load a form into a using jQuery. My code looks like this:
From within the main file:
$('#left_colum').click(function(e) {
e.preventDefault();
$('#column_left').load(create_album.php);
});
create_album.php -> it contains the actual form, as well as the php script that handles it on POST. It's very basic. If I load up my_form.php by its own, it works fine. If I dynamically load it as above; the HTML works but the POST php script doesn't execute.
There is also another interesting behavior; if I click the submit button on the dynamically loaded form, it all disappears (unlike the "properly" loaded one).
I've gone through a lot of posts and tutorials, and I haven't been able to find a solution other than using iframes. It seems that people generally don't dynamically load anything other than basic HTML that doesn't have to talk back to the server. I'm new to this : P
Is there a fix or another way of doing it? Thanks!
Edit:
albums.php:
<?php
include 'init.php';
if(!logged_in()) {
header("Location: index.php");
exit();
}
?>
<h3>Albums</h3>
<?php
/*Output albums*/
$albums = get_albums();
if(empty($albums)) {
echo("You don't have any albums");
} else {
/*Changed: uploading images is now part of the albums sections*/
foreach($albums as $album) {
echo '<p><a class="album_view" id="'.$album['id'].'" href="">', $album['name'], '</a> (', $album['count'], ' images)<br/>Description: ', $album['description'], '...<br/><a class="album_edit" id="'.$album['id'].'" href="">Edit</a> / Delete / <a class="upload_image" id="'.$album['id'].'" href="">Upload</a></p>';
}
}
?>
<script type="text/javascript">
$(document).ready(function() {
/*Creating albums*/
$('#create_album').click(function(e) {
e.preventDefault();
$('#column_left').load(album.php);
});
});
create_album.php:
<h3>Create Album</h3>
<?php
if(isset($_POST["album_name"], $_POST["album_description"])) {
echo 'got here';
$album_name = $_POST["album_name"];
$album_description = $_POST["album_description"];
$errors = array();
if(empty($album_name) || empty($album_description)) {
$errors[] = "Album name and description required";
} else {
if(strlen($album_name) > 55 || strlen($album_description) > 255) {
$errors[] = "Name/description too long";
}
}
if(!empty($errors)) {
foreach($errors as $error) {
echo $error, "<br/>";
}
} else {
echo 'got here, too';
//create_album($album_name, $album_description);
//header("Location: albums.php");
}
}
?>
<form action="" method="post">
<p>Name:<br/><input type="text" name="album_name" maxlength="55"/></p>
<p>Description:</br><textarea name="album_description" rows="6" cols="35" maxlength="255"></textarea></p>
<p><input type="submit" value="Create"/></p>
</form>
I think that's:
$('#column_left').load('my_form.php');
right?
Anyways:
Is the form showing up correctly?
Try having a look at the generated source, by using firebug, in order to see if the loading was successful
Make sure that "my_form.php" returned html isn't the whole <html> but just <form> and its content
What's the form action? Is it an absolute path or not? If it is relative, it may point to different locations when called from the ajax-loading page or from my_form.php
Are you submitting the form vja ajax, or "the standard way"?
What does exactly happen when you click on form submit? Where do you get redirected?
because your form action would be to a different page so every time you click submit button it redirect you to that page , you can try using iframe it will work that way or if you want to use jquery only than paste some of your code so that we can understand what's actually happening... though iframe is the best solution for you as if now
With your code, you load only the html part of you form. So when user push submit button, your fields had sended to original page and not to "my_form.php", where I suppose you manage POST datas.
The easiest solution is to use IFRAME to load you form code.
Your form action is missing try this, i have tried and working on my end
album.php
<h3>Create Album</h3>
<?php
if(isset($_POST["album_name"], $_POST["album_description"])) {
echo 'got here';
$album_name = $_POST["album_name"];
$album_description = $_POST["album_description"];
$errors = array();
if(empty($album_name) || empty($album_description)) {
$errors[] = "Album name and description required";
} else {
if(strlen($album_name) > 55 || strlen($album_description) > 255) {
$errors[] = "Name/description too long";
}
}
if(!empty($errors)) {
foreach($errors as $error) {
echo $error, "<br/>";
}
} else {
echo 'got here, too';
//create_album($album_name, $album_description);
//header("Location: albums.php");
}
}
?>
<form action="album.php" method="post">
<p>Name:<br/><input type="text" name="album_name" maxlength="55"/></p>
<p>Description:</br><textarea name="album_description" rows="6" cols="35 "maxlength="255"></textarea></p>
<p><input type="submit" value="Create"/></p>
yourmainfile.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Untitled</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#create_album').click(function(e) {
e.preventDefault();
$('#column_left').load('album.php');
});
});
</script>
</head>
<body>
<div id="mainWrapper">
<div id="column_left"></div><!-- end column left -->
Create New Album
</div><!--end mainWrapper-->
</body>
</html>