PHP - Write selected checkboxes to a text file - php

What I want to do is write a bunch of songs that a user selects from a checkbox list to a text file. The songs are listed in a text file, which is then opened and has its values stored into an array, and that array is used to make the checkbox list. This is what I have so far.
<html>
<h1>Welcome to Zmzon. Select songs below to add to your library.</h1>
<?php
var_dump($_POST);
/*Write song selections to myLibrary.txt file.*/
if(isset($_POST['songList'])){
$addSongs = $_POST['songList'];
$handle = fopen('myLibrary.txt', 'a');
foreach($addSongs as $song){
fwrite($handle, $song."\n");
}
fclose($handle);
}
?>
<form action="zmzon.php" method="POST">
<?php
/*Add contents of zmzonSongs.txt to array.*/
$songList = explode("\n", file_get_contents('zmzonSongs.txt'));
foreach($songList as $songs){
echo "<br/><input type='checkbox' name='songList[]' value='$songs' />$songs<br>";
}
?>
<input type="submit">
</form>
To zTunes
</html>
I've looked around everywhere and I'm still struggling with this.

Do the following in the zmzon.php file
<?php
if(isset($_POST['songList'])){
$listOfSongs = $_POST['songList'];
$fp = fopen('myLibrary.txt', 'w');
foreach ($listOfSongs as $song) {
fwrite($fp, $song.'\n');
}
fclose($fp);
}
?>
The above process is used to receive the song list and store it in file 'myLibrary.txt'.
you can include the above part in your existing zmzon.php file

Related

Create file PHP file on form submit and frwite to it

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;

PHP: "Submit" box

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 promocode form a text file in php?

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>

Can't perform simple array search from array

I have a program that is failing because it's not finding the $post in the search of the array, so it's continuing to add each time. I have used the other suggested method of using a foreach loop, with strpos, such as:
if (strpos($data, $posts) !== false), and this will work find the $post, but it will also find the rest and run against everything in the data/array. hence why I would just like it to search the array, if it's not there add it, if it is, just say it's there or checking in... I've spent 3 days using in_array, array_search, etc, now I'm asking for help...
<html>
<body>
<?php
$post = $_POST['name'];
$data = file("data.txt");
if (in_array($post, $data)) {
echo "$post is checking in...";
}
else {
echo "Adding to $data...";
$data = fopen("data.txt", "a+");
fwrite($data, $post.PHP_EOL);
fclose($data);
}
$data = file("data.txt");
foreach ($data as $d) {
echo $d;
}
?>
</body>
</html>
tclient.html
<html>
<body>
<form action="test4.php" method="POST">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
data.txt
Names
John
Doe
The value in $post probably doesn't have a new line at the end. You can specify not to include new lines when you use file().
file("data.txt", FILE_IGNORE_NEW_LINES);

PHP replacing 'editable' areas in html files

I'm working on a tool to replace tagged areas in a html document. I've had a look at a few php template systems, but they are not really what I am looking for, so here is what I am after as the "engine" of the system. The template itself has no php and I'm searching the file for the keyword 'editable' to set the areas that are updatable. I don't want to use a database to store anything, instead read everything from the html file itself.
It still has a few areas to fix, but most importantly, I need the part where it iterates over the array of 'editable' regions and updates the template file.
Here is test.html (template file for testing purposes):
<html>
<font class="editable">
This is editable section 1
</font>
<br><br><hr><br>
<font class="editable">
This is editable section 2
</font>
</html>
I'd like to be able the update the 'editable' sections via a set of form textareas. This still needs a bit of work, but here is as far as I've got:
<?php
function g($string,$start,$end){
preg_match_all('/' . preg_quote($start, '/') . '(.*?)'. preg_quote($end, '/').'/i', $string, $m);
$out = array();
foreach($m[1] as $key => $value){
$type = explode('::',$value);
if(sizeof($type)>1){
if(!is_array($out[$type[0]]))
$out[$type[0]] = array();
$out[$type[0]][] = $type[1];
} else {
$out[] = $value;
}
}
return $out;
};
// GET FILES IN DIR
$directory="Templates/";
// create a handler to the directory
$dirhandler = opendir($directory);
// read all the files from directory
$i=0;
while ($file = readdir($dirhandler)) {
// if $file isn't this directory or its parent
//add to the $files array
if ($file != '.' && $file != '..')
{
$files[$i]=$file;
//echo $files[$i]."<br>";
$i++;
}
};
//echo $files[0];
?>
<div style="float:left; width:300px; height:100%; background-color:#252525; color:#cccccc;">
<form method="post" id="Form">
Choose a template:
<select>
<?php
// Dropdown of files in directory
foreach ($files as $file) {
echo "<option>".$file."</option>"; // do somemething to make this $file on selection. Refresh page and populate fields below with the editable areas of the $file html
};
?>
</select>
<br>
<hr>
Update these editable areas:<br>
<?php
$file = 'test.html'; // make this fed from form dropdown (list of files in $folder directory)
$html = file_get_contents($file);
$start = 'class="editable">';
$end = '<';
$oldText = g($html,$start,$end);
$i = 0;
foreach($oldText as $value){
echo '<textarea value="" style="width: 60px; height:20px;">'.$oldText[$i].'</textarea>'; // create a <textarea> that will update the editable area with changes
// something here
$i++;
};
// On submit, update all $oldText values in test.html with new values.
?>
<br><hr>
<input type="submit" name="save" value="Save"/>
</div>
<div style="float:left; width:300px;">
<?php include $file; // preview the file from dropdown. The editable areas should update when <textareas> are updated ?>
</div>
<div style="clear:both;"></div>
I know this answer is a little more involved, but I'd really appreciate any help.
Not sure if i correctly understand what you want to achieve. But it seems I would do that in jquery.
You can get all html elements that has the "editable" class like this :
$(".editable")
You can iterate on them with :
$(".editable").each(function(index){
alert($(this).text()); // or .html()
// etc... do your stuff
});
If you have all your data in a php array. You just need to pass it to the client using json. Use php print inside a javascript tag.
<?php
print "var phparray = " . json_encode($myphparray);
?>
I think it would be better to put the work on the client side (javascript). It will lower the server work load (PHP).
But as I said, I don't think I've grasped everything you wanted to achive.

Categories