PHP script doesn't save text files on the server - php

This is the PHP script I wrote in a folder of my server:
<?php
$answer = $_POST['ans'];
if ($answer == "yes.") {
$testo = "qwe\r\n";
$documento ="/other/yes.txt";
$identificatore = fopen($documento, "a");
fwrite($identificatore, $testo) ;
}
else {
$testo = "qwe\r\n";
$documento ="/other/no.txt";
$identificatore = fopen($documento, "a");
fwrite($identificatore, $testo) ;
}
fclose($identificatore);
header('http://mk7vrlist.altervista.org/other/poll.html');
?>
This code takes the answer from a radiogroup and if the answer is Yes, it makes a file called yes.txt. Else it makes a file called no.txt. This is the image.
This is the HTML code:
<form name="mainform" action="poll.php" method="POST">
<br />
<input type="radio" name="yes" value="yes">Yes, I like it.<br>
<br />
<input type="radio" name="yes" value="no" onclick="apri();">No, I want the old layout.
</fieldset>
//other code...
<input type="submit" value="Send" />
</td>
</table>
</form>
When I click the "Send" button, the script doesn't save anything on the server. Do you know why?

One problem is you are using $_POST['ans'] but your actual radio button is called 'yes'.
Also there's a stray closing fieldset tag in your form.

First both your radio buttons should be called name="ans" and not name="yes"
Your if ($answer == "yes.") should not have a dot in it.
And your header is not properly formatted:
header('http://mk7vrlist.altervista.org/other/poll.html');
should read as:
header('Location: http://mk7vrlist.altervista.org/other/poll.html');
More on headers on PHP.net: http://php.net/manual/en/function.header.php
This:
<input type="radio" name="yes" value="no" onclick="apri();">
onclick="apri(); does not belong in there. If you're going to use this, would be used in conjunction with a submit button.
This $testo = "qwe\r\n"; may need to be reformatted as $testo = "qwe" . "\n"; Linux and Windows react differently using \r
HTML form (reformatted)
<form name="mainform" action="poll.php" method="POST">
<br />
<input type="radio" name="ans" value="yes">Yes, I like it.<br>
<br />
<input type="radio" name="ans" value="no">No, I want the old layout.
</fieldset>
<input type="submit" value="Send" />
</td>
</table>
</form>
PHP handler
<?php
$answer = $_POST['ans'];
if ($answer == "yes") {
$testo = "YES\n";
$documento ="yes.txt";
$identificatore = fopen($documento, "a");
fwrite($identificatore, $testo) ;
}
else {
$testo = "NO\n";
$documento ="no.txt";
$identificatore = fopen($documento, "a");
fwrite($identificatore, $testo) ;
}
fclose($identificatore);
header('Location: http://mk7vrlist.altervista.org/other/poll.html');
// echo "ok done";
?>
EDIT (optional as a counter method)
You may also want to use your answers as a counter instead of appending data which will eventually could grow very large.
NOTE: You must first create two files with the number 0 (zero) inside them.
yes_count.txt and no_count.txt
Here is a tested example of such a way:
<?php
$answer = $_POST['ans'];
if ($answer == "yes") {
$fr_yes = fopen("yes_count.txt", "r");
$text_yes = fread($fr_yes, filesize("yes_count.txt"));
$fw = fopen("yes_count.txt", "w");
$text_yes++;
fwrite($fw, $text_yes);
// will echo the counter but you can use header to redirect after
echo $text_yes;
// header('Location: http://mk7vrlist.altervista.org/other/poll.html');
}
else {
$fr_no = fopen("no_count.txt", "r");
$text_no = fread($fr_no, filesize("no_count.txt"));
$fw = fopen("no_count.txt", "w");
$text_no++;
fwrite($fw, $text_no);
// will echo the counter but you can use header to redirect after
echo $text_no;
// header('Location: http://mk7vrlist.altervista.org/other/poll.html');
}
?>

For debugging purposes, you should use a die statement when trying to fopen.
$fh = fopen($documento, 'a') or die('Could not append to file');
and if error reporting is on, you can always use error_get_last() to get a more detailed description of what's failing.

