How to fill a TextArea with HTML code inside a form - php

So I built a site last night and now I want to add in the functionality of being able to edit the files from the web. To do a proof of concept I created:
A list box filed with file names in the DIR (Working)
A submit button that calls the selected file (Working)
A text area to display the code (Working kinda)
A save button (not hooked up yet)
I can't figure out how to fill the text area with a HTML file that contains <form> tags. As soon as I do it breaks the actual form on the page and messes up all the ui. This is just a prototype but I can only imagine the real site will have a similar issue.
Here is the relevant code for your testing purposes.
<html>
<body>
<form action="getdir.php" method="GET">
<table>
<td valign="top">
<select name="file">
<option value=""></option>
<?php
$size = 0;
foreach(glob("*.html") as $filename)
{
$size++;
}
$count = 0;
$files[size];
foreach(glob("*.html") as $filename)
{
$files[$count] = $filename;
print('<option value=');
print($filename);
print('>');
print($filename);
print('</option>');
$count++;
}
?>
</select>
<input type="submit" value="Get Code"/></td><td>
</form>
<form action="getdir.php" method="POST">
<?php
$f = $_GET['file'];
if($f!=null){
$openedFile = fopen($f,'r');
$read = fread($openedFile,filesize($f));
print('<textarea name="tb1" rows="100" cols="100">');
print(addslashes($read));
print('</textarea></td>');
fclose($openedFile);
}
else{
print('<textarea name="tb1" rows="100" cols="100"></textarea></td>');
}
?>
<td>
<input type="submit" style="height:800px" value="Save Code"/>
</td>
</form>
</body>
</html>

Try replace addslashes with htmlspecialchars

Related

How to pass a variable from one file to another in PHP through a button and without and input

I have a search functionality that it works as shown below, but I would like to be able to pass a variable from a php file to another file without having an input like I have in my search function.
This is search functionality that works:
I have the following index.html file
<html>
<body>
<p>Search</p>
<form name"form1" method="post" action="searchresults.php">
<input name="search" type="text" size="40" maxlength="50">
<input type="submit" name="submit" value="Search">
</form>
</body>
</html>
and I have my searchresults.php file
<?php
$nameofcity = $_POST['search'];
?>
Something like this is what I would like to have but not sure how to do it.
index.php file
<html>
<body>
<p>Search</p>
<?php
$variabletopass = "London";
echo '<form name"form1" method="post" action="searchresults.php">';
echo '<input type="submit" name="submit" value="Search">';
</form>
?>
</body>
</html>
my searchresults.php file where I want the $nameofcity to be equal to the value of $variabletopass, in the example = London.
<?php
$nameofcity = $_POST['search'];
?>
You could try session. For example,
// index.php
$_SESSION['variabletopass'] = "London";
//searchresults.php
echo $_SESSION['variabletopass']; // Prints London
Hope this helps.

Using forms from a tabbed index page

