HTML forms, fwrite and PHP - php

I want to use fwrite to save data into a .txt file. The action method seems to be working, as it can show HTML tags when being transfered when pressing submit, but i wont run the PHP.
<HTML lang="da">
<style>
</style>
<header>
<title>Tilføj</title>
<meta charset="ISO-8859-1">
</header>
<body>
<form method="post" action="eksamen_save_data.php" enctype='multipart/form-data'>
<fieldset>
<legend>Filmoplysninger</legend>
<div><label>Titel: <input type="text" name="titel" id="titel" required="required" size="60" maxlength="100"></label></div>
<div><label>Hovedskuespiller: <input type="text" name="hovedskuespiller" id="hovedskuespiller" required="required" size="30" maxlength="100"></label></div>
<div><label>Genre: <input type="text" name="genre" id="genre" required="required" size="60" maxlength="100"></label></div>
<div><label>Format: <input type="text" name="format" id="format" required="required" size="60" maxlength="100"></label></div>
<div><label>Billede: <input type="file" name="billede" id="billede" required="required"></label></div>
</fieldset>
<div><input type="submit" id="ok" value="OK"></div>
</form>
</body>
This sends it to the "eksamen_save_data.php" that looks like this:
<?php
$Titel = $_POST["titel"];
$Hovedskuespiller = $_POST["hovedskuespiller"];
$Genre = $_POST["genre"];
$Format = $_POST["format"];
//$Billede = $_FILES["billede"]["navn"];
//if($_FILES){
// move_uploaded_file($_FILES["billed"]["navn"], $_FILES["billed"]["navn"]);
//}
$user_data = "$Titel, $Hovedskuespiller, $Genre, $Format, $Billede \r\n";
$fh = fopen("data.txt", "a") or die("Fejl i åbning af fil!");
fwrite($fh, $user_data) or die ("Fejl i skrivning til fil!");
fclose($fh);
?>
If i write some HTML in the "eksamen_save_data.php" i can show this, but it wont run the PHP. I'm using XAMPP.
The problem is that it wont save to the "data.txt" file as i tell the PHP to do.
Another question; is there also a way, I can make the PHP run in the same file as where I have my fieldset?
LAST EDIT:
Most of the time it's the little mistakes that proves to be the biggest problem. For me i personally forgot to use: localhost/eksamen_tilføj.php in the browser.
So it was me making a mistake in XAMPP.

Use file_put_contents
file_put_contents("data.txt", $user_data, FILE_APPEND);
It does all the jobs like file open, write and close. Advantage is if the file does not exist then it will create.
Find full working code
<?php
$Titel = $_POST["titel"];
$Hovedskuespiller = $_POST["hovedskuespiller"];
$Genre = $_POST["genre"];
$Format = $_POST["format"];
$Billede = $_FILES["billede"]["name"];
// Example of accessing data for a newly uploaded file
$fileName = $_FILES["billede"]["name"];
$fileTmpLoc = $_FILES["billede"]["tmp_name"];
// Path and file name
$pathAndName = "upload/".$fileName;
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
// Evaluate the value returned from the function if needed
if ($moveResult == true) {
echo "File has been moved from " . $fileTmpLoc . " to" . $pathAndName;
} else {
echo "ERROR: File not moved correctly";
}
$user_data = "$Titel, $Hovedskuespiller, $Genre, $Format, $Billede \r\n";
file_put_contents("data.txt", $user_data, FILE_APPEND);
?>

you'll have to remove the third parameter $test (because it specifies the length of the content to be written). But $test is not defined in your PHP file, so it won't write anything..
So change this
fwrite($fh, $user_data, $test) or die ("Fejl i skrivning til fil!");
into this
fwrite($fh, $user_data) or die ("Fejl i skrivning til fil!");
and have a look at this :)

As for your second question: sure you can merge your form and submit scripts:
<?php
if(count($_POST) > 0) { //
/** Form submit function, file write **/
} else {
?>
<html>
<form action="#" method="POST">
<!-- Enter HTMLform here -->
</form>
</html>
<?php } ?>
This pseudocode is not pretty, but will do in terms of explaining stuff. The # in the form action means that the same script is to be called upon submission. The if(count($_POST) > 0) checks whether data has been submitted. If so, the file will be written. Otherwise, the form will be displayed.
Good luck.

