php not functioning inside html file but works outside - php

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>

Related

php and html form in single file

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>

Php to add to html file

How can I use PHP to edit a html file on a website? To explain what I want to do, I want to have a php file with input boxes to add to a list in html.
So admin.php will edit index.html by adding more contents to the list.
<body>
<li>
<ul>Dog</ul>
<ul>Cat</ul>
</li>
</body>
https://jsfiddle.net/dam30t9p/
You should use a database to store the contents and then using php - extract the contents out of the db and echo them into the page.
Also you need to swap the ul's and li's in your document:
<body>
<ul>
<li>Dog</v>
<li>Cat</li>
</ul>
</body>
for example:
<body>
<ul>
<?php
//method to extract data from the db giving a variable called $content
foreach($rows as $row //whatever loop you created)
{
$content=$row['content'];
echo"<li>".$content."</li>";
}
?>
</ul>
</body>
As I mentioned in my comment, I recommend you create a form that then saves this information (in a database, text file, or other storage option), and then another php file would extract that information. Since I believe you are new to programming, I will explain how to do it with a text file, however I HIGHLY recommend you use a database to store the information, not just because of it's speed in executing queries, but for securely storing information that might be sensative.
Form page: Index.php
<!DOCTYPE html>
<html>
<head></head>
<body>
<form method="POST" action="action.php">
<input type="text" name="message1">
<input type="text" name="message2">
<input type="submit" value="Submit">
</form>
</body>
</html>
Php page that saves the information: action.php
<?php
//receiving the values from the form:
//I also used htmlspecialchars() here just to prevent cross
//site scripting attacks (hackers) in the case that you
//echo the information in other parts of your website
//If you later decide to store the info in a database,
//you should prepare your sql statements, and bind your parameters
$message1 = htmlspecialchars($_POST['message1']);
$message2 = htmlspecialchars($_POST['message2']);
//saving the values to a text file: info.txt
$myFile = fopen('info.txt', 'w');
fwrite($myFile, $message1."\n");
fwrite($myFile, $message2."\n");
fclose($myFile);
?>
Then in another php file you would retrieve that information and use it in your website:
page2.php
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
$myFile = fopen('info.txt', 'r');
$message1 = fgets($myFile);
$message2 = fgets($myFile);
fclose($myFile);
echo "message1 = ".$message1;
echo "message2 = ".$message2;
?>
</body>
</html>
Let me know if that helped!

Using multiple PHP files while avoiding redirect loop and resubmission

So I am pretty new to PHP, I have done and learnt lots of console based experience so I'm not a full beginner to programming. But I decided to learn how to database because its always fascinated me, and I've learnt the basic HTML and CSS and JS, and now basic PHP and SQL, but putting into action is getting weird on me.
I've figured out how to manipulate and make databases through PHP code and stuff like that, but they were all simple things and in one file, I am going for a bigger project and I need to put all the PHP's in separate files, this is the problem.
say my 'index.php' file is so:
<!DOCTYPE html>
<html>
<head>
<?php include 'other.php' ?> //Problem 1
</head>
<body>
<FORM method="POST" action="other.php">
<INPUT type="text" name="textTest" value="<?php print $input; ?>">
<INPUT type="submit" name="subTest" value="TEST" >
</FORM>
</body>
</html>
and my 'other.php' is :
<?php
$input = "";
if (isset ($_POST['subTest']))
{
$input = $_POST['textTest'];
//header("Location : index.php");
}
header("Location: index.php"); //Problem 2
?>
so my problems:
Problem 1, if I don't include the 'other.php' file, there is an error when I try print the: value = "print $input"
Problem 2, if I don't redirect with 'header', it obviously doesn't redirect and go back to the 'index.php' which I want to happen. BUT with it there, it causes a TOO_MANY_REDIRECT error. I found this is a problem caused by the include which can't be removed for Problem 1 reasons.
Problem 3, I found out I could move the 'header' function to where it is commented out, but then the value="..." doesn't stay on submit.
Problem 4, if I completely get rid of the 'header' redirect, and change the form's action to 'index.php', then I get the 'Confirm Form Resubmission' thing I want to avoid.
So I hope that is a mouthful someone understands and can help with, and thankyou in advanced.
include does what it sounds like, it includes the file into the parent, essentially the same as copy and pasting the content into it.
So to fix your problem, 1st change the forms action to index.php (so it posts to its self), and remove the redirect all together:
<?php include 'other.php' ?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<FORM method="POST" action="index.php">
<INPUT type="text" name="textTest" value="<?php print $input; ?>">
<INPUT type="submit" name="subTest" value="TEST" >
</FORM>
</body>
</html>
other.php:
<?php
$input = "";
if (isset ($_POST['subTest'])){
$input = $_POST['textTest'];
}
Note that i also moved the include to the 1st line in index.php, before any html output.
This is not strictly required in this instance, but is a good practice, as you are unable to set headers (eg for a redirect) after the response body is sent to the output stream
EDIT
If you want to avoid form resubmits on refresh, then you are correct that you would need to submit to a seperate endpoint and redirect.
To do that you would need to pass the posted data back to the index file, as the redirect is a new (GET) request, so the post data is lost.
The two main ways to do that would be with SESSION or URL parameters.
I'll show how to do it with parameters:
Dont include the destination file:
<?php
//get value from url parameter, or set to empty string if parameter not present
$input = isset($_GET['input'])? $_GET['input'] : '';
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<FORM method="POST" action="other.php">
<INPUT type="text" name="textTest" value="<?php print $input; ?>">
<INPUT type="submit" name="subTest" value="TEST" >
</FORM>
</body>
</html>
Then append the required data to the redirect url as parameters
other.php:
<?php
$input = "";
if (isset ($_POST['subTest'])){
$input = $_POST['textTest'];
header("Location: index.php?" . http_build_query(['input'=>$input]));
die(); //always stop execution after redirect
}
//if post data not sent, something went wrong, so set $input parameter to error message
header("Location: index.php?" . http_build_query(['input'=>'No Data posted']));
die(); //always stop execution after redirect
In other.php at the last line try require-ing the index.php instead of redirrecting.
Also remove the inclusion of other.php in index.php .
$input = "";
if (isset ($_POST['subTest']))
{
$input = $_POST['textTest'];
}
require_once 'index.php';
?>

Weird behaviour with QR Code generation

I've below working code in PHP
<?php
include('../../lib/qrlib/qrlib.php');
QRcode::png('PHP QR Codep :)');
?>
The weird part is if I put a space in front of
<?php
then the same code does not work & error log does not show any details either. Also, if I put any other function in the top code before this code, the QR code does not get generated. No error in log either.
What am I missing here???
Update:
Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$myErr = "";
$myid = "";
function generateRandomCode() {
// returns random code
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["myid"])) {
$myidErr = "myID is required";
}
$code = generateRandomCode();
}
?>
<h2>My Project</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
My ID: <input type="text" name="myid" value="">
<span class="error">* <?php echo $myidErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>QR Code:</h2>";
$tem = '"myid":"' . $myid . '","code":"' . $code . '"}';
include('../../lib/qrlib.php');
QRcode::png($tem);
?>
</body>
</html>
Looking at the source code for QRcode::png(), I can see that it sends a Content-Type header prior to displaying the PNG image data. That is necessary to inform the receiving browser or device that the data is a PNG image.
// Excerpted from source:
if ($filename === false) {
Header("Content-type: image/png");
ImagePng($image);
// etc...
https://github.com/t0k4rt/phpqrcode/blob/f0567ce717fa1172cb66c48ebae017a094de64b1/qrimage.php#L30
If you have leading whitespace before the opening <?php or any output of any kind before that function is called, PHP will not be able to send the necessary headers.
For full details on this issue and all its potential causes, see How to fix Headers already sent errors in PHP.
Always when developing and testing code, ensure that you have enabled PHP's error display. If it were on, you would have seen PHP issuing warnings related to headers already being sent.
Warning: Cannot modify header information - headers already sent by....etc...
// At the very top of your script:
error_reporting(E_ALL);
ini_set('display_errors', 1);
Or set error_reporting and display_errors in your php.ini. The fact that you saw no errors in your log suggests you either have log_errors disabled in php.ini, or a conservative setting for error_reporting which is not reporting on E_WARNING errors. Best to use E_ALL.
Update after code posted:
You have attempted to call QRcode::png() inside the same script which is currently generating your HTML page. You can't actually do that, because the QR code has to be generated and inserted into an <img> tag. Even though it is generated at runtime by PHP, from the browser's perspective it isn't any different from a real image read from a file on disk so you have to use it the same way in HTML markup as you would a file from disk.
The easiest method to handle this properly is to move the QR code generation to a different PHP file where it is the only action taking place. Then reference that file in an <img> tag's src.
File: generate_qrcode.php
This PHP script is intended to be referenced as example.com/generate_qrcode.php?myid=abcdefg. If you called it as such from the browser, it should just display the bare QR code.
// Contains only QR generation
// Move the $code here, and pass the myid in the query string
// Also move the function definition here
function generateRandomCode() {
// whatever...
}
$code = generateRandomCode();
// This value was originally POSTed to the main script, so
// it needs to be passed from the main script to this one via the query string
$myid = $_GET['myid'];
$tem = '"myid":"' . $myid . '","code":"' . $code . '"}';
include('../../lib/qrlib.php');
QRcode::png($tem);
Main PHP file:
To really use it the way you want in context of your HTML page requires an <img> tag though.
Include an <img> tag which sources the QR code and passes $myid in its query string. The PHP/HTML should not call QRcode::png() itself.
<img src="generate_qrcode.php?myid=<?php echo htmlspecialchars($myid); ?>" alt="QR code" />
This would result in a tag like <img src="generate_qrcode.php?myid=abcdefg" alt="QR code" />
For full context, your main script would now look like:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$myErr = "";
$myid = "";
// This function is defined instead in the QR code script...
//function generateRandomCode() {
// returns random code
//}
// POST handling is the same!
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["myid"])) {
$myidErr = "myID is required";
}
// But this is done in the other QR code script
//$code = generateRandomCode();
}
?>
<h2>My Project</h2>
<!-- The form is the same! -->
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
My ID: <input type="text" name="myid" value="">
<span class="error">* <?php echo $myidErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if ($myid) {
echo "<h2>QR Code:</h2>";
// Now include an <img> tag
echo "<img src='generate_qrcode.php?myid=$myid' alt='QR code' />";
}
?>

form variables not passing to php

I have a simple form and I'm trying to pass the form variable to php and output the value. I have tried to solve this myself with the almighty google but wasn't successful. The html form code is as follows
<html>
<head>
<title>Form</title>
</head>
<body>
<form method="post" action="test1.php">
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
Then the php to handle the form is:
<html>
<head>
<title>Form</title>
</head>
<body>
<?php
echo "<h1>Hello " . $_POST["username"] . "</h1>";
?>
</body>
</html>
The output I'm getting no matter what I type into the html form is , Hello " . $_POST["username"] . ""; ?>
I don't know why it also outputs the ending semi colon and ending php tag also, maybe this is evidence of what's going wrong here?
PHP is
misconfigured or
not configured or
not working or
not working within HTML files.
You have to configure your webserver that it parses PHP inside HTML files, see here for example:
=> Server not parsing .html as PHP
The syntax is fine, try to write a sample code snippet like below
<?
$a = "hello word!";
echo $a;
?>
and check if php is working.

Categories