Writing to a text file in PHP opens a new window - php

Ok, I've got a form and i've parsed all the data and i'm ready to write it to the file. I use the following PHP code (simplified):
$file = fopen("Data.txt","a");
fwrite($file,$_GET["InputText"]);
fclose($file);
It writes just fine to the file but opens a new blank page. How do i stop it from doing that?
Thanks for the help
-Dave
EDIT: No output generated by PHP. It just writes a line of text to a file. I am using a seperate file to hold my PHP code...
< form id="fmInput" action="IM.php" onsubmit="submitText()" >
How else can i do that?
EDIT2: Heres more of my code:
<form id="fmInput" action="IM.php" onsubmit="submitText()">
<input type="text" name="fnInputText" id="iInputText">
</form>
<?php
//IM.php
$file = #fopen("IMData.txt","ab");
fwrite($file,$_GET["fnInputText"]);
fwrite($file,"<br>");
fclose($file);
?>
Now, when the user hits enter on the form, JS captures and processes (using the submitText function) then PHP writes it to a file, but then opens a blank browser...
EDIT3: I'm guessing its a blank page being loaded in the same window because it's got this in the address bar "/IM.php?fnInputText="
I dont want it to do that. I need it to write to the file without any interuption, so having PHP display anything after it runs is a deal breaker. Even if i have to have it reload the page that'd be better... It'll be marginally more time consuming as JS will have to reload the file again...
I figured out how to read from a file using JS and the XMLHttpRequest but for the life of me i cant get JS to write to the file. I'd perfer to use JS as I know very little about PHP (which is probably aparent from this post ;D)
My goal is this: page loads, JS reads in file and displays file on screen. User types in somthing, hits enter, JS adds that to screen and then [PHP or JS] writes data to file. repeat.

Perhaps you want to redirect your user to a non-blank page after you're done writing your data?
header("Location: /back-to-my-page.html");

You must be submitting the form data to another file. For example, doing an
onsubmit="write.php"
That should open a new page and write to the file

Here is the whole package!
IM.php:
<?php
// write to file if the form is submitted
if(isset($_POST['submitted'])){ # if form is submitted
$secure_input = htmlentities($_POST['input_text']); # making sure no malicious html code is submitted
file_put_contents('some_file_to_write.txt', $secure_input); #write secure_input to a file
echo '<br>completed!</br>';
}
?>
<form id="fmInput" action="IM.php" method="post">
<input type="text" name="fnInputText" id="input_text">
<input type="submit" name="submitted" value="write to file" />
</form>
if any errors comes up : you do not have permission to write! and if the file gets downloaded you do not have php installed ;)
Good Luck!

Related

How do I make an html file include itself without refreshing the page each time a button or link is clicked?

Beginner's question here :
file #1 : file1.html (one dataset)
//header, body and some other stuff
<form action="some_logic.php">
<input type="text" name="data1" placeholder="data1">
<input type="text" name="data2" placeholder="data2">
<input type="submit" value="Ok!">
</form>
//end of the html
file #2 : (I don't even know what this file should be : php? html? js?)
//usual stuff
include 'file1.html'; //OR
<!--#include file="file1.html"-->
#logic to replicate file1.html with a button
I need to have the file1's code repeated once each time the user clicks on a button (or a link or whatever) and I would like this to work without refreshing the page (or at least without questionning the server over and over and without deleting the current datas). The server uses php7.
I need this because I do not know in advance how much datasets the user will create.
It would be awesome if this could be done with javascript! (since I doubt this can be achieved with php/html only) Although I have never used js until now.
You can fetch data from server without refreshing the webpage using JavaScript Ajax. Here you can create an event listener to send a request to the server. The data can be plain text, html, json, xml or whatever you want. Just create Ajax request for events. Then update the webpage using the response data.

Get and use the user's previous form data variable across the page