Related

How can I get the output for form without the page changing

I am trying to get information from textarea to be converted to a .py file.
Here's my file https://jsfiddle.net/girlwhocancode/68mb49gq/
<form action=action.php method="post">
<center>
<textarea placeholder="Code you want to execute in python..."></textarea>
</center><br/>
<center><input type="submit" class="button_example"></center>
</form>
and this is my php file:
<?php
$path = #PATH;
if (isset($_POST['field1'])) {
$fh = fopen($path,"a+");
$string = $_POST['field1'];
fwrite($fh,$string); // Write information to the file
fclose($fh); // Close the file
}
?>
For some reason my php isn't working and I have no idea how to keep the same webpage after submitting
Try this:
<form action="action.php" method="post">
<center>
<textarea name="script" placeholder="Code you want to execute in python..."></textarea> //added name
</center><br/>
<center><input name="submit" type="submit" class="button_example"></center>
</form> // added name submit
in php
<?php
$path = #PATH;
if (isset($_POST['submit'])) {
$fh = fopen($path,"a+");
$string = $_POST['script'];
fwrite($fh,$string); // Write information to the file
fclose($fh); // Close the file
}
?>
Remember that in php $_POST/$_GET keys are always your form field
names

how to upload at new name and section

I have a problem that made me lose my temper really I have the following code
OK ?
$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");
$vedioname = $_POST['vedionamet'];
$path = $_POST['selectsection'];
$finalpath =realpath(dirname(__FILE__)."/Uploads/".$path);
$vedname= $_FILES['vedio']['name'];
$temp=$_FILES['vedio']['tmp_name'];
$type = $_FILES["vedio"]['type'];
$size = $_FILES['vedio']['size'];
$errors = $_FILES['vedio']['error'];
if($_POST['uploadsub']){
move_uploaded_file($temp,$finalpath.$vedioname);
echo "Done Uploaded".$type;
}else
{
echo "$error";
}
The first problem is supposed to be the process of uploading the file to file uploads
The file is not even uploaded to the same file as the page
Second, the goal is to write the name of the file uploaded within the text, but what is happening in reverse exactly that
So how to make the upload process successful
Inside the uploads / value received from the form section
And the new name of the received value of the form
<form action="<?php echo $PHP_SELF; ?>" method="post" enctype="multipart/form-data">
<div id="inputs">
<label class="labels" for="name">Vedio Name: </label>
<input id="name" type="text" name="vedionamet" value="vedio"> </br>
<label class="labels" for="selectsection">Select Section :</label>
<select name="selectsection" id="section" >
<?php
foreach($sections as $pathat){
echo "<option value='$pathat'>" . "$pathat" . "</option>";
};
?>
</select></br>
<label class="labels" for="upup">Select Vedio : </label>
<input id="upload" type="file" name="vedio"></br>
<input id="subb" type="submit" name="uploadsub" value="Upload">
</
For the HTML part, you may change the action to "#" if you want to use a same page to handle the upload request.
For the PHP part, you may try the following codes, it works on my computer. Please also make sure that you have already established these sub video folders in Uploads folder
<?php
$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");
//add one condition to avoid warning when the page first loads
if(isset($_POST["selectsection"])){
$vedioname = $_POST['vedionamet'];
$path = $_POST['selectsection'];
//Use this to get the path
$finalpath = realpath(dirname(getcwd())) . '\\Uploads\\' . $path. '\\';
$vedname= $_FILES['vedio']['name'];
$temp=$_FILES['vedio']['tmp_name'];
//Use this to get the extension of file name
$type = pathinfo($vedname, PATHINFO_EXTENSION);
$size = $_FILES['vedio']['size'];
$errors = $_FILES['vedio']['error'];
if($_POST['uploadsub']){
move_uploaded_file($temp,$finalpath.$vedioname.".".$type);
echo "Done Uploaded".$type;
}else
{
echo "$error";
}
}
?>

Editing PHP files Using PHP