you are trying to write in / (root directory)
php user have permissions over the folder?
try this:
/project_folder
-poll.php
-other (create other folder with write permissions).
poll.php
<?php
$base = __DIR__; //if your php version dont work __DIR__ try: dirname(__FILE__);
if ($answer == "yes.") {
$testo = "qwe\r\n";
$documento =$base."/other/yes.txt";
$identificatore = fopen($documento, "a");
fwrite($identificatore, $testo) ;
}
else {
$testo = "qwe\r\n";
$documento =$base."/other/no.txt";
$identificatore = fopen($documento, "a");
fwrite($identificatore, $testo) ;
}
fclose($identificatore);
header('http://mk7vrlist.altervista.org/other/poll.html');

Related

Submit form data and go to next page on one click

Right now I have code that submits form data and gets put into a text file and then after I click a button to go to the next page. I want to be able to submit the form data and go to the next page on the same click. I'm using PHP and HTML right now. Is there anyway to successfully do this?? I tried an onclick like I have for my next button but it doesn't seem to work with the input type function.
<h2>Please enter your name.</h2>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
First Name: <input type="text" name="fName">
<br><br>
Middle Initial: <input type="text" name="mInitial">
<br><br>
Last Name: <input type="text" name="lName">
<br><br>
<input type="submit" name="submit" value="Submit">
<button type="button" name="submit" value="Submit"
onclick="location.href='county.php'">Next</button>
</form>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['submit']))
{
replace();
}
function replace() {
$myFile = "freewill.doc";
$fh = fopen($myFile, 'a') or die("can't open file");
$fName = $_POST["fName"];
$mInitial = $_POST["mInitial"];
$lName = $_POST["lName"];
$placeholders = array('fin', 'min', 'lana');
$namevals = array($fName,$mInitial,$lName);
$path_to_file = 'freewill.doc';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace($placeholders,$namevals,$file_contents);
file_put_contents($path_to_file,$file_contents);
fclose($fh);
}
?>
Change below line
<button type="button" name="submit" value="Submit"
onclick="location.href='county.php'">Next</button>
to
<input type="submit" name="submitform" value="Submit">Next</button>
and change PHP code to this
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['submitform']))
{
$myFile = "freewill.doc";
$fh = fopen($myFile, 'a') or die("can't open file");
$fName = $_POST["fName"];
$mInitial = $_POST["mInitial"];
$lName = $_POST["lName"];
$placeholders = array('fin', 'min', 'lana');
$namevals = array($fName,$mInitial,$lName);
$path_to_file = 'freewill.doc';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace($placeholders,$namevals,$file_contents);
file_put_contents($path_to_file,$file_contents);
fclose($fh);
header('Location: county.php');
}
Try setting an onSubmit method for your form instead.

having issue with my php code