The purpose is to allow user uploading files (usual uploading process) and confirm uploading by pressing on the confirmation button. Programming side: 2 folders - 1 for unconfirmed files where files get deleted periodically and 2 - confirmed folder - where files are copied from unconfirmed folder if a user presses the confirmation button.
Basically, I have a form, where a user uploads files that are stored in the folder and the path to it - in a database. And on the same page I have another button, so when the user presses it I would like to move his/her uploaded files from one directory to another (not re-uploading - coping on server).The issue is taht I should know WHICH files to deal with!
My problem is: everything seems ok, but I can't get the variable $name - that tells me the name of the file, user has uploaded. Because When I try to use it to proceed second submit button - it says variable is undefined. I need to get the variable that tells me the name of the file user has submitted so I can copy that file to another directory, but it can only be assigned (and unfornunatelly used) when procesing the form submittinf and enabled to use only inside of the processing, while I want to use it outside.
I have tried to use sessions - but this code doesnt work, same problem - it says that - 'undefined index - regex', same with COOKIES.
All the html:
<form action="videator.php"method="post" enctype="multipart/form-data">
<input class="form" type="file" name="fileToUpload" id="fileToUpload" accept="video/*" >
<input class="form" type="submit" value="Upload Image" name="submit">
</form>
<form action="love.php" method="post">
<input class="post" type="submit" value="POST" name="post" id="post"/>
</form>
videator.php:
if(isset($_POST["submit"])) {
$file = $_FILES['fileToUpload'];
$name = $file['name'];
$_COOKIE['name'] = $name;
$_SESSION['regex'] = $name;
...
}
love.php
if(isset($_POST["post"])) {
session_start();
$name = $_GET['regex'];
$from = "temp_videos/".$name;
$to = "videos/";
if (!copy($from, $to)) {
echo("<script>alert('fail')</script>");
}else {
echo("<script>alert('Success!')</script>");
}
It says also that 'The first argument to copy() function can not be a directory. I guess, that's due to the fact that my variable $name is undefined, therefore only the folder is here as the path.
Please, help. I've spent all my day on that.
(If I just use copy() function with indicating actual path and not a variable of it - everything works)
Thanx in advance.
I have a few tips that may help.
(1) At the top of each PHP file, as the first instruction, put:
<?php
if (!session_id()) session_start();
//any other PHP instructions follow.
?>
(2) Try using the excellent jQuery File Upload plugin by Ravi Kusuma. Although I generally try to code everything myself and not use plugins, this one is so well done that it's my primary goto for file uploads.
(3) Until you get this working, there is no need to put the session_start() inside an if statement. The session_start() must be the first instruction at top of each PHP page that references the $_SESSION variable.
(4) Look into AJAX instead of using <form> (for managing the file upload process). Kusuma's plugin also works great with AJAX. If you haven't used AJAX before, it may sound intimidating - but it's super simple. Copy the examples at the bottom of this post and make them work on your system. It may be the most important 15 mins you've spent in 2016. Note that the point of the linked question is that there must be a separate PHP file that receives the AJAX post.
(5) Don't forget that AJAX is a two-step process: (a) the javascript on the current page communicates with the specified PHP page; (b) the PHP page receives the data (or file upload data) via POST varibles. Therefore, be sure to check out the "SERVER SIDE" tab at top of Kusuma's Hayageek page. At the top of the SERVER SIDE page are four links to sample PHP files. Study the upload.php example.
Happy coding.

HTML form triggers php code in file, how do i get back to html?

I am collecting data in a form which calls on a php file to put the data into mysql. It works fine, but after the data gets into the database, the browser just shows a blank page and in the browser input bar is the line
http://nameofmyste.net/mfb1.php
It is as though the HTML sent me to the php code where runs fine on the server then it just gets stuck, and stays there. How do I "get back" to my html script?
The call form action command looks like:
<form class="form-horizontal" role="form" action="mfb1.php" method="post" >
The php code exists in the file mfb1.php and works fine and just terminates with the standard closing "?> " at the end.
Thanks for your help.
Sorry for the delay in getting back to the question, and very sorry for my incorrect use of the forum, I am new and learning...
I have done some work since the original question and have created a very simple AJAX example that should work fine, but it doesn't. Here is the HTML file with the js function localform. It uses a synchronous AJAX call (3rd parameter set to "false") to invoke my php code, which is below as well.
It runs fine, I see the phrase "we made it" which replaces the "replace here" text on the html page, just like it is supposed to. But, within half a second, the "we made it" goes away and the "replace here" text shows up again.
It is as though the html code were running again form the top. The address in the browser bar, after the submit now reads
http://bruwptest.netne.net/Test%20Files/ajaxtester.html?
The question mark at the end is new.
Here is the code:
ajaxtester.php:
<?php
echo "we made it";
?>
ajaxtester.html:
<!DOCTYPE HTML>
<html>
<body>
<h1>AJAX Tester</h1>
<p>Echo here from the server: <span id="text">replace here</span></p>
<form onclick="localform()">
<button type="submit" >Submit</button>
</form>
<script>
function localform() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "ajaxtester.php",false);
xhttp.send();
document.getElementById("text").innerHTML = xhttp.responseText;
}
</script>
</body>
</html>
My question is why the html page is refreshing and overwriting the "we made it" that I just wrote there from the php?
It is as though the HTML sent me to the php code
Well, yes. That's what you specified:
<form class="form-horizontal" role="form" action="mfb1.php" method="post" >
<!-- right here ----^ -->
then it just gets stuck
Well, what does mfb1.php do? What output does it generate? If it doesn't render any HTML to the browser, then no HTML is rendered to the browser.
Or if there's an error and error reporting isn't turned on, there may be no valid output to render to the browser. Turn on error reporting during debugging, check your logs, etc.
You can, within that script, output any HTML that you like. Anything outside of <?php ?> tags is just sent directly to the client, so put any HTML that you want there.
Alternatively, at the logical completion of the script you could also redirect the user to another page:
header('Location: somePage.html');
This would return a response to the user's browser indicating that it should make a new request for somePage.html.
You have to send to client a redirect location to your original HTML page; at the end of your php script, write:
header( "Location: YourHtmlFileUrlHere" );
exit;
The exit command is not mandatory, if the command is at the end of script.
Please note: The header command fails if before in page there are ANY OUTPUT

