Create file PHP file on form submit and frwite to it - php

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;

Related

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>

Submit email form to .txt file won't work

I have made a script with a form which is supposed to submit a persons email to a .txt file, only problem is that nothing happends to the .txt file, it is kept blank when the function is called. Both the html file and the php file is kept in the same folder and the .txt file is named formdata.txt .
Html code:
<form name="newsletter-form" action="process-form-data.php" method="post" id="newsletter-form">
<input type="email" name="newsletter-email" id="newsletter-email" class="form-control" placeholder="Enter Your Email" data-validate="validate(required, email)" />
<input type="submit" id="newsletter-submit" class="btn" value="Notify Me" />
</form>
Php code named process-form-data.php:
<?php
// Receive form Post data and Saving it in variables
$email = $_POST['newsletter-email'];
// Write the name of text file where data will be store
$filename = "formdata.txt";
// Marge all the variables with text in a single variable.
$f_data= '
Email : '.$email.'
=========================
';
echo 'Form data has been saved to '.$filename.' <br>
Click here to read ';
$file = fopen($filename, "a");
fwrite($file,$f_data);
fclose($file);
?>
Your code works for me.
Here's a variation using file_put_contents:
// Receive form Post data and Saving it in variables
$email = $_POST['newsletter-email'];
//$email = 'myhappymail#unhappy.com';
// Write the name of text file where data will be store
$filename = "formdata.txt";
// Marge all the variables with text in a single variable.
$f_data= '
Email2! : '.$email.'
=========================
';
file_put_contents( $filename, $f_data, FILE_APPEND | LOCK_EX );
// $file = fopen($filename, "a");
// fwrite($file,$f_data);
// fclose($file);
echo 'Form data has been saved to '.$filename.' <br>
Click here to read ';
Do a:
var_dump( $_POST );
die;
at the top of your script. I'm thinking you're missing your POST data.

PHP link to include header

I have php reading a text file that contains all the names of images in a directory, it then strips the file extension and displays the file name without the .jpg extension as a link to let the user click on then name, what I am looking for is a easy way to have the link that is clicked be transferred to a variable or find a easier solution so the link once it is clicks opens a page that contains the default header and the image they selected without making hundreds of HTML files for each image in the directory.
my code is below I am a newbie at PHP so forgive my lack of knowledge.
thank you in advance. also I would like a apple device to read this so I want to say away from java script.
<html>
<head>
<title>Pictures</title>
</head>
<body>
<p>
<?php
// create an array to set page-level variables
$page = array();
$page['title'] = ' PHP';
/* once the file is imported, the variables set above will become available to it */
// include the page header
include('header.php');
?>
<center>
<?php
// loads page links
$x="0";
// readfile
// set file to read
$file = '\filelist.txt' or die('Could not open file!');
// read file into array
$data = file($file) or die('Could not read file!');
// loop through array and print each line
foreach ($data as $line) {
$page[$x]=$line;
$x++;
}
$x--;
for ($i = 0; $i <= $x; $i++)
{
$str=strlen($page[$i]);
$str=bcsub($str,6);
$strr=substr($page[$i],0,$str);
$link[$i]= "<a href=".$page[$i]."jpg>".$strr."</a>";
echo "<td>".$link[$i]."<br/";
}
?>
</P></center>
<?php
// include the page footer
include('/footer.php');
?>
</body>
</html>
add the filename to the url that you want to use as a landing page, and catch it using $_GET to build the link.
<a href='landingpage.php?file=<?php echo $filename; ?>'><?php echo $filename; ?></a>
Then for the image link on the landing page
<img src='path/to/file/<?php echo $_GET['file'] ?>.jpg' />

PHP writing a text file in the begin

So we are making in the class a sort of log. There is a input box and a button. Everytime the button is pressed, PHP will write on the text file and prints the current log. Now the text appears on the bottom, and we need to have the text appear on the top. Now how would we do that?
We tried doing this with alot of my classmates but it all resulted in weird behavours. (Like text is printed more then once, etc)
Thanks alot!
EDIT: Sorry, here is the code:
<html lang="en">
<head>
<title>php script</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form name="orderform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="text"/>
<input type="submit" value="Submit" />
<?php
//Basic variables
echo("<br/>");
$myFile = "log.txt";
$logfile = fopen($myFile,'r+');
$theData = fread($logfile,filesize($myFile));
//Cookie stuff so the username is rememberd.
$username = $_COOKIE['gebruikerscookie'];;
if(isset($_POST['username'])){
$gebruiker = $_POST['username'];
if($_COOKIE['gebruikerscookie'] == $gebruiker){
$username = $_COOKIE['gebruikerscookie'];
echo("Welcome back");
}else{
setcookie("gebruikerscookie", $gebruiker);
$username = $_COOKIE['gebruikerscookie'];
echo("Welcome dude!");
}
}
//Checks if theres something inside
if(isset($_POST['text'])){
$message = "<br/>". $username ." : " . $_POST['text'];
fwrite($logfile, $message ,strlen($message));
}
echo($theData);
?>
</form>
</body>
Check the fopen manual on modes: http://www.php.net/manual/en/function.fopen.php
Try 'r+' Open for reading and writing; place the file pointer at the beginning of the file.
Altough without any code this is hard to answer.
<?php
$contentToWrite = "Put your log content here \n";
$contentToWrite .= file_get_contents('filename.log');
file_put_contents('filename.log', $file_data);
?>
This will add the previous content of your file after your cureent content and write on your file.
Please reply if you have any doubt.
you're just missing the
fclose();
I assume, since not closing a filehandle can cause a lot of strange errors like this.
So
$myFile = "log.txt";
$logfile = fopen($myFile,'r+');
........
//Checks if theres something inside
if(isset($_POST['text'])){
$message = "<br/>". $username ." : " . $_POST['text'];
fwrite($logfile, $message ,strlen($message));
}
fclose($logfile); // close it outside the if-condition!
echo($theData);
should do the trick
$log = file('log.txt');
krsort($log);
foreach($log as $line) echo "$line<br>\n";

Categories