displaying variable content is not working
here's my php code with variable name of $schanName
if($_POST['thisfolder'] == 'default') {
$schanName = 'Please select a Name';
return;
}
i have tried this to echo out the string where ever i want
<div id="err" style="color:#fff;"><?php echo $schanName ?></div>
but it doesn't show anything at all.
if i try it like this it will work
if($_POST['thisfolder'] == 'default') {
echo 'Please select a Name';
return;
}
but i don't know what am i doing wrong up there and it's not working.
EDIT #2 HERE my whole page
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<div id="error"> i must display that error here</div>
<form class="s_submit" method="post">
<label class="def_lab">File:</label>
<input class="t_box" type='text' name='filename' placeholder='File Name'>
<label class="t_lab def_lab">Select Folder:</label>
<select id="soflow" name="thisfolder">
<option selected="selected" value="default">Default</option>
<option value="../embed/tv/xbox/">Xbox</option>
<option value="Folder2">Folder2</option>
<option value="Folder3">Folder3</option>
</select><br><br>
<label class="def_lab">Text Area 1:</label><br>
<textarea class="tarea_box" type='text' name='strin'></textarea><br><br>
<label class="def_lab">Text Area 2:</label><br>
<textarea class="tarea_box" type='text' name='strin2'></textarea><br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<?php
var_dump($_POST);
$fNum = 'File Name is Required';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST['filename'])) {
echo $fNum;
return;
}
if($_POST['thisfolder'] == 'default') {
$schanName = 'Please select a Folder';
return;
}
$filename=$_POST['filename'];
$words = array("1", "2", "3", "4", "5");
$arrlength = count($words);
$found = false;
for($x = 0; $x < $arrlength; $x++) {
if($filename == $words[$x])
{
$found = true;
}
}
if($found)
{
echo 'Not a valid File Name';
return;
}
// the name of the file to create
$filename=$_POST['filename'];
// the name of the file to be in page created
$strin=$_POST['strin'];
// the name of the file to be in page created
$strin2=$_POST['strin2'];
// the name of the folder to put $filename in
$thisFolder = $_POST['thisfolder'];
// make sure #thisFolder of actually a folder
if (!is_dir(__DIR__.'/'.$thisFolder)) {
// if not, we need to make a new folder
mkdir(__DIR__.'/'.$thisFolder);
}
// . . . /[folder name]/page[file name].php
$myFile = __DIR__.'/'.$thisFolder. "/page" .$filename.".php";
// This is another way of writing an if statment
$div = ($strin !== '') ? '<div id="area_code">'.$strin.'</div>' : '<div id="area_code">'.$strin2.'</div>';
$fh = fopen($myFile, 'w');
$stringData = "";
fwrite($fh, $stringData);
fclose($fh);
}
?>
</body>
</html>
U need to give this $schanName a value and html form need to be added after php because if u use php after html u can't get values or variable names. But if u use php then html then u can grab values and variables from php into html.
For error report i puted u errors in array so u will get all errors at once.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty($_POST['filename']))
{
$schanName[] = 'File Name is Required';
}
if($_POST['thisfolder'] == 'default')
{
$schanName[] = 'Please select a Folder';
}
$filename=$_POST['filename'];
$words = array("1", "2", "3", "4", "5");
$arrlength = count($words);
$found = false;
for($x = 0; $x < $arrlength; $x++)
{
if($filename == $words[$x])
{
$found = true;
}
}
if($found)
{
$schanName[] = 'Not a valid File Name';
}
// the name of the file to create
$filename=$_POST['filename'];
// the name of the file to be in page created
$strin=$_POST['strin'];
// the name of the file to be in page created
$strin2=$_POST['strin2'];
// the name of the folder to put $filename in
$thisFolder = $_POST['thisfolder'];
// make sure #thisFolder of actually a folder
if (!is_dir(__DIR__.'/'.$thisFolder))
{
// if not, we need to make a new folder
mkdir(__DIR__.'/'.$thisFolder);
}
// . . . /[folder name]/page[file name].php
$myFile = __DIR__.'/'.$thisFolder. "/page" .$filename.".php";
// This is another way of writing an if statment
$div = ($strin !== '') ? '<div id="area_code">'.$strin.'</div>' : '<div id="area_code">'.$strin2.'</div>';
$fh = fopen($myFile, 'w');
$stringData = "";
fwrite($fh, $stringData);
fclose($fh);
}
?>
<?php
// display your errors here
if(!empty($schanName))
{
foreach ($schanName as $sn)
{
echo '<div id="error"><ul><li>'.$sn.'</li></ul></div>';
}
}
?>
<form class="s_submit" method="post">
<label class="def_lab">File:</label>
<input class="t_box" type='text' name='filename' placeholder='File Name'>
<label class="t_lab def_lab">Select Folder:</label>
<select id="soflow" name="thisfolder">
<option selected="selected" value="default">Default</option>
<option value="../embed/tv/xbox/">Xbox</option>
<option value="Folder2">Folder2</option>
<option value="Folder3">Folder3</option>
</select><br><br>
<label class="def_lab">Text Area 1:</label><br>
<textarea class="tarea_box" type='text' name='strin'></textarea><br><br>
<label class="def_lab">Text Area 2:</label><br>
<textarea class="tarea_box" type='text' name='strin2'></textarea><br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</body>
</html>
Declare the variable $schanName outside the if statement first then you can use it in if statement. It will display in the html also.
This is a scoping issue. Check variable scope for more details.

