php and html form in single file - php

I wonder if there is a problem for a php file that contains php codes and html form.
for example:
in the file the first part would be:
<?php ...
?>
<html>...<form action = "current file"> ..... </form>
</html>
The action will refer to the name of this current file.
or do I have to separate the php code in a file with extension .php, and html code in a file with extension .html?

Test it on your own– You can.
You can also use PHP inside of a HTML tag, because the PHP is loaded server-side whenever the client sends a request.
Client sends request --> Server gets request and loads up the .php file --> Server loads the php, executes the php, and replaces all php objects with text that it returns, or nothing --> Client gets the file that has been loaded (and edited) via the server
Note: If you combine PHP with HTML, the file needs the extension .php because HTML does not originally support PHP tags.

Here's an example for a php and html form in same file. Ofcourse the file extension needs to be .php
You just need to change 'action="current file"' to 'action=""'
index.php
<?php
if(isset($_POST['submit'])) {
// The things that needs to be checked and executed WHEN submitted.
$email = htmlspecialchars($_POST['Email']);
$email = strip_tags($email);
$password = htmlspecialchars($_POST['Password']);
$password = strip_tags($password);
//SQL STUFF
if ($email === $row['email'] && $password === $row['password']) {
$_SESSION['uuid'] = $row['uuid'];
header("Location: profile.php?id=". $row['uuid'] ."");
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>My Form</title>
</head>
<body>
<form action="" method="POST">
<input type="email" name="Email" placeholder="Email..." required>
<input type="password" name="Password" placeholder="Password..." required>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

Related

Saving data from HTML form on server?

How do i save data from a HTML form on a server?
Here is my code:
<form action="?action=save" name="myform" method="post">
<textarea class="textBox" name="mytext"> </textarea>
<input type="submit" class="save" value="save"/>
Thanks in advance.
You will need to change the action name to point to where the PHP code will be. I put my PHP code on the same page as my HTML and changed the action to save.php (that's my file name where the PHP is).
This is my save.php file where everything is.
<?php
// Check if form is submitted and we have the fields we want.
if(isset($_POST["mytext"]))
{
$file = "data.txt";
$text = $_POST["mytext"];
// This file will create a data.txt file and put whatever is in the POST field mytext into the text and put a new line on the end.
// The FILE_APPEND allows you to append text to the file. LOCK_EX prevents anyone else from writing to the file at the same time.
file_put_contents($file, $text . "\r\n", FILE_APPEND | LOCK_EX);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Save POST Data</title>
</head>
<body>
<form action="save.php" name="myform" method="post">
<textarea class="textBox" name="mytext"></textarea>
<input type="submit" class="save" value="save"/>
</body>
</html>
Easiest way its set action on save.php and in this file put
<?php
if(isset($_POST)){
file_put_contents('file.txt', json_encode($_POST));
}
You can handle the submit event by js, and send the data to server by using Ajax or fetch. Then in your server side, build an API to catch the request and store data in database or any file you want to store your data.
Best

How to save string entered in HTML form to text file

I have a very basic PHP file. i want to have two textboxes for user input, and a submit button. The user will enter their first and last name, then i would like to append or create a TXT file with the data entered from field1 and field2.
Possibly i am going about this the wrong way. I will post two of the ways i have been tinkering around with.
<html>
<head>
<title>Field1 & 2</title>
</head>
<body>
<form>
What is your name?<br>
<input type="text" name="field1"><br>
<input type="text" name="field2"><br>
<input type="submit" value="Submit">
</form>
<?php
$txt= $_POST['field1'].' - '.$_POST['field2'];
$var_str3 = var_export($txt, true); //is this necessary?
$var3 = "$var_str3"; //is this necessary?
file_put_contents('fields.txt', $var3.PHP_EOL, FILE_APPEND);
?>
</body>
</html>
I cant figure out how to get the data from field1 and field2 into a string variable.
I have also messed around with using this php instead of the section listed above
<?php
$txt= "data.txt";
if (isset($_POST['field1']) && isset($_POST['field2'])) {
$fh = fopen($txt, 'a');
$txt=$_POST['field1'].' - '.$_POST['field2'];
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the file
}
?>
You should learn about HTML Forms And PHP Form Handling.
In your code you have to use a form HTTP method. And the form data must sent for processing to a PHP file.
In this code i use HTTP PSOT method you can also use GET method the result will be same. This two method is used for collecting the form data. And the php file name is "action.php".
index.html
<html>
<head>
<title>Field 1 & 2</title>
</head>
<body>
<form action="action.php" method="post">
What is your name?<br>
<input type="text" name="field1"><br>
<input type="text" name="field2"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
action.php
<?php
$path = 'data.txt';
if (isset($_POST['field1']) && isset($_POST['field2'])) {
$fh = fopen($path,"a+");
$string = $_POST['field1'].' - '.$_POST['field2'];
fwrite($fh,$string); // Write information to the file
fclose($fh); // Close the file
}
?>
Let's take a snippet from http://www.w3schools.com/html/html_forms.asp
<form action="action_page.php" method="post">
First name:<br>
<input type="text" name="firstname" value=""><br>
Last name:<br>
<input type="text" name="lastname" value=""><br><br>
<input type="submit" value="Submit">
</form>
Note the first line: upon form submission a php script is called: action_page.php.
action_page.php is your webpage with the form and the embedded php script. action_page.php both displays the empty form and then process the submitted data.
On the first line also it is specified that the submitted data is sent with the POST method.
The php part will look like this:
<?php
if( isset($_POST['firstname'] ) && isset( $_POST['lastname'] ) )
{
$txt= $_POST['firstname'].' - '.$_POST['lastname'] . PHP_EOL;
file_put_contents('fields.txt', $txt, FILE_APPEND);
}
?>
The if statement is there because the first time the script action_page.php is loaded its purpose is only to display the form and don't receive any POST data.
As the form is submitted by the user the script will receive the data and store to file.
The script will also (with this approach) display again an empty form ready for the submission of another entry.
You can rearrange things in order to have two web pages: one with just the form, another one with a "Thank you" message and the data processing php script.

php not functioning inside html file but works outside

I have been following the php tutorial here
CODE
Here is my html file:
<!DOCTYPE html>
<html>
<head>
<link rel=”stylesheet” type=”text/css” href=”style.css”>
<form action="postForm.php" method="post">
<TextArea name="microBlog" id="microBlog" cols="30" rows=“10"></TextArea>
<input type="submit">
</form>
</head>
<body>
<?php
require_once 'meekrodb.2.3.class.php';
DB::$user = 'root';
DB::$password = '';
DB::$dbName = 'MicroBlog';
$results = DB::query("SELECT post FROM MicroBlog");
foreach ($results as $row){
echo "<div class='microBlog'>" . $row['post'] . "</div>";
}
?>
</body>
</html>
This yields the following:
However if I copy the php code into a new postForm.php file and click "Submit" (as you can see the action is postForm.php), it works.
I get my blank screen with 3 words (from the database).
The problem is it is a brand new blank page and I do not want that.
PROBLEM
Why is it that the code works outside the html file, but not inside the html file. Why do I get ".row['post']."";} ?> when inside the html file but I get perfect output when the php exists in its own php file?
There is clearly nothing wrong with the code, so what could it be?
It really confuses me. Thanks for any answers.
Change your file extension .html into .php or .phtml. It will solve your problem.
You are writing a php code inside html file. html file doesn't evaluate php code.change the extension of file to .php instead of .html by doing so you write both html and php code inside that file.
Reason: 1. An html file does not support php scripts inside it and thus anything written will not be executed and will only be treated as an html markup.
Solution:
1. Just save the .html file as .php file and you are done!(very simple).For example if your file name is index.html, just save it as index.php and all the php scripts inside will be executed.
index.php:
<!DOCTYPE html>
<html>
<head>
<link rel=”stylesheet” type=”text/css” href=”style.css”>
<form action="postForm.php" method="post">
<textArea name="microBlog" id="microBlog" cols="30" rows=“10"></textArea>
<input type="submit">
</form>
</head>
<body>
<?php
require_once 'meekrodb.2.3.class.php';
DB::$user = 'root';
DB::$password = '';
DB::$dbName = 'MicroBlog';
$results = DB::query("SELECT post FROM MicroBlog");
foreach ($results as $row){
echo "<div class='microBlog'>" . $row['post'] . "</div>";
}
?>
</body>
</html>

Error while Processing a Basic Form in PHP

The problem goes as follows:
File 1 which has the name of: Lesson 17_Forms - Simple Form.php
and
File 2 which has the name of: Lesson 17_Forms - Process.php
The contents of file 1 are as follows:
<html>
<title>Lesson 17_Forms - Simple Form</title>
<head>
<center><h1>Lesson 17_Forms - Simple Form</h1></center>
</head>
<body>
<form action= "Lesson 17_Forms - Process.php" method="post">
Username: <input type="text" name="username" value="" />
<br />
Password: <input type="password" name="password" value="" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
The contents of file 2:
<html>
<title>Lesson 17_Forms - Process</title>
<head>
<center><h1>Lesson 17_Forms - Process</h1></center>
</head>
<body>
<?php
// Ultra-simple form processing
// Just retrieve the value and return it to the browser
$username = $_POST['username'];
$password = $_POST['password'];
echo "{$username}: {$password}";
?>
</body>
</html>
Both files are in the same directory, when i am trying to process the form by clicking the submit button, i am receiving the following error:
Object not found!
The requested URL was not found on this server. The link on the
referring page seems to be wrong or outdated. Please inform the author
of that page about the error.
If you think this is a server error, please contact the webmaster.
Error 404
localhost Sat 12 May 2012 02:40:39 PM EEST Apache/2.2.21 (Unix) DAV/2
mod_ssl/2.2.21 OpenSSL/1.0.0c PHP/5.3.8 mod_apreq2-20090110/2.7.1
mod_perl/2.0.5 Perl/v5.10.1
Any suggestions are greatly appreciated.
No spaces are allowed in url -> change the names to simple_form.php and process.php.
or if you want to keep spaces in name then replace all spaces by '%20' whenever you use it as a url.
Or the best option is to use urlencode -> it automatically replaces all non-allowed characters by their web acceptable placeholders.
<form action=<?php echo '"'.urlencode("Lesson 17_Forms - Process.php").'"'; ?> method="post">
Make sure you have both files on the same directory. Also, eliminate any spaces in file names, while valid, they will cause massive headaches. So name your files something more like: lesson17_forms_process.php.
Also, after some modifications, this is the code I get:
<?php
//Initialize variables
$fields_set = false;
$username = "";
$password = "";
//Validity check
if (isset($_POST['username']) && isset($_POST['password'])) {
$fields_set = true;
$username = $_POST["username"];
$password = $_POST["password"];
}
?>
<html>
<head>
<title>Lesson 17_Forms - Process</title>
</head>
<body>
<h1 style="text-align: center;">Lesson 17_Forms - Process</h1>
<?php
//Display results if validity passed, or error in case it didn't.
if ($fields_set) {
echo "{$username}: {$password}";
}
else {
echo "Error! username or password not set!";
}
?>
</body>
</html>
Some Points
I process all form data before I start sending HTML. Separate logic and display as much as possible.
I removed the h1 element from the head and placed it in the body (where it belongs). All page content must go in body.
I removed the presentational element <center> and replaced it with CSS.
I validate the input prior to processing.
I display an error in case the form is not valid.
I'll use your existing code, and modify it. With new file names.
I did also correct your HTML.
Create a file named: form.php, insert the code below:
<html>
<head>
<title>Submit form</title>
</head>
<body>
<center><h1>Submit form</h1></center>
<form action="process.php" method="post">
Username:<input type="text" name="username" value="" />
<br />
Password: <input type="password" name="password" value="" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Create a file named: process.php, insert the code below:
<html>
<head>
<title>Your form</title>
</head>
<body>
<center><h1>Lesson 17_Forms - Process</h1></center>
<?php
// Ultra-simple form processing
// Just retrieve the value and return it to the browser
$username = $_POST['username'];
$password = $_POST['password'];
echo "{$username}: {$password}";
?>
</body>
</html>
That should work perfectly, remember to have both files in the same folder.

Beginner Help: Creating and Storing Text Using PHP

I'm trying to write a program where the basic idea is I ask the user for input in a textarea, and then the text gets stored into a word file. Here is the code I'm trying to use:
<html>
<head>
<title>Simple Guestbook</title>
</head>
<body>
<h1>Simple Guestbook Comment Creator</h1>
<br>
<form method = "post"
action = "mysite.php">
<textarea name = "text"
rows = "10"
cols = "20">Write Here</textarea>
<input type = "submit"
value = "Submit Comment">
</form>
<?
if($_POST['text'] !== NULL){
$comment = $_POST['text'];
$file = fopen("texttest.txt", "a");
fputs($file, "<br>\n$comment");
fclose($file);
}
?>
</body>
</html>
I can't seem to get this to work properly. I was also thinking about somehow making the form action store the text and then reload the site, but I haven't gotten that to work (the original file is mysite.php, so the action is to just reload the page).
If anyone has any better ideas of an algorithm to use/different syntax to use, please let me know, as I just started learning basic PHP syntax.
Thanks
Check the following:
Does php have the permission to write files in that directory?
Is that php file called "myfile.php"?
Anyway, when something does not work and you want to know what's causing the arror, place error_reporting(-1); at the beginning of your php - it will output any error or warning, including the ones trown by fopen().
Also, you might want to check whether the variable has been correctly submitted: echo $comment right after you assign it.
Something like this might work.
You might want to do more with the values they are entering and all, but this will basically do what you are asking.
You will also want to make sure that you have the correct path of the file you are trying to write to and that that file has the correct permissions to allow it to be written to:
<html>
<head>
<title>Simple Guestbook</title>
</head>
<body>
<h1>Simple Guestbook Comment Creator</h1><br>
<?php
if (isset($_POST['submit'])) {
if (strlen(trim($_POST['comment']))) {
$file = fopen("texttest.txt", "a");
fputs($file, "$_POST['comment'])\n");
fclose($file);
}
} else {
?>
<form method = "post" action = "<?php echo($_SERVER['PHP_SELF']); ?>">
<label>Leave your comment
<textarea name="comment" rows="10" cols="20"></textarea>
</label>
<input type="submit" name="submit" value="Submit Comment" />
</form>
<?php
}
?>
</body>
Also, since you are returning to the same page you may want to put some kind of message letting the person know that they succeeded in entering something into your address book.

Categories