I'm trying to make a scrolling text box in a page "front-end page" read from text file "msg.txt"
<div class="scroll-slow">
<?php echo file_get_contents('../msg.txt'); ?>
</div>
I added this code to add textbox and save button in my backend:
<html>
<head>
<title></title>
</head>
<body>
<form action="msg.txt" method="POST">
<input name="field1" type="text" />
<input type="submit" name="submit" value="Save">
</form>
</body>
</html>
<?php
if(isset($_POST['field1'])) {
$data = $_POST['field1'] . "\n";
$ret = file_put_contents('../msg.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
} else {
echo "$ret bytes written to file";
}
} else {
die('no post data to process');
}?>
Also I included txt file called "msg.txt" in my root, to make the save button save the text into the file then the scrolling msg box will read the file
My problem is:
The scrolling textbox doesn't read from the file
The save button doesn't save into the file it's just open the file!
What I'm doing wrong?
I'm sorry I know it's a mess, but I'm trying to learn.
You have to make action tag blank to execute the PHP code which is inside if statement
Change
action="msg.txt"
to
action=""
If you are doing coding on PH, you should use php file in action tag, you can not perform any action on txt file.
To append the text every time to existing file use
$txt = "This is text";
$myfile = file_put_contents('text_file.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
Here you can use jquery and ajax for get activ value of text
$.ajax({
url: "backendFile.php",
type: "post",
data: {
text: $("input[name='field1']").val()
},
success: (e) => {
$(".scroll-slow").html(e)
}
}
Your backendFile.php
<?php
if(isset($_POST['field1'])) {
$data = $_POST['field1'] . "\n";
$ret = file_put_contents('../msg.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
} else {
echo "$ret bytes written to file\n".file_get_contents("../msg.txt");
}
} else {
die('no post data to process');
}
?>
You are submitting the form data to a text file, text files won't be able to handle form data.
You need to send data to php file, in your case just removing the action from form tag would work.
Related
I am creating a php file to alter file systems and I want to make this php run in the background on a ubuntu server. The html creates a webpage but the php does not trigger at all.
I followed a youtube video to this point but I need to pass both new and old string to the php in the Data part of my query which I am unsure how to do.
HTML code
<html>
<head>
<meta charset ='utf-8'/>
<title> JQuery test </title>
<script src= "https://ajax.googleapis.cpm/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<td>Please type in the old string</td>
<input id= 'Old_String' />
<td>Please type in the new string</td>
<input id= 'New_String' />
<script>
$(document).ready(function() {
$('#New_String').change(function(){
$.ajax({
type: 'GET',
url: 'replace.php',
data: 'Old_String='+$('#Old_String').val(),
success : function(msg){
$('#results').html(msg);
}
})
});
});
</script>
<table border="0">
<div id="results' ></div>
</body>
My php code
<?php
$valid = true;
if (!empty($_GET["Old_string"])) {
$Old_string = $_GET["Old_string"];
} else {
$valid = false;
echo "Old string is Empty . Please Enter value to proceed\n";
}
if (!empty($_GET["New_string"])) {
$New_string = $_GET["New_string"];
} else {
$valid = false;
echo "New string is Empty . Please Enter value to proceed\n";
}
if ($valid) {
echo "all input correct\n";
$myfile = fopen("word.txt", "r+") or die("Unable to open file!");
if (flock($myfile, LOCK_EX)) {
$text = fread($myfile, filesize("word.txt"));
$count = 0;
$newstring = str_ireplace($Old_string, $New_string, $text, $count);
file_put_contents("word.txt", $newstring);
echo "Number of changes made = " . $count;
flock($myfile, LOCK_UN); // unlock the file
} else {
// flock() returned false, no lock obtained
print "Could not lock $filename!\n";
}
fclose($myfile);
}
?>
}
For some reason my PHP does not fire at all and no output is shown in the div results. Am I passing the values incorrectly or am I not quite doing this right? Please any suggestion would be appreciated. I am also trying to switch the event so that it triggers on a button click if you could show me how to do that I would very much appreciate it.
You had multiple errors.
These languages are case sensitive. You had different cases for the varables all over the place. So I made everything lowercase.
You can't mix the quotes. So when you start with a ' you need to end with a '.
You may need to create the word.txt file manually. The web server normally does not have permissions to create files in the web root dir.
The browser does not pay attention to new lines "\n" you need to use
Added some error reporting on the top.
index.php
<html>
<body
<head>
<meta charset ='utf-8'/>
<title> JQuery test </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<table border="0">
<tr>
<td>Old String</td>
<td align="center"><input type="text" name="old_string" size="30" id="old_string" /></td>
</tr>
<tr>
<td>New String</td>
<td align="center"><input type="text" name="new_string" size="30" id="new_string" /></td>
</tr>
<div id="results" ></div>
</table>
</form>
<script>
$(document).ready(function() {
$('#new_string').change(function(){
$.ajax({
type: 'GET',
url: 'replace.php',
data: 'old_string='+$('#old_string').val()+'&new_string='+$('#new_string').val(),
success : function(msg){
$('#results').html(msg);
}
})
});
});
</script>
</body>
</html>
replace.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$valid = true;
if (!empty($_GET['old_string']) and isset($_GET['old_string'])) {
$old_string = $_GET['old_string'];
} else {
$valid = false;
echo 'Old string is Empty . Please Enter value to proceed<br>';
}
if (!empty($_GET['new_string']) and isset($_GET['new_string'])) {
$new_string = $_GET['new_string'];
} else {
$valid = false;
echo 'New string is Empty . Please Enter value to proceed<br>';
}
if ($valid) {
echo 'all input correct<br>';
$myfile = fopen('word.txt', 'r+') or die('Unable to open file!<br>');
if (flock($myfile, LOCK_EX)) {
if(filesize('word.txt')>0){
$text = fread($myfile, filesize('word.txt'));
} else {
$text = '';
}
$count = 0;
$newstring = str_ireplace($old_string, $new_string, $text, $count);
ftruncate($myfile,0);
fwrite($myfile,$newstring,strlen($newstring));
echo "Number of changes made = $count<br>";
flock($myfile, LOCK_UN); // unlock the file
} else {
// flock() returned false, no lock obtained
print 'Could not lock $filename!<br>';
}
fclose($myfile);
}
You're referencing $_GET["Old_string"] in your PHP code but passing it by query string parameter under the Old_String key in this line.
data: 'Old_String='+$('#Old_String').val(),
use case consistently, either Old_string or Old_String in both places.
To pass both values, I'd use a simple json object instead of building a query string manually.
data: { 'Old_String': $('Old_String').val(), 'New_String': $('New_String').val() }
Here's my code:
The PHP Code
<?php
if(isset($_POST['Submit'])){
$title ='myPost.php';
echo $title;
//the data
$data = "Hey I am Aidan\n";
//open the file and choose the mode
$fh = fopen($title, "a");
fwrite($fh, $data);
//close the file
fclose($fh);
}
?>
The HTML Form Code
<form action="<?php echo $title; ?>" method="post">
<input type="submit" name="Submit" value="submit">
</form>
When form is submitted I want to load that newly created file on the next page.
use this is php to move to next page . header('Location: /somewhere');
write this code in php tags of which you displayed in html and in place of somewhere you have to write the name of your file.php ... also write this code in first line of your php document inside php tags ob_start();
After you close the file, redirect the user to it:
//close the file
fclose($fh);
// eg: /path/to/page.php. Also try $_SERVER['PHP_SELF']
$currentPath = $_SERVER['SCRIPT_NAME'];
// replace the old filename with $title
$newPath = preg_replace('#(.*/)[^/]*#','$1' . $title, $currentPath);
// Redirect browser to new file and stop.
header("Location: $newPath");
exit;
I am fairly new to PHP and am having trouble with an assignment. The assignment is to create a simple address book in PHP, and i would like my address book to display all addresses that are in it along with a submission box at the bottom to add more addresses. Currently, I can get the addresses to display, but the submission box gives me an error ") Notice: Undefined variable: addres_add in C:\wamp64\www\address_tmp\address.php on line 18"
This is my code thus far, I snagged the submission box code from another answer here on StackOverflow, but I don't know how to modify it to fit my needs.
<?php
//Open address book file and print to user
$fh = fopen("address_book.txt", "r+");
echo file_get_contents("address_book.txt");
//Perfom submit function
if(isset($_POST['Submit']))
fseek($fh, 0, SEEK_END);
fwrite($fh, "$addres_add") or die("Could not write to file");
fclose($fh);
print("Address added successfully. Updated book:<br /><br />");
echo file_get_contents("address_book.txt");
{
$var = $_POST['any_name'];
}
?>
<?php
//HTML for submission box?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="any_name">
<input type="submit" name="submit">
</form>
<p>
You never assigned the variable from the form input. You need:
$addres_add = $_POST['any_name'];
fwrite($fh, "$addres_add") or die("Could not write to file");
Also, if you're just adding to the file, you should open it in "a" mode, not "r+". Then you don't need to seek to the end, that happens automatically.
You probably should put a newline between each record of the file, so it should be:
fwrite($fh, "$addres_add\n") or die("Could not write to file");
Otherwise, all the addresses will be on the same line.
Here is a simpler version of your program.
<?php
$file_path ="address_book.txt";
// Extract the file contents as a string
$file_contents = file_get_contents($file_path);
if ($file_contents) // Check if the file opened correctly
echo($file_contents . " \n"); // Echo contents (added newline for readability)
else
echo("Error opening file. \n");
// Make sure both form fields are set
if(isset($_POST['submit']) && isset($_POST['any_name']))
{
// Append the new name (used the newline character to make it more readable)
$file_contents .= $_POST["any_name"] ."\n";
// Write the new content string to the file
file_put_contents($file_path, $file_contents);
print("Address added successfully. Updated book:<br /><br />");
echo($file_contents);
}
else
{
echo("Both form elements must be set. \n");
}
?>
//HTML for submission box?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="any_name">
<input type="submit" name="submit">
</form>
Even with no comments it should be self explanatory. I leave the proper error dealing to you.
To answer your question, the error was being caused because the $address_add variable wasn't previously declared. You also added quotes to it, making it a string.
How to make a textbox form redeem a promo code form a text file in php i cant seem to figure it out it's for my csgo gambling site i want them redeem to redeem codes that comes from a text file /promo/codes.txt and make it so they can just use any codes from the list in the text file but im to useless :(
It depends totally on the format of the file.
Example:
ZQC01
ZQR92
ZQA84
ZQD73
To check if a promotion code is in this file and remove it afterwards:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$myPromoCode = isset($_POST['promocode']) ? $_POST['promocode'] : false;
$contents = file_get_contents('/path/to/file.txt');
$promoCodes = explode("\n", $contents);
// Check if the promo code is present in the file
if ($myPromoCode && in_array($myPromoCode, $promoCodes)) {
// Find the corresponding key
$key = array_search($myPromoCode, $promoCodes);
// Remove the code
unset($promoCodes[$key]);
// Write coes back to file
$contents = implode("\n", $promoCodes);
file_put_contents('/path/to/file.txt', $contents);
} else {
die("Promotion code doesn't exist");
}
}
?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<input type="text" name="promocode" />
<button type="submit">Redeem</button>
</form>
I have a function in javascript called "dumpData" which I call from a button on an html page as **onlick="dumpData(dbControl);"* What it does is return an xml file of the settings (to an alert box right now). I want to return it to the user as a file download. Is there a way to create a button when click will open a file download box and ask the user to save or open it? (sorta of like right-clicking and save target as)...
Or can it be sent to a php file and use export();? Not sure how I would send a long string like that to php and have it simple send it back as a file download.
Dennis
I don't think you can do that with javascipt, at least not with a nice solution.
Here's how to force a download of a file in PHP:
$file = "myfile.xml";
header('Content-Type: application/xml');
header("Content-Disposition: attachment; filename='$file'");
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
Instead of using readfile to output your file, you could also directly display content using echo.
/EDIT: hell, someone was faster :).
EDITED:
just a proof of concept.. but you get the idea!
instead of
<a onlick="dumpData(dbControl); href="#">xml file</a>
you can have like this:
xml file
then like this:
// Assuming your js dumpData(dbControl); is doing the same thing,
// retrieve data from db!
$xml = mysql_query('SELECT * FROM xml WHERE id= $_GET['id'] ');
header("Content-type: text/xml");
echo $xml;
I eneded up going this route:
The HTML code
<script type="text/javascript">
$(document).ready(function() {
$("#save").click(function(e) { openDialog() } );
});
</script>
<button id="save" >Send for processing.</button>
The javascript code:
function openDialog() {
$("#addEditDialog").dialog("destroy");
$("#Name").val('');
$("#addEditDialog").dialog({
modal: true,
width: 600,
zIndex: 3999,
resizable: false,
buttons: {
"Done": function () {
var XMLname = $("#Name").val();
var XML = dumpXMLDocument(XMLname,geomInfo);
var filename = new Date().getTime();
$.get('sendTo.php?' + filename,{'XML':XML}, function() {
addListItem(XMLname, filename + ".XML");
});
$(this).dialog('close');
},
"Cancel": function () {
$("#Name").val('');
$(this).dialog('close');
//var XMLname = null;
}
}
});
}
PHP Code, I just decided to write the file out to a directory. Since I created the filename in the javascript and passed to PHP, I knew where it was and the filename, so I populated a side panel with a link to the file.
<?php
if(count($_GET)>0)
{
$keys = array_keys($_GET);
// first parameter is a timestamp so good enough for filename
$XMLFile = "./data/" . $keys[0] . ".kml";
echo $XMLFile;
$fh = fopen($XMLFile, 'w');
$XML = html_entity_decode($_GET["XML"]);
$XML = str_replace( '\"', '"', $XML );
fwrite($fh, $XML);
fclose($fh);
}
//echo "{'success':true}";
echo "XMLFile: ".$XMLFile;
?>
I don't know why, but when I send the XML to my php file it wrote out the contents withs escape charters on all qoutes and double quotes. So I had to do a str_replace to properly format the xml file. Anyone know why this happens?
POST the XML via a form to a php script that writes it back to the client with a Content-Disposition: attachment; filename=xxx.xml header.
<form name="xml_sender" action="i_return_what_i_was_posted.php" method="POST">
<input type="hidden" name="the_xml" value="" />
</form>
Then with js
function dumpData(arg) {
var parsedXML = ??? //whatever you do to get the xml
//assign it to the the_xml field of the form
document.forms["xml_sender"].the_xml.value = parsedXML;
//send it to the script
document.forms["xml_sender"].submit();
}
Can't remember if this loses the original window, if so, post to an iframe.