I would like to store new data from a form tag into a php file?

I am trying to make a PHP page which will ask a the user for three things. An email, a first name, and a last name. I want this data to be stored and saved on my computer. Right now I am running XAMPP locally.
When I input the form tags it redirects. I would like to save the data.
Let's say that the user (myself) put a name like "John Mayer" with an email of "johnmayer#gmail.com" how would I save that information on a PHP page after the sumbit button is hit?
Your data input page containing the HTML Form should look something like this:
<form action="save-data.php" method="POST">
<input name="firstname" type="text" />
<input name="lastname" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
now in the PHP file named save-data.php:
<?php
if(isset($_POST['firstname']) && isset($_POST['lastname'])) {
$data = $_POST['firstname'] . '-' . $_POST['lastname'] . "\n";
$ret = file_put_contents('/tmp/mydata.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');
}
Note that 'tmp/mydata.txt' is the path to the file you want to write your data. And it must have the proper write permissions.
HTML:
<form action="mailer.php?savedata=1" method="post">
First Name: <input type="text" name="first_name"><br>
LastName: <input type="text" name="last_name"><br>
Your Email: <input type="text" name="email"><br>
<input type="submit" name="submit" value="Submit">
</form>
PHP:
<?php
$savedata = $_REQUEST['savedata'];
if ($savedata == 1){
$data = $_POST['first_name'];
$data .= $_POST['last_name'];
$data .= $_POST['email'];
$file = "YOURDATAFILE.txt";
$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);
echo "Your Form has been Submitted!";
}
?>
Thanks a lot guys. I figured this out after writing some code myself.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HTML</title>
<meta name="author" content="nelly" />
<!-- Date: 2016-01-01 -->
</head>
<body>
<?php
echo 'Hello' . htmlspecialchars($_POST["first_name"]);
$input = $_POST["first_name"];
$handle = fopen("savingData.txt" , "a+");
$fileName = 'savingData.txt';
$data = $handle;
if (is_writable($fileName))
{
if (!$handle = fopen($fileName, 'a+'))
{
echo "Cannot open file ($fileName)";
exit;
}
if (fwrite($handle, $input ) === FALSE)
{
echo "Cannot write to file name";
exit;
}
echo "Success wrote ($input) to file ($fileName)";
fclose($handle);
}
echo "the file name is not writable?"
?>
</body>
</html>

How to check line in file (php)

I'm new to php and wanted to make a simple php script to check a form of my html site.
To answer the questions:
I have a file, that's the Name of the User and I want to check if the password that is in there (line 1) is the same as the one in the "password" field on my site. And when it's like this it should open a site.
Maybe a check if the file exists would be nice :D
This is my php-file, it's named "check.php":
<?php
$f = fopen($_POST["name"], "r");
$theData = fgets($f);
if ($_POST["pw"] == $theData) {
$ch = curl_init("site.com");
curl_exec($ch);
}
fclose($f);
?>
This is my html-file:
<h2>Check</h2>
<form action="check.php" method='post'>
<b>Name: </b><input name="name" type="text" value="Name"> <br>
<b>Password: </b><input name="pw" type="text" value="Passwort"> <br>
<input type="submit" value="Check">
<input type="reset" value="Reset">
</form>
I hope one can help me ^^
I've tried a lot of things now, nothing really worked.
To process a form fields you should do like this in your check.php file(simplest one)
if(isset($_POST['submit']))
{
$name = $_PSOT['name'];
$password = $_POST['password'];
if($name == 'admin' && $password == 'admin')
{
header('Location:admin.php');exit;
}else{
echo 'Wrong user name or password';
}
}
may be you are asking to do like this
if(isset($_POST['submit']))
{
$name = $_PSOT['name'];
$password = $_POST['password'];
$file_type = '.txt';
$path = 'path to folder/'.$name.$file_type;
if(file_exists($path))
{
$user_pass = fopen($path, "r");
$flag = 0;
while(!feof($user_pass))
{
$p = fgets($user_pass);
if($password == $p)
{
$flag = 1;
}
}
fclose($user_pass);
if($flag == 1)
{
header('Location:to your page link/weblink');exit;
}else{
echo 'Wrong password';
}
}else{
echo 'User does not exists';
}
}