So I'm new to PHP and I'm having trouble getting some of my forms to function. I think it may be the way my site is set up that's causing me problems.
I have index.php which is set up as such:
<div class="pageContent">
<div id="main" style="width:1000px; margin:0 auto;">
<!-- Create the tabs -->
<div id="tabs" >
<ul>
<li>Overview</li>
<li>Ranked</li>
<li>Arena</li>
<li>Decks</li>
<li>New Game</li>
<li>Admin</li>
</ul>
<div id="tabs-0"></div>
<div id="tabs-1"></div>
<div id="tabs-2"></div>
<div id="tabs-3"></div>
<div id="tabs-4"></div>
<div id="tabs-5"></div>
</div>
<!-- Load the pages into tabs -->
<script>
$("#tabs").tabs();
$("#tabs-0").load("tab0.php");
$("#tabs-1").load("tab1.php");
$("#tabs-2").load("tab2.php");
$("#tabs-3").load("tab3.php");
$("#tabs-4").load("newGame.php");
$("#tabs-5").load("admin.php");
</script>
</div><!-- / main -->
</div><!-- / pageContent -->
This gives me a nice static page and 6 tabs of .php files to do cool stuff on.
There are a couple of forms, log in and such, in index.php which all function fine. But when I create a form on a page in a tab, it will not.
Here's an example from admin.php (#tabs-5)
<?php
if(isset($_POST['delLog'])){
unlink('log.txt');
echo 'Success';
}
if(isset($_POST['delLog'])){
unlink('error_log');
echo 'Success';
}
?>
<html>
<head>
</head>
<body>
<table width="100%" border="1">
<tr>
<td width="40%" valign="top">
</td>
<td width="30%" valign="top">
<h1>error_log</h1>
<form action="" method="post">
<input type="submit" name="delErr" id="delErr" value="Delete" />
</form>
<hr />
<?php
$lines = explode("\n", file_get_contents('error_log'));
foreach ($lines as $line){
echo $line.'<br>';
}
?>
</td>
<td width="3'0%" valign="top">
<h1>log.txt</h1>
<form action="" method="post">
<input type="submit" name="delLog" id="delLog" value="Delete" />
</form>
<hr />
<?php
$lines = explode("\n", file_get_contents('log.txt'));
foreach ($lines as $line){
echo $line.'<br>';
}
?>
</td>
</tr>
</table>
</body>
</html>
This is another, better example. A stripped down test I did yesterday for this question
Problems with $_POST
<?php
define('INCLUDE_CHECK',true);
include 'php/functions.php';
error_reporting(E_ALL);
ini_set('display_errors',1);
logThis('ready!');
if (isset($_POST['submit'])) {
logThis('success');
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="">
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
</body>
</html>
Neither of these examples work. When the submit button is pressed the site refreshes but no PHP actions are taking place. There is no error message in error_log. I don't think it's getting the call at all.
Neither of the forms return an output, one adds to the database. The other deletes log files.
Hope I've provided enough details.
What ever you are trying to do is not possible at all. You can not load PHP code to frontend, it can only be processed by the server.
The statement $("#tabs-5").load("admin.php"); is fetching only the html code (processed by the server) not the PHP script
<form action="" method="post"> will post to the current page (ie. whatever is in your address bar).
When you load the pages into index.php using ajax, that means the forms will post to index.php... I'm guessing you are expecting to fetch the form submissions in each individual php-file
So to fix it either you have to also post using ajax (and refresh the tabs with the response), or you need to change the action attribute on the forms to each individual php-file... in which case you lose your tabbed layout when a form is submitted. You can work around that as follows:
In each of the php-files you do something like this (using newGame.php as example):
<?php
if (isset($_POST)) {
//Do your form-handling stuff first
// [...]
// ...and then redirect back to index.php
header("Location: index.php");
die();
} else {
//Print your form
echo '<form action="newGame.php" method="post">';
// [...]
echo '<input type="submit" value="Create game">';
echo '</form>';
}
Note that there should be no <html>, <head>, <body> or other html in the "sub-pages" at all - just the bare content you want inside the tabs...
Now for the ajax-submit method you should also remove all "wrapping html", you should still set a target="[...]" on each form, and you should still do form handling inside each individual file. But you should not do a redirect after form handling, but just output the form again:
<?php
if (isset($_POST)) {
//Do your form-handling stuff first
// [...]
//Maybe print a little message to let the user know something happened
echo 'Form completed at ' . date('H:i:s');
}
//...then print your form no matter what
echo '<form action="newGame.php" method="post">';
// [...]
echo '<input type="submit" value="Create game">';
echo '</form>';
Then add this script to index.php - it will post all forms inside the tabs using ajax instead of refreshing the page:
<script>
my_cool_ajax_post = function(form_elm, tab_elm) {
//Actual ajax post
$.post(form_elm.target, $(form_elm).serialize(), function(data){
//Results are in, replace tab content
tab_elm.html(data);
});
};
$(document).on("submit", "#tabs form", function(){
//Store the form element
var form_elm = this;
//Find the parent tab element
var tab_elm = $(this).closest('#tabs > div');
//Really simple "loader"
tab_elm.html('<p>loading...</p>');
//Submit by ajax
my_cool_ajax_post(form_elm, tab_elm);
return false;
});
</script>
Disclaimer: Completely untested, so let me know...

Php button action event needed

How do i implement button click php when either one of the buttons is clicked? I am trying to do is, if sumbit button is clicked the php script below shows it written to a file and if view comments is hit shows comments
<html>
<body>
<form action="http://localhost/class/assignment10.php" method="post">
User Name: <input type="text" name="uname"><br>
User Comments: <textarea type ="text" name="tcomment"></textarea><br>
<input type="submit" value="Submit Comments"/>
<input type="submit" value="View Comments"/>
</form>
</body>
</html>
I have two form buttons IF submit comments is clickedthe php code should write the user’s name and comments to a text file (use fputs function to write to a file. Also you should insert a newline after each name and each comment). When user’s name and comments are successfully recorded, php should direct
On the other hand, if a user clicks on the ‘view all comments’ button, the php code should
show all users and their corresponding comments (use fgets function)
<html>
<head>
<title>PHPLesson10</title>
</head>
<body>
<?php
// Collect user name and add a line break at the end.
$customer = $_POST['uname']."\n";
// Collect comment and add a line break.
$comments = $_POST['tcomment']."\n";
$file = fopen("C:/data/feedback.txt", "a");
If ($file) // if the file open successfully
{
// Write the variables to the file.
fputs($file, $customer);
fputs($file, $comments);
fclose($file);
}
Else
{
Echo "Please try again.";
}
?>
</body>
</html>
<?php
// Open the file feedback for reading
$file = fopen("C:/data/feedback.txt", "r");
// While the end of the file has NOT reached
While (!feof($file))
{
// Print one line of file
Echo fgets($file);
Echo "<br />";
}
// close the connection
fclose($file);
?>
Your submit buttons should like below :
<input type="submit" name="submit_comment" value="Submit Comments"/>
<input type="submit" name="view_comment" value="View Comments"/>
And your php code for each buttons should like below:
<?php
if(isset($_POST['submit_comment']))
{
//the php code will be here for save comment
}
if(isset($_POST['view_comment']))
{
//the php code will be here for view comment
}
?>
use name attribute on buttons
<input type="submit" value="Submit Comments" name="btn_submit"/>
<input type="submit" value="View Comments" name="btn_view"/>
then on php you can check something like
if (isset($_POST['btn_submit']))...
or
if (isset($_POST['btn_view']))...
Best regards,
Nebojsa
For buttons, I usually use <button> tags and not <input> tags, as long as you're using <!doctype html> for HTML5.
<form action="http://localhost/class/assignment10.php" method="post" id="commentForm">
<button type="submit" name="action" value="submit" form="commentForm">
Submit Comments
</button>
<button type="submit" name="action" value="view" form="commentForm">
View Comments
</button>
</form>
Then use PHP to figure out what the user clicked like this:
<?php
$action = $_POST["action"];
if ($action == "submit") {
// submission code
}
if ($action == "view") {
// viewing code
}
else {
die("Your request could not be completed.");
}
?>
First give your submit buttons a name like so:
<input type="submit" name="button1" value="Submit Comments"/>
<input type="submit" name="button2" value="View Comments"/>
and then use this PHP:
<?php
if (isset(#$_POST['button1'])) {
//Code to execute
}
if (isset(#$_POST['button2'])) {
//Code to execute
}
?>

How to generate pdf with defined forms in php?

I'm php newbie. I'll try to explain my needs.
I would like to fill few forms in php that would be placed at appropriate locations in the document and then generate pdf file.
I'm using mPDF atm. because I need polish signs to show up correctly.
If you could help me anyhow I would appreciate that a lot. Peace.
include('mpdf/mpdf.php');
$html = file_get_contents("generated.html");
$mpdf=new mPDF('iso-8859-2');
$mpdf->allow_charset_conversion=true;
$mpdf->charset_in='ISO-8859-2';
$mpdf->WriteHTML($html);
$mpdf->Output("my_file.pdf","F");
exit;
That's for generating pdf from html, but now I would like to somehow generate the html with forms that I could define first, and then generate pdf.
So far I'm thinking about form for generating html like:
<?php
$test1 = $_POST['test1'];
$test2 = $_POST['test2'];
$test3 = $_POST['test3'];
$data = "$test1 | $test2 | $test3\n";
$fh = fopen("generated.html", "a");
fwrite($fh, $data);
fclose($fh);
print "Finished";
?>
<body>
<form name="form1" method="post" action="generate_html.php">
test1:
<input type="text" name="test1">
<br>
test2:
<input type="text" name="test2">
<br>
test3:
<select name="test3">
<option value="test3_1">test3_1</option>
<option value="test3_2">test3_2</option>
<option value="test3_3">test3_3</option>
</select>
<br>
<input type="submit" name="Submit" value="Generate">
</form>
</body>
EDIT
Thanks to #Gavin
<?php
include('mpdf/mpdf.php');
$html = file_get_contents("2.html");
$html = str_replace("%title_placeholder%", $_POST['title'], $html);
$mpdf=new mPDF('iso-8859-2');
$mpdf->allow_charset_conversion=true;
$mpdf->charset_in='ISO-8859-2';
$mpdf->WriteHTML($html);
$mpdf->Output("3.pdf","F");
?>
<body>
<form name="form1" method="post" action="1.php">
Title: <input type="text" name="title">
<br>
<input type="submit" name="Submit" value="Generate">
</form>
</body>
Works great,thanks!
You are loading the contents of a static HTML file so you could put place holders within the html...
<h1>%title_placeholder%</h1>
and then use file get_contents
$html = file_get_contents("my_file.html");
and replace the placeholders with your form data
$html = str_replace("%title_placeholder%", $_POST['title'], $html);
then write your new string to mPDF

dynamic number of file upload - PHP

I'm creating a page when user can enter how many files he want to upload then that page is rendered again with a form, after submission to another page the files are uploaded.
But i'm receiving an error [if i upload 1 file, else the problem is userfile[limit-1]]
Notice: Undefined index: userfile0 in E:\wamp\www\uploader\uploader.php on line 10
I'm pasting here my code
index.php
<html>
<?php
if (isset($_POST['num']) && !empty($_POST['num']))
{
?>
<form name="uploader" action="uploader.php" method="post">
<table>
<tr><td>Title</td><td>Select File</td><td>Description</td></tr>
<input type="text" name="number" value="<?php echo $_POST['num']; ?>"/>
<?php
for ($i=0;$i<$_POST['num'];$i++)
echo '<tr><td><input type="text" name="title'.$i.'"/></td>
<td><input type="file" id="userfile'.$i.'" name="userfile'.$i.'" size="30"></td>
<td><textarea name="desc'.$i.'" rows="4"></textarea></td></tr>';
?>
</table>
<input type="submit" name="b" value="Submit"/>
</form>
<?php
}
else
{
?>
<form name="form" method="post">
How many files to upload ? <input type="text" name="num" value="1"/>
<input type="submit" value="Submit"/>
</form>
<?php
}
?>
</html>
uploader.php
<?php
if (isset($_POST['number']))
{
for ($slot = 0; $slot < $_POST['number']; $slot++)
{
$title = $_POST["title$slot"];
$desc = $_POST["desc$slot"];
if (move_uploaded_file($_FILES["userfile$slot"]['tmp_name'],$_FILES["userfile$slot"]['name']))
echo $name.' file Uploaded !';
else
echo ' file not Uploaded ! ';
}
}
?>
Edit
SQL code removed
You need an enctype="multipart/form-data" on your <form> tag, otherwise it cannot upload files/PHP cannot read it.
You should also check the existance of a file before trying to upload it.
if (isset($_FILES['userfile'.$slot])) ...

Categories