I am currently trying to implement a PHP page that will generate a code when a user clicks a button. The code will be generated on the fly, and then the PHP page will trigger a download file that will prompt the user to save the text file on their machine.
After reading numerous posts, I am using this bit of code which is short, concise and does exactly what I need:
{
$result = "Your code is: " . $_POST['req_code'];
header('Content-disposition: attachment; filename=code.lic');
header('Content-type: text/plain');
echo $result . "\n";
}
However, the downloaded file does not only contain the code, it also contains all the HTML from the current page. Below is just a fraction of what is included in the file:
<!DOCTYPE html>
<html lang="en-CA">
<head>
<meta charset="UTF-8" />
<title>My Account | ...
I have tried using the "exit();" function to terminate the stream but it still outputs all the HTML.
Does anyone know what I'm doing wrong here? The file should only contain the contents of $result.
Thank you in advance.
Although this is an old thread, there are search results that still direct to here. So to answer the original question (sort of) by giving a simple stand-alone example that works, here goes:
Create two files, 'index.php' and 'redirect.php'
index.php:
<?php
$head = <<<EOHEAD
<head>
<title>Download document test</title>
<meta http-equiv="Content-Type" content="txt/html; charset=utf-8" />
</head>
EOHEAD;
$body = <<<EOBODY
<body>
<form action="redirect.php" method="post" id="mainform">
<input type="submit" name="download" value="Download"/>
<input type="submit" name="cancel" value="Cancel"/>
</form>
</body>
EOBODY;
echo $head.$body;
?>
redirect.php:
<?php
if (isset($_POST['download'])) {
header('Content-disposition: attachment; filename=test.txt');
header('Content-type: text/plain');
echo "Hello World\n";
}
else {
header("location:index.php");
}
?>
You need to either a) Make a new page to download the file (without any HTML) or b) Remove all HTML from the current page. Also, you are not supposed to send any content before calling header():
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP
Reference: http://php.net/manual/en/function.header.php
You do not have to delete all HTML code from download site, but there cannot be ANY HTML code before function, that downloads your files. Put your code ad the top of the page and it should be fine
Related
I am making a simple API from PHP.
Code Snippet:
elseif ($_GET["command"]="verifyconn"){
header("Content-Type: application/json");
$data=array("response" => "success");
echo json_encode($data);
exit;
}
Whenever this is executed, I get this response on browser:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
</body>
</html>{"response":"wrong_secret"}
The whole HTML code gets printed on browser. When I remove header("Content-Type: application/json");, it gets fixed and JSON displays but in text. How can I fix it?
It doesn't get really fixed when you remove the content type header, but the HTML part will become "invisible", because the content type will fall back to the default text/html; if you check the source code of the page, you will see it's still there.
The real solution is to search for where the above HTML is printed and remove it.
I tried to host a simple website on my Mac. My goal is to make a form that everyone can enter text in, then the piece of text will be shown in the main HTML page. I encountered two problems:
I could see updates in mylog.log when I run php submit.php, but I can't when using a browser (Safari) and visiting the site itself.
Even if I managed to write to the file, I don't know how to make the HTML interact with it to display the contents.
This is the code in index.html:
<form action="submit.php" method="post" target="_self">
<input type="text" id="textform2" name="msg">
<input type="submit">
</form>
And submit.php:
<!DOCTYPE html>
<html>
<head>
<title>Processing</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php
$message = 'hi';
$file = 'mylog.log';
$handle = fopen($file, 'w');
fwrite($handle, $message);
fclose($handle);
?>
<p class="par">Our server is processing your request. You will be redirected…</p>
<script> location.replace("http://johann.local"); </script>
</body>
</html>
I put these files in Macintosh/Library/WebServer/Documents.
Sanitisation is not required since it will only be hosted on my private WiFi network.
Firstly, you need to run PHP Web Server to make your submit.php working.
Go to your directory with index.html and submit.php, and run this:
php -S localhost:5000
Then your website is available at http://localhost:5000 .
About your second question, if you want easily write into the file, you can use file_put_contents function instead of fopen/fwrite/fclose, and vice versa, you can easily read the content via file_get_contents.
This is example of usage:
<!DOCTYPE html>
<html>
<head>
<title>Processing</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php
$message = 'hi';
$file = 'mylog.log';
file_put_contents($file, $message); // save $message into $file
?>
<p class="par">Our server is processing your request. You will be redirected…</p>
<p>Contents of the log: <?php echo file_get_contents($file); ?></p>
</body>
</html>
(I removed the redirection to see the content)
With echo function combined with file_get_contents, you can print the contents of the log file into the HTML.
I used to be able to post variables to pure PHP pages, but it seems to have been broken by a server setting change with our web host, because this used to work just fine. Basically, I've set up a form to retrieve and allow the user to download a file from a secure location outside of the public folder on the server (only to authorized users). It works like this:
request_file.php
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Request File</title>
</head>
<body>
<form name="request_file" method="post" action="retrieve_file.php" enctype="multipart/form-data">
<input type="text" name="filename" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
retrieve_file.php
<?php
session_start();
header("Vary: User-Agent");
header("Pragma: public");
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=".$_POST['filename']);
readfile( "../../".$_SESSION['userid']."/".$_POST['filename'] );
?>
However, if I replace the retrieve_file.php code with simply this:
<?php
echo "<pre>";
var_dump( $_POST );
echo "</pre>";
?>
It will print out an empty array, every time. However, if I put HTML headers on retrieve_file.php, it works just fine. However, for exporting a file, this won't really work since the headers have to be sent out AFTER the page gets its post variables.
Any ideas how to work around this? Please don't berate me for pulling files this way, it actually works well for our very specific application.
Thanks!
Additional Information
PHP Version: 5.4
You need to access with the $_FILES variable, like this:
$_FILES["file"]["filename"]
Check more at http://www.w3schools.com/php/php_file_upload.asp
I am just calling a simple PHP script through a HTML form.
An error is thrown everytime : "The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must to be declared in the document or in the transfer protocol"
I have defined the encoding both in PHP as well as HTML as UTF-8 (please refer to code below). I am unable to solve this problem despite searching all over the web.
HTML code :
<head>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
<meta content="UTF-8" http-equiv="encoding"/>
<title>Test</title>
</head>
<body>
<div align="center">
<form action= "google1.php" method="get" accept-charset="UTF-8" >
Enter Your Name:
<INPUT TYPE = "text" NAME = "student"> <BR>
<!--input name="q" type="text"-->
<br/ >
<input name="btnG" type="submit" value ="test">
</form>
</div>
</body>
PHP Code
header("Content-type: text/html; charset=UTF-8");
print "<pre>";
print_r($_GET);
print "</pre>";
The result after submitting the button (along with the error) is :
"; print_r($_GET); print ""; ?>
I am using XAMPP. I tried to edit .htaccess (added : AddType 'text/html; charset=UTF-8' html) as suggested in some of the solutions over internet but that also did not help.
I found a site where there is a simple form which calls a PHP script again. http://www.tjhsst.edu/~dhyatt/superap/form1.html . When I try to submit value in the form, I get the same error.
So I thought, this could be a browser problem and I changed the default encoding of my browser to UTF-8. But this also did not help.
I am a novice in web programming and trying to learn. Appreciate if any one can help.
Thanks,
Ashutosh
It looks like you have some issue with opening/closing tags.
Ensure that you have php code wrapped with <?php and ?> in your process1.php3 (Some details: http://php.net/manual/en/language.basic-syntax.phpmode.php)
Like here:
<?php
header("Content-type: text/html; charset=UTF-8");
print "<pre>";
print_r($_GET);
print "</pre>";
?>
UPD:
After a long session of question/answer finally appeared that OP were opening file with a form using file:// protocol. Like file:///C:/xampp/htdocs/example/form.html and form were submitted to file:///C:/xampp/htdocs/example/google1.php?... As apache works with HTTP protocol only, PHP were not executed actually.
Your Code:
<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
Correct code:
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
You have forget to put slash at the end of meta-tag. You have not closed the meta tag.
Though, its not very crucial, as you have tried everything. Try this one too. It might work for you.
I'm using php to build a small form that requires passing 2 variables for processing.
I got the example off w3schools and although the info gets passed in the URL, the php form doesn't process it in any way (let alone extract it).
I'm just wondering if there might be anything wrong with my WAMP server.
<html>
<body>
welcome
Welcome <?php echo $_GET["fname"]; ?>.<br />
You are <?php echo $_GET["age"]; ?> years old!
</body>
</html>
HTML form:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:// www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<form action="welcome.php" method="get">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
Indeed as already noted by various posts, this code should work.
In my experience the php tags are output directly if they're not parsed.
Do you see anything on the page at all? You could also check the sourcecode of the page and check if you can spot anything wrong there.
Also when copying from examples on the internet, sometimes you get weird characters that interrupt the parser. Usually this results in an error (which is not the case here), there's no harm in checking though.
Try outputing something simple and see if that works:
<?php echo "Hello World"; ?>
Can't think of anything else at the moment...
This should work fine code-wise. Did you save the php file in the same directory as 'welcome.php'?
Your code seems correct. Does PHP work? Does
echo phpinfo();
work? If yes, what does
var_dump($_SERVER);
give you? Do the GET parameters appear there?
Just add <?php echo phpinfo(); ?> after that run your page for example page http://localhost/yourpage.php again, now just see whether error_reporting = E_ALL and display_errors = 1 is set or not if not then you have to configure your php.ini,
Check URL if you can view values in url and still can't able to fetch it then try var_dump($_REQUEST); and my suggestion is to try to submit form in same page because when i was fresher i write both codes in same page but action page is different so i was confused why its not working
This script should work as far as I can see. What is your WAMP-setup?
Try to upload the script on a free server that uses php and run it there.