Simple PHP form not working

I´m trying to make a form that works. I´m using codeigniter, the view has this form:
<form class="renuncia_form" action="/formulario/send_form" method="post">
<p>
<label for="nombre">Nombre y apellidos:</label>
<input name="nombre" type="text" id="renuncia_nombre">
<br>
<label for="participe">Nº Partícipe: </label>
<input name="participe" type="text" id="renuncia_participe">
<br>
<label for="nombre_fondo">Nombre del Fondo de Inversión o SICAV: </label>
<input name="nombre_fondo" type="text" id="renuncia_fondo">
<br>
<label for="email">Direccion de correo electrónico: </label>
<input name="email" type="text" id="renuncia_email">
<br>
<input type="submit" value="Enviar" class="renuncia_submit" name="enviar">
</p>
</form>
And the controller has this php:
public function send_form(){
if($_POST['submit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['nombre']))
{
$errorMessage .= "<li>You forgot to enter your name</li>";
}
if(empty($_POST['participe']))
{
$errorMessage .= "<li></li>";
}
$varMovie = $_POST['nombre'];
$varName = $_POST['participe'];
if(empty($errorMessage))
{
$fs = fopen("mydata.csv","a");
fwrite($fs,$varName . ", " . $varMovie . "\n");
fclose($fs);
header("Location: thankyou.html");
exit;
}
}
}
I don´t know if I´m doing correctly the form. I just want to work it as a normal form action, that you click on submit an it takes you to a new page saying "Thanks for your email", no AJAX, just that.
Can anybody help me out with this one?
Edit: Also where do I put the recipient e-mail?
if($_POST['submit'] == "Submit")
should be
if(isset($_POST['enviar']))
As submit button is not having name as submit, instead it is name='enviar'
try this
if(isset($_POST["enviar"]) && $_POST["enviar"] == "Enviar")
You've got
if($_POST['submit'] == "Submit")
and then everything else if the condition is satisfied. It is never as there isn't such field. Just remove it and it'll be fine.
As for mail, you should access it via $_POST['email']. If you want to send an email, take a look here or here.
I think this is because you are translating your form anyway you used
if($_POST['submit'] == "Submit")
and you used in form
<input type="submit" value="Enviar" class="renuncia_submit" name="enviar">
your actual submit button name is enviar and not submit. Since this is a button I would reccomend to check isset()
if(isset($_POST['enviar']))
I'm not sure but the problem is the action attribute.
why don't use From helper to create this form?. Anyway if you don't what or can't use it change the action to something like http://localhost/your_project/index.php/formulario/send_form.
read about base_url here http://ellislab.com/codeigniter/user-guide/helpers/url_helper.html
Besides if($_POST['submit'] == "Submit") is wrong. It must be
if(isset($_POST['submit']) && ($_POST['submit'] === "Enviar"))
if (isset($_POST['enviar']))
This should work
Use:
public function send_form(){
if(array_key_exists('submit',$_POST))
{
$errorMessage = "";
if(empty($_POST['nombre']))
{
$errorMessage .= "<li>You forgot to enter your name</li>";
}
if(empty($_POST['participe']))
{
$errorMessage .= "<li></li>";
}
$varMovie = $_POST['nombre'];
$varName = $_POST['participe'];
if(empty($errorMessage))
{
$fs = fopen("mydata.csv","a");
fwrite($fs,$varName . ", " . $varMovie . "\n");
fclose($fs);
header("Location: thankyou.html");
exit;
}
}
}

Categories