Can you read a web pages sources code and covert it to a .txt file

Im converting a PHP file to .txt file on a local host.
i am using file_get_contents at the moment to write my php file to a txt file the only problem i am having is that it is not reading in the php variables that i pull from my SQL file in this page. It renders perfectly on screen but when it writes it to a txt file all my variables are missing
So i was wondering if there was a way i could write the source code of that web page (the outcome once the page has been loaded) to a text file so it read in all the variables?
This is my SQL line which gets the CompleteDate this is in a separate sql.php file which gets called at the start of certificates.php
if (isset($_GET['CompleteDate'])) {$CompleteDate = $_GET['CompleteDate'];};
In Certificates.php I echo out the $CompleteDate which shows perfectly when i view it through my local host
<h3><div class="info">Date </div><?php echo $CompleteDate ; ?></h3>
Then you click a button to convert that page into a . txt file
<form action = "convert.php">
<input type="submit" name="submit" id="submit" value =" convert" class="pdfButton">
</form>
When you click the button it calls this code from convert.php
<?php $test = file_get_contents("http://localhost/test/Certificates.php"); file_put_contents("test.txt","$test");?>
When i check my .txt file it outputs "Date:" Then there is a blank space where the $CompletedDate variable should be
Why is it not reading in my SQL variables from my php page when it displays perfectly in my browser??
I am quite new to this so i assume it is something i am doing wrong.
The value comes from the query string:
$CompleteDate = $_GET['CompleteDate']
But when you invoke the page, you don't provide anything on the query string:
file_get_contents("http://localhost/test/Certificates.php")
So there's no value for the code to use. In order to get a value from the query string, you have to provide a value:
file_get_contents("http://localhost/test/Certificates.php?CompleteDate=someValue")

Why would a.php file open as if it were an html file, rather than execute?

I have a .php file that I'm trying to execute. It's referred to in the 'action' part of an html form.
For some reason when the form submits it opens the .php file in the browser as if it were an html page (a blank one).
The .php file doesn't have anything out of the ordinary in it, but I'm not sure it's getting to the point of executing it anyway.
My opening form tag looks like this: <form action="my_script.php" method="post">
What am I missing?...
In all likelihood your script is executing. By default, HTTP headers will be sent indicating that the script's content is HTML, hence that's how your browser will treat it. But if you don't actually send any output, it'll appear as a blank page.
If you want the form to do something but not open a new page, maybe you could use AJAX to submit the form data without leaving the page. Alternatively, you could just add at the end of the script
echo 'Finished :)';
so that you know it has gotten to the end, and presumably done something.
When you submit a form, your browser posts data to the URL specified by the action attribute, as part of the request for that page.
Your page at my_script.php should output some HTML.
If instead you see your PHP code when you view the source of this new page, then PHP is not configured to be parsed on the server.
euh... php
Use: http://www.apachefriends.org/en/index.html instead of opening a html file directly in your browser.

Categories