Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to echo "success" on the same page the form is on if it uploaded correctly, but Im new to php so dont know how its done?
index.php
<form action="upload" method="POST">
<input name="field1" placeholder="First name" type="text" />
<input type="submit" name="submit" value="Submit">
upload.php
$content = "".$_POST["field1"];
$fp = fopen("upload/test.txt","wb");
fwrite($fp,$content);
fclose($fp);
I also need it to redirect back to same page index.php
You cannot do this when using a regular form post. When a form is posted the user navigates away from the current page and is given a new page by the server. The one they were looking at no longer exists, so you cannot inject a message.
If you want to perform the task as you describe you will need to use an AJAX-based file uploader.
See:https://stackoverflow.com/search?q=php+jquery+ajax+upload
If you need to echo on the same page and you don't want to use ajax there are 2 possible solution.
a) Use a GET parameter on upload script, and thread this on the index.php (As #Brad also said at comment)
upload.php
$content = "".$_POST["field1"];
$fp = fopen("upload/test.txt","wb");
fwrite($fp,$content);
fclose($fp);
header('Location: /index.php?m=success');
index.php
//Check for message parameter
if (isset($_GET['m']{0}) && $_GET['m'] === 'success')
echo 'Form uploaded successfully';
//Display the upload form
echo '<form action="upload" method="POST">' .
'<input name="field1" placeholder="First name" type="text" />' .
'<input type="submit" name="submit" value="Submit">';
b) Within the same script
index.php
//Check if form is submitted
if (isset($_POST['field1']))
{
$content = "".$_POST["field1"];
$fp = fopen("upload/test.txt","wb");
fwrite($fp,$content);
fclose($fp);
//Do anything else
}
//Display form. Use index.php as the action, instead of upload
echo '<form action="/index.php" method="POST">' .
'<input name="field1" placeholder="First name" type="text" />' .
'<input type="submit" name="submit" value="Submit">';
Update after comment:
When you open a file with the fopen function, you define 2 arguments. The first argument is the filename, and the second argument is the flags.
You need the 'a' (append) flag, instead of 'w' (write):
'a' Open for writing only; place the file pointer at the end of the
file. If the file does not exist, attempt to create it.
'w' Open for writing only; place the file pointer at the beginning
of the file and truncate the file to zero length. If the file does
not exist, attempt to create it.
Take a look here
$content = "".$_POST["field1"];
$fp = fopen("upload/test.txt","wb");
if (fwrite($fp,$content))
{
echo "Successful upload!";
} else {
echo "Not successful!";
};
fclose($fp);
You will need to use some javascript along with php to get what you are looking for.
ajax-file-upload-with-php-and-jquery
I haven't tried it, but at first glance looks like a great place to start.
Try the following code
if (! move_uploaded_file ( $_FILES ['attachment'] ['tmp_name'], UPLOAD_DIR )) {
//handle if file not uploaded
header("Location:index.php?m=fail");
}else{
header("Location:index.php?m=success");
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
Improve this question
I need someone to help me with php guides on how i can echo every user input to the screen...
Example:
Html
<form action"bot.php" method="POST">
<input type="text" name="name">
<input type="submit" name="submit" value="submit">
</form>
Php Code
<?php
//request name from form
$username = $_REQUEST['username'];
//create function
function msg()
{
$username = $_POST['username'];
echo "$username";
echo "\r\n";
}
//echo input to screen
if (isset($_POST['submit']))
{
msg();
}
If I click submit button it will display my input text to the screen, that's fine, If I input another username click on submit button again to display under my previous output to screen...Instead PHP overide my previous output with new username submitted..
Will be glad if anyone can help
This example uses a session. You don't need anything external other than a working PHP installation. I've added comments in the code, but the basic flow is,
start a session
read the names from the session. If this is a new session, default the names to an empty array
read the submitted name
append the submitted name to the existing names
write the existing names to the session
<form action="bot.php" method="POST">
<input type="text" name="name">
<input type="submit" name="submit" value="submit">
</form>
<?php
// Always start the session
session_start();
// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Read the existing names from the session. Default to an empty array if none are set
$existingNames = $_SESSION['names'] ?? [];
// Grab the submitted name
$name = $_POST['name'];
// Add it to the end of the list
$existingNames[] = $name;
// Overwrite the entire session's list
$_SESSION['names'] = $existingNames;
// Output something interesting
echo 'Welcome ' . $name;
echo '<br>';
echo 'There are ' . count($existingNames) . 'name(s).';
echo '<br>';
foreach ($existingNames as $storedName) {
echo $storedName;
echo '<br>';
}
}
What is the most elegant and efficient way of search a string against injected script file in PHP.
The flow:
i want make form search when user input strings & click search, data searched save on txt/php file with auto create new file based on month & year ex: -201601.php / txt
then data was saved on safety query with serial key on each string
then if data on -201601.php contents have more than 1000+ query, the data old was deleted automatic
then how showing 50 strings based on random strings on -201601.php
then in -201601.php there are no double string or same string
If you have a solution for my issue and want to post an answer, please add some explanation so that I can understand why/how you did it so that I won't come asking the same questions all over again. Thanks
Im search & create file that i want making it with my plot imagination. Here is what I have so far manually :
<center>
<form action="./cari.php?q=" method="GET">
<input type="text" name="q" value="" placeholder=" Cari .." style="cursor: pointer;width:69%"/>
<input type="submit" value="Search"/>
</form>
</center><?php
if(isset($_GET['q'])) {
$data = ''.$_GET['q']."<br>\n";
$ret = file_put_contents('rcnt.php', htmlspecialchars($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');}
?>
Im stuck searching with cant find related tutorial & hope find answer :(
Please your help, i want learn more with this, i use XAMPP 5.6
First step, the ?q= var the browser will create, you don`t need to set this on your form action.
<form method="get">
<input type="text" name="q" placeholder="search">
</form>
The PHP code will be:
<?php
if(!empty($_GET["q"]))
{
$file = fopen(date("Ym") . ".txt","a+");
fwrite($file, $_GET["q"] . "\r\n"); //\r\n jump the line
flose($file);
}
?>
If today is the 1st search of the 1st day of the month, the file will not exists, then, the PHP will create it, otherwise, will open and write on it.
Hope it could help you.
We could try this way:
<?php
$theFile = date("Ym") . ".txt";
$myFile = file($theFile);
for($i = 0; $i < 100; $i++){ //deleting the first 100 lines
unset($myFile[$i]);
}
//rewriting the file without the 100st first lines
file_put_contents($theFile, implode($myFile));
?>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am very new to php (3.5 weeks in) and I am working on a project for a php course I am taking. I have been working on this php file for several days and I am at my breaking point. Here is what I am trying to achieve:
"Create a document with a form that registers bowlers for a bowling tournament. Use a single text file that saves information for each bowler on a separate line. Include the bowler’s name, age, and aver- age, separated by commas. Ensure that the Projects directory has read and write permissions for everyone."
I have successfully created the form and I think I have my variables set up correctly. I am thinking I will need to use an array to store each of the variables based on user input. I have tried writing this and I break everything. Here is what I have so far with my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>List of Bowlers</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
<h1 style="text-transform: uppercase; color: #666666; font-weight: 400; font-size: 1.5em; letter-spacing: 5px;">Register for the upcoming bowling tournament</h1>
<?php
if (isset($_POST['first_name']) && isset($_POST['last_
name'])) {
$BowlerFirstName = addslashes($_POST['first_name']);
$BowlerLastName = addslashes($_POST['last_name']);
$BowlerAge = addslashes($_POST['bowler_age']);
$BowlerAverage = addslashes($_POST['bowler_average']);
$NewBowler = "$BowlerLastName, $BowlerFirstName, $BowlerAge, $BowlerAverage\r\n";
$BowlersFile = "bowlers.txt";
if (file_put_contents($BowlersFile, $NewBowler,
FILE_APPEND) > 0)
echo "<p>" . stripslashes($_POST['first_name']) .
" " . stripslashes($_POST['last_name']) .
" has been registered for the upcoming bowling tournament.</p>\n";
else
echo "<p>An error has occurred in your registration. Please try again.</p>";
} else
echo "<p>To successfully enter the upcoming bowling tournament, enter
your first and last name and click the Register
button.</p>";
?>
<form action="bowling_names.php" method="POST">
<p>First Name: <input type="text" name="first_name"
size="30" /></p>
<p>Last Name: <input type="text" name="last_name"
size="30" /></p>
<p>Age: <input type="text" name="bowler_age"
size="30" /></p>
<p>Average: <input type="text" name="bowler_average"
size="30" /></p>
<p><input type="submit" value="Register" /></p>
</form>
<?php
$BowlersList = readfile("bowlers.txt");
echo $BowlersList;
?>
</body>
</html>
I am really attempting to learn the concepts here. If you are willing to provide assistance, please explain where I am going wrong too. I greatly appreciate any help!
There is one issue here with this piece of code:
if (isset($_POST['first_name']) && isset($_POST['last_
name'])) {
and that broken POST array for your "last_name" will prevent it from writing to your file.
It needs to be together:
if (isset($_POST['first_name']) && isset($_POST['last_name'])) {
Then, make sure the text file exists for it, otherwise you'd of gotten a warning such as: (and if your system is setup to catch/display errors, warnings, notices)
Warning: readfile(bowlers.txt): failed to open stream: No such file or directory...
Also make sure it has proper permissions to write to it (if it does already exist).
Usually, 644 is enough. As a last resort, you can use 777 but that isn't a safe setting to use.
The folder itself also requires proper permissions to write to. 755 is the recommended setting.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Plus right now, your file's content will echo in a single line.
If you want them on seperate lines, you can use the following:
$file = fopen("bowlers.txt", "r");
$i = 0;
while (!feof($file)) {
$lines[] = fgets($file);
}
fclose($file);
foreach (lines as $x){
echo $x.'<br/>';
}
There are a few things I can point out:
1) You can't have a line break on this line:
if (isset($_POST['first_name']) && isset($_POST['last_
name'])) {
Don't know if your original code has it, or only the one posted here. If it does, remove it so it reads:
if (isset($_POST['first_name']) && isset($_POST['last_name'])) {
2) The function readfile() outputs the file contents directly to the output buffer, it doesn't return its contents, it returns the number of bytes read. So, to read the entire file to a variable you would use file_put_contents() instead.
3) I suppose you want $BowlersList to be an Array. To achieve that, you need to read the file line by line, then use explode() to split each line into an array. Something like this:
$fileName = "bowlers.txt";
$BowlersList = array();
if (file_exists($fileName)) {
$file = fopen($fileName, "r");
while(!feof($file)){
$line = fgets($file);
if ($line != "") {
$BowlersList[] = explode(", ", $line);
}
}
fclose($file);
} else {
echo "Bowlers file doesn't exist.";
}
echo "<pre>";print_r($BowlersList);echo "</pre>";
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
So I have a Form with Check Boxes and When I submit the form I want the values of the boxes that are selected to be sent to a text file?
Question: How do I know what boxes are selected and then retrieve those values?
this is my form, it is all automated once someone selects a value from a drop down box
echo '<form action="test.php" method="post">'
sqlCheckbox();
echo '<input type="submit" value="save to text file" name="Save To Text File"'
echo '</form>
sqlCheckbox() does this for each result
echo '<input type="checkbox" name="check[]" value="SQL_QUERY">SQL_QUERY <br>'
I found the solution, this is what i fixed/did.
change 1: changed my checkbox name to an array ([] at the end of name)
change 2: once the submit is clicked it goes to my test.php page
here is my other page code
<?php
echo "saved to file";
$array = $_POST['check'];
information = "";//Justin for the variable Idea
foreach ($array $value) {//turns out only the checked checked boxes get submitted
$information .= $value . "<br>";
}
$file = "test.txt" //Flo draven had this idea
file_put_contents($file, $information, FILE_APPEND | LOCK_EX);
?>
this saves the values that were selected and sends them to the test.txt file, so I now have my sql queries in a text file
<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>
instead of "Hello World" , take the contents of your checkboxes.
you can of course define a variable with the path to any file you want to put the contents into.
a better option probably would be :
<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>
Check out using fopen and fclose on the Php Manual. That opens a file, then you will be able to send the data to it and save it.
Ok, so I have a form that takes a username and a code. This is then passed to php for processing. I am not super php saavy, so I want to be able to take a specific portion of the out put and write it to a text file, this form would be used over and over, and I want the text to be appended to the file. As you can see from the output I'm looking to capture, it's basically writing to some code that will be used for usernames in a css. So here is what I have...
The HTML Form
<html><body>
<h4>Codes Form</h4>
<form action="codes.php" method="post">
Username: <input name="Username" type="text" />
Usercode: <input name="Usercode" type="text" />
<input type="submit" value="Post It!" />
</form>
</body></html>
The PHP
--><html><body>
<?php
$Usercode = $_POST['Usercode'];
$Username = $_POST['Username'];
echo "You have recorded the following in our system ". $Username . " " . $Usercode . ".<br />";
echo "Thanks for contributing!";
echo .author[href$="/$Username"]:after {
echo content: "($Usercode)"
echo }
?>
</body></html>
All that I would like to be written to the text file would be this portion..
--> .author[href$="/$Username"]:after {
content: "($Usercode)"
}
Basically, the text file would have line after line of that exact same code, but with different usernames and usercodes. Hopefully, the variable $Usercode and $Username can also be captured and written into the output in the manner that I have it written. I'm just baffled by output buffering in php and clean and flush etc, and fwrite doesn't seem to be able to write without wiping a file clean each time it writes to it. I may be wrong of course. Anyone care to help?
Try this:
<?php
$output = "--> .author[href=$Username]:after { \n"
."content: ($Usercode)\n"
."}";
$fp = fopen($file, 'a');
fwrite($fp, $output);
fwrite($fp, "\n");
fclose($fp);
?>
The flag a will open already a text file and place the pointer to the end of file, so this will not overwrite your already file, more information in fopen.
You can use the function file_put_contents($file, $data, FILE_APPEND); where $file is the path of the file you are writing to, data is the whatever value you are writing to the file. This assumes you are using php5. If not, you will have to create a handle with fopen, write to the file with fwrite and end with fclose to close the file pointed to in your fopen handle.