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' />";
}
?>
Related
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 3 years ago.
I have done a simple form like this:
index.php:
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<?php
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
// handle missing field
} else {
$name = $_POST["name"];
}
}
if($name != '') {
header('location: http://localhost/new_page.php');
exit();
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
<span class="label">Name</span>
<input type="text" name="name">
<button><span>Validate</span></button>
</form>
</body>
</html>
I would like the following behaviour:
staying on the form if the name field is not set by the user
going to new_page.php if name field is set
I have the following error right now: if I set the name, I am redirected to a blank.php page.
Can someone help me on this ? Or at least give me some tips to debug this as I am not really a PHP specialist.
Thank you !
Your header call comes too late.
an HTTP Response first has a header, then a body. HTML code is the body.
You need to put all output AFTER your PHP code. Since you start with <html>, headers will already have been sent and so your redirect will not work.
Also, regarding white pages (White screen of death or WSOD):
For the best error logging experience, set error_reporting to -1, turn display_errors off, and set a custom error_log. Then in the terminal, type 'tail -f /path/to/error_log'. Your notices, warnings and errors will now scroll past in real time, without distorting your web page's display.
The answer given by #delboy1978uk is correct.
All you have to do is change your file content to:
<?php
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
// handle missing field
} else {
$name = $_POST["name"];
}
if($name != '') {
header('location: http://localhost/new_page.php');
exit();
}
}
?><!DOCTYPE HTML>
<html>
<head></head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
<span class="label">Name</span>
<input type="text" name="name">
<button><span>Validate</span></button>
</form>
</body>
</html>
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';
?>
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>
I don't know if something like this has already been asked and answered, but since no matter what search query I make, nothing seems to be close to what I am looking to do. I am working on a project where the user will upload a file. Once the file has been uploaded it will show the user a success message as well as some file info. I am trying to keep this all within one page, if possible, but can't seem to get it to work. File gets uploaded, but the info does not show.
Here is something like what I am working with:
<?php
if(isset($_POST['uploadFile']) && isset($_FILES['file'])) {
move_uploaded_file($_FILES['file']['tmp_name'], "files/" . $_FILES['file']['name']);
$message = "\"" . $_FILES['file']['name'] . "\" uploaded successfully...";
}
?>
<html>
<head>
<title>Upload File</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".uploaded-file-info").hide();
$(".uploadForm").submit(function() {
$(".upload-form").hide();
$(".uploaded-file-info").show();
});
});
</script>
</head>
<body>
<div class="upload-form">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" class="uploadForm" >
<input type="file" name="file" /><br />
<input type="submit" name="uploadFile" value="Upload File" />
</form>
</div>
<div class="uploaded-file-info">
<p><?php echo $message; ?></p>
</div>
</body>
</html>
Like I said, the file gets uploaded, but the form doesn't hide and the file info ($message) doesn't show. Any suggestions?
The problem is the JQuery part :
$(".uploadForm").submit(function() {
$(".upload-form").show();
$(".uploaded-file-info").show();
});
coupled with this line :
<form method="post"
The JQuery part is saying : As soon as the form on the page is submitted, Show the information DIV.
The "Form" part just say : Submit the form.
So, when you click the button, the form is submitted and at the same time, the JQuery is executed. But then the form that you just posted needs to "refresh" the page to get the response back from the server. Basically, the JQuery you wrote display your div while you submit it. Meaning that it will work for a fraction of a second but will display an empty div because the response of the server is not there yet.
What you probably want to do is something like :
When the page loads
And there is content in the uploaded-file-info
Show the info and hide the form.
Add a Style tag with the following :
<style>
.uploaded-file-info {
display: none;
}
</style>
It will always hide the uploaded-file-info when the page loads.
Then, change your JavaScript code with :
<script>
$(document).ready(function() {
if ($('.uploaded-file-info > p').html() != "") {
$(".uploaded-file-info").show();
}
});
</script>
It says that when the page loads, if something is present inside the children of the element "uploaded-file-info", then show it. Otherwise, do nothing.
An easier solution would be to display the block, with php (so on the server side), only if a file was uploaded. No need for JQuery (client side) code.
Remove all the JQuery code and code within "<style>" tags and replace surround your "div class="uploaded-file-info" with an IF like this :
<?php if ($message != '') { ?>
<div class="uploaded-file-info">
<p><?php echo $message; ?></p>
</div>
<?php } ?>
Here's what will happen then:
you post (from your browser) the form
the server receives your post
if there is a file uploaded, it will initiate your "message" variable
and if the message variable exists, the server will put the "div uploaded-file-info" into the response. If not, everything surrounded by the "if" won't be put into the response.
your browser will receive the response and display it on screen.
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.