I am using the following script to edit text based files on my server (TXT,HTML,PHP,etc..)
<?php
$filename = "test.php";
function make_content_file($filename,$content,$opentype="w")
{
$fp_file = fopen($filename, $opentype);
fputs($fp_file, $content);
fclose($fp_file);
}
if($_POST)
{
$newcontents=$_POST[newcontents];
make_content_file($filename,$newcontents);
}
$filecontents = file_get_contents($filename);
?>
<?php
if($_POST)
{
echo '<p><span style="font-weight: 700; background-color: #CCFFCC">You have successfully posted to your txt file!</span></p>
Download';
}
?>
<form method="post">
<textarea name="newcontents" cols="70" rows="25"><?=$filecontents?></textarea>
<br>
<input type="submit" value="Save">
</form>
The script works fine with most of PHP files Example:
But if a file includes some form with textarea the code just get messed up
Example:
Another Example: http://i.imgur.com/P9O34Y8.png
Would like to know why this happen and how to fix it, Thanks
The first comment sums it all
Fun fact: I have a similar tool myself, with the ability to edit files from a bookmark, an emptying files feature, and sha1 password protection. (insecure crc32 is still used in the original code)
Hope it's actually useful
if (sha1($_POST['pass']) != $pass) {
echo "<style>input{padding:0.1em; font-size:1.1em}body{background:$bg; color:$fg; font-family:corbel;font-size:1.4vw;padding:0.4em}a{color:$fg}</style><body><h2>$nick<mark>:)</mark></h2>";
echo '
<form action="writer.php" method="post">
Code: <input type="password" name="pass" autofocus>
<input type="hidden" name="f" value="'.$_GET['f'].'"><br><br>';
if ($_POST['pass'] != ""){
echo 'Incorrect code.';
}
}
https://pastebin.com/krMrA783
To empty a file, type "empty".
To set the password before using, go through the first 5 lines of code, and modify $pass.
Make sure that the password is secure and unique (14+ characters)

PHP how to clear memory when refreshing

I am facing the following issue. I have a simple textarea where user will use to submit text which is subsequently written to a text file in the server. This is working.
But when I refresh the page it adds in the last added text into the text file again causing duplicate entries.
Any idea what I must do to prevent this? Below is the code I used for the textarea portion.
<html>
<body>
<form name="form" method="post">
<input type="text" name="text_box" size="50"/>
<input type="submit" id="search-submit" value="submit" />
</form>
</body>
</html>
<?php
if(isset($_POST['text_box'])) {
$a = $_POST['text_box'];
$myFile = "textfile.txt";
$fh = fopen($myFile, 'a+') or die("can't open file");
fwrite($fh, $a."\r\n");
fclose($fh);
}
?>
Pages that are loaded via POST will cause the browser to ask the user to resubmit the information to view the page resulting in the actions performed by that page happening again. If the pages is requested via GET and has variables in the querystring the same thing happens but silently (without the user being prompted to d it again).
The best to work around this is to use the POST/REDIRECT/GET pattern. I used it in an example about processing payments that I wrote for Authorize.Net. Hopefully that points you in the right direction.
A simpler so
You can just store a simple hash on session and regenerate it every time.
When the user reloads the page the php wont be executed.
<?php
if(isset($_POST['text_box']) && $_SESSION['formFix'] == $_POST['fix']) {
$a = $_POST['text_box'];
$myFile = "textfile.txt";
$fh = fopen($myFile, 'a+') or die("can't open file");
fwrite($fh, $a."\r\n");
fclose($fh);
}
?>
<html>
<body>
<form name="form" method="post">
<input type="text" name="text_box" size="50"/>
<?php
$value = md5(rand(1,999999));
$_SESSION['formFix'] = $value;
?>
<input type="hidden" name="fix" value="<?= $value; ?>" />
<input type="submit" id="search-submit" value="submit" />
</form>
</body>
</html>
ps: the order of the blocks will matter, so you need to invert em.
As John said, you need to redirect user after form submit.
fclose($fh);
// and
header("Location: success.php or where else");
exit;
Note: Your redirection won't work unless ob_start is not called before, cos your page contains html outputs.
// form.php
<?php ob_start(); ?>
<html>
<body>
<? if (isset($_GET['success'])): ?>
Submit OK! New submit
<? else: ?>
<form name="form" method="post" action="form.php">
<input type="text" name="text_box" size="50"/>
<input type="submit" id="search-submit" value="submit" />
</form>
<? endif; ?>
</body>
</html>
<?php
if(isset($_POST['text_box'])) {
$a = $_POST['text_box'];
$myFile = "textfile.txt";
$fh = fopen($myFile, 'a+') or die("can't open file");
fwrite($fh, $a."\r\n");
fclose($fh);
// send user
header("Location: form.php?success=1");
exit;
}
?>

How can i create variables to get file data and insert into db those variables?

I am a newbie and have spent over 3 hours trying to find a way to get the filename, filesize, path, from the uploaded file. But this form is doing it in a way i am not able to understand. I need the filename, filesize, path variables stored in the db. How can i implement a $sql insert in the code below:
Code:
$upload_dir = "/var/www/anyexample/aeu"; // Directory for file storing
// filesystem path
$web_upload_dir = "/aeu"; // Directory for file storing`
// Web-Server dir
/* upload_dir is filesystem path, something like
/var/www/htdocs/files/upload or c:/www/files/upload
web upload dir, is the webserver path of the same
directory. If your upload-directory accessible under
www.your-domain.com/files/upload/, then
web_upload_dir is /files/upload
*/
// testing upload dir
// remove these lines if you're shure
// that your upload dir is really writable to PHP scripts
$tf = $upload_dir.'/'.md5(rand()).".test";
$f = #fopen($tf, "w");
if ($f == false)
die("Fatal error! {$upload_dir} is not writable. Set 'chmod 777 {$upload_dir}'
or something like this");
fclose($f);
unlink($tf);
// end up upload dir testing
// FILEFRAME section of the script
if (isset($_POST['fileframe']))
{
$result = 'ERROR';
$result_msg = 'No FILE field found';
if (isset($_FILES['file'])) // file was send from browser
{
if ($_FILES['file']['error'] == UPLOAD_ERR_OK) // no error
{
$filename = $_FILES['file']['name']; // file name
move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir.'/'.$filename);
// main action -- move uploaded file to $upload_dir
$result = 'OK';
}
elseif ($_FILES['file']['error'] == UPLOAD_ERR_INI_SIZE)
$result_msg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
else
$result_msg = 'Unknown error';
// you may add more error checking
// see http://www.php.net/manual/en/features.file-upload.errors.php
// for details
}
// outputing trivial html with javascript code
// (return data to document)
// This is a PHP code outputing Javascript code.
// Do not be so confused ;)
echo '<html><head><title>-</title></head><body>';
echo '<script language="JavaScript" type="text/javascript">'."\n";
echo 'var parDoc = window.parent.document;';
// this code is outputted to IFRAME (embedded frame)
// main page is a 'parent'
if ($result == 'OK')
{
// Simply updating status of fields and submit button
echo 'parDoc.getElementById("upload_status").value = "file successfully uploaded";';
echo 'parDoc.getElementById("filename").value = "'.$filename.'";';
echo 'parDoc.getElementById("filenamei").value = "'.$filename.'";';
echo 'parDoc.getElementById("upload_button").disabled = false;';
}
else
{
echo 'parDoc.getElementById("upload_status").value = "ERROR: '.$result_msg.'";';
}
echo "\n".'</script></body></html>';
exit(); // do not go futher
}
// FILEFRAME section END
// just userful functions
// which 'quotes' all HTML-tags and special symbols
// from user input
function safehtml($s)
{
$s=str_replace("&", "&", $s);
$s=str_replace("<", "<", $s);
$s=str_replace(">", ">", $s);
$s=str_replace("'", "&apos;", $s);
$s=str_replace("\"", """, $s);
return $s;
}
if (isset($_POST['description']))
{
$filename = $_POST['filename'];
$size = filesize($upload_dir.'/'.$filename);
$date = date('r', filemtime($upload_dir.'/'.$filename));
$description = safehtml($_POST['description']);
// Let's generate file information page
$html =<<<END
<html><head><title>{$filename} [uploaded by IFRAME Async file uploader]</title></head>
<body>
<h1>{$filename}</h1>
<p>This is a file information page for your uploaded file. Bookmark it, or send to anyone... </p>
<p>Date: {$date}</p>
<p>Size: {$size} bytes</p>
<p>Description:
<pre>{$description}</pre>
</p>
<p>download file<br>
back to file uploading<br>
upload-log</p>
<br><br>Example by AnyExample
</body></html>
END;
// save HTML
$f = fopen($upload_dir.'/'.$filename.'-desc.html', "w");
fwrite($f, $html);
fclose($f);
$msg = "File {$filename} uploaded,
<a href='{$web_upload_dir}/{$filename}-desc.html'>see file information page</a>";
// Save to file upload-log
$f = fopen($upload_dir."/upload-log.html", "a");
fwrite($f, "<p>$msg</p>\n");
fclose($f);
// setting result message to cookie
setcookie('msg', $msg);
// redirecting to the script main page
// we're doing so, to avoid POST form reposting
// this method of outputting messages is called 'flash' in Ruby on Rails
header("Location: http://".$_SERVER['HTTP_HOST'].$PHP_SELF);
exit();
// redirect was send, so we're exiting now
}
// retrieving message from cookie
if (isset($_COOKIE['msg']) && $_COOKIE['msg'] != '')
{
if (get_magic_quotes_gpc())
$msg = stripslashes($_COOKIE['msg']);
else
$msg = $_COOKIE['msg'];
// clearing cookie, we're not going to display same message several times
setcookie('msg', '');
}
?>
<!-- Beginning of main page -->
<html><head>
<title>IFRAME Async file uploader example</title>
</head>
<body>
<?php
if (isset($msg)) // this is special section for outputing message
echo '<p style="font-weight: bold;">'.$msg.'</p>';
?>
<h1>Upload file:</h1>
<p>File will begin to upload just after selection. </p>
<p>You may write file description, while you file is being uploaded.</p>
<form action="<?=$PHP_SELF?>" target="upload_iframe" method="post" enctype="multipart/form-data">
<input type="hidden" name="fileframe" value="true">
<!-- Target of the form is set to hidden iframe -->
<!-- From will send its post data to fileframe section of
this PHP script (see above) -->
<label for="file">text file uploader:</label><br>
<!-- JavaScript is called by OnChange attribute -->
<input type="file" name="file" id="file" onChange="jsUpload(this)">
</form>
<script type="text/javascript">
/* This function is called when user selects file in file dialog */
function jsUpload(upload_field)
{
// this is just an example of checking file extensions
// if you do not need extension checking, remove
// everything down to line
// upload_field.form.submit();
var re_text = /\.txt|\.xml|\.zip/i;
var filename = upload_field.value;
/* Checking file type */
if (filename.search(re_text) == -1)
{
alert("File does not have text(txt, xml, zip) extension");
upload_field.form.reset();
return false;
}
upload_field.form.submit();
document.getElementById('upload_status').value = "uploading file...";
upload_field.disabled = true;
return true;
}
</script>
<iframe name="upload_iframe" style="width: 400px; height: 100px; display: none;">
</iframe>
<!-- For debugging purposes, it's often useful to remove
"display: none" from style="" attribute -->
<br>
Upload status:<br>
<input type="text" name="upload_status" id="upload_status"
value="not uploaded" size="64" disabled>
<br><br>
File name:<br>
<input type="text" name="filenamei" id="filenamei" value="none" disabled>
<form action="<?=$PHP_SELF?>" method="POST">
<!-- one field is "disabled" for displaying-only. Other, hidden one is for
sending data -->
<input type="hidden" name="filename" id="filename">
<br><br>
<label for="photo">File description:</label><br>
<textarea rows="5" cols="50" name="description"></textarea>
<br><br>
<input type="submit" id="upload_button" value="save file" disabled>
</form>
<br><br>
upload-log
<br><br><br>
Example by AnyExample
</body>
</html>
move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir.'/'.$filename);
I would suggest adding something like the following after the previous mentioned line:
$size = filesize($upload_dir.'/'.$filename);
$path = $upload_dir.'/'.$filename;
mysql_connect(YOUR_HOST, YOUR_USERNAME, YOUR_PASSWORD);
mysql_select_db(YOUR_DATABASE);
mysql_query('INSERT INTO your_table SET filename=$filename, size=$size, path=$path');

Categories