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)
Related
I am creating a Guestbook in PHP, each IP will only be able to post once.
Except for that it will require name and message before sending, and also CAPTCH validation. Somehow my code does ignore the Captcha validation as long as something is written in the input, regardless of what.
I have tried to save the captch in session, and validate the input for the captcha but it doesnt help.
Code to generate the captcha:
function generateCaptchaString($length = 5) {
$captchaString = substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
$_SESSION["captchaString"] = $captchaString;
return $captchaString;
}
Code to input name, message and captcha:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"
id="guestform">
<fieldset>
<legend>Skriv i gästboken</legend>
<label>Från: </label>
<input type="text" placeholder="Skriv ditt namn"
name="name">
<br>
<label for="text">Inlägg</label>
<textarea id="text" name="message"
rows="10" cols="50"
placeholder="Skriva meddelande här"></textarea>
<br>
<label>Captcha: <span class="red" id="captchastring"><?php
echo generateCaptchaString(); ?></span></label>
<input type="text" placeholder="Skriva captcha här"
name="captcha" id="captchainput" required>
<button type="submit" id="submit">Skicka</button>
</fieldset>
</form>
Code in the POST-function that will check for validation.
if( ! isset($_POST['captcha']) || empty($_POST['captcha']) ||
$_POST['captcha'] != $_SESSION['captcha']) {
$error .= "<p class=\"message-error\">" . $messages['math_invalid'] . "
</p>";
}
In your generateCaptchaString() function, you store the captcha string in $_SESSION["captchaString"].
But in the POST-validation code, you read it as: $_SESSION['captcha']
Change that into $_SESSION["captchaString"] as well.
Also, are you sure the URL to go to when submitting the form is $_SERVER['PHP_SELF'] (which may be another .php script that includes or requires this one) rather than $_SERVER['REQUEST_URI'] which is the same URL you're currently visiting.
Also, if the POST check code is in (or included by) the same file that also contains or includes the form, is it possible that generateCaptchaString() gets called again (to create the form again) thus overwriting any previous captchaString stored there?
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.
This is a simple Captcha form which is working well and prints the requested result after I press ‘submit’.
<?php
session_start();
$msgCaptcha = "";
?>
<?php
if (isset($_POST['submit'])){
$secCode = isset($_POST['secCode']) ? strtolower($_POST['secCode']) : "";
if ($secCode == $_SESSION['securityCode']) {
$msgCaptcha = "valid code";
$result = true;
}
else {
$msgCaptcha = "wrong security code";
$result = false;
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
name:<input name="myname" type="text"><br />
Security code: <input class="text" name="secCode" type="text">
<img src="securityCode.php" /><br />
<?php echo $msgCaptcha ?>
<input name="submit" type="submit" value="submit">
</form>
. i.e.
If my input is the same as like in the picture the printing is “valid security code”
and if the input is not the same, the printing is “wrong security code”.
When I change in the form the code to action="mailer.php" this file is opened but ignore of any input in the Captcha validation.
I need mailer.php to be open after Captcha validation.
I have tried onsubmit and some other options, but none of them works as a solution for the above.
Any help would be greatly appreciated.
You could try to include mailer.php after the $msgCaptcha = "valid code"; line.
Any code inside mailer.php would be executed in that block of code, and any $_POST variables required by mailer.php would be available.
The bottom line is, when you call mailer.php, you must have captcha validation in front of that file, otherwise any bot/spammer can bypass your captcha protection just by submitting the form directly to mailer.php
Keep in mind, bots generally ignore javascript, so the validation has to be done server side.
You may want to set a variable prior to including mailer.php that it will check so even if someone did try to directly submit to mailer.php, it won't process the form unless the file was included.
If this doesn't help, post the code for mailer.php so we know what the contents of that file are.
Use header()
if ($secCode == $_SESSION['securityCode']) {
$msgCaptcha = "valid code";
header("Location: http://www.website.com/ ... /mailer.php");
}
I have developed a site for a client and he wants to be able to edit a small part of the main page in a backend type of solution. So as a solution, I want to add a very basic editor (domain.com/backend/editor.php) that when you visit it, it will have a textfield with the code and a save button. The code that it will edit will be set to a TXT file.
I would presume that such thing would be easy to code in PHP but google didn't assist me this time so I am hoping that there might be someone here that would point me to the right direction. Note that I have no experience in PHP programming, only HTML and basic javascript so please be thorough in any reply that you provide.
You create a HTML form to edit the text-file's content. In case it get's submitted, you update the text-file (and redirect to the form again to prevent F5/Refresh warnings):
<?php
// configuration
$url = 'http://example.com/backend/editor.php';
$file = '/path/to/txt/file';
// check if form has been submitted
if (isset($_POST['text']))
{
// save the text contents
file_put_contents($file, $_POST['text']);
// redirect to form again
header(sprintf('Location: %s', $url));
printf('Moved.', htmlspecialchars($url));
exit();
}
// read the textfile
$text = file_get_contents($file);
?>
<!-- HTML form -->
<form action="" method="post">
<textarea name="text"><?php echo htmlspecialchars($text); ?></textarea>
<input type="submit" />
<input type="reset" />
</form>
To read the file:
<?php
$file = "pages/file.txt";
if(isset($_POST))
{
$postedHTML = $_POST['html']; // You want to make this more secure!
file_put_contents($file, $postedHTML);
}
?>
<form action="" method="post">
<?php
$content = file_get_contents($file);
echo "<textarea name='html'>" . htmlspecialchars($content) . "</textarea>";
?>
<input type="submit" value="Edit page" />
</form>
You're basically looking for a similar concept to that of a contact-form or alike.
Apply the same principles from a tutorial like this one and instead of emailing using mail check out the file functions from PHP.net.
What did you Google on then? php write file gives me a few million hits.
As in the manual for fwrite():
<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);
// the content of 'data.txt' is now 123 and not 23!
?>
But to be honest, you should first pick up a PHP book and start trying. You have posted no single requirement, other than that you want to post a textfield (textarea I mean?) to a TXT file. This will do:
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
$handle = fopen("home.txt", 'w') or die("Can't open file for writing.");
fwrite($fh, $_POST['textfield']);
fclose($fh);
echo "Content saved.";
}
else
{
// Print the form
?>
<form method="post">
<textarea name="textfield"></textarea>
<input type="submit" />
</form>
<?php
}
Note that this exactly matches your description. It doesn't read the file when printing the form (so every time you want to edit the text, you have to start from scratch), it does not check the input for anything (do you want the user to be able to post HTML?), it has no security check (everyone can access it and alter the file), and in no way it reads the file for display on the page you want.
First thing to do is capture the information, the simplest way to do this would be the use of a HTML Form with a TEXTAREA:
<form method='post' action='save.php'>
<textarea name='myTextArea'></textarea>
<button type='submit'>Go</button>
</form>
On 'save.php' (or wherever) you can easily see the information sent from the form:
<?php
echo $_POST['myTextArea']
?>
To actually create a file, take a look at the fopen/fwrite commands in PHP, another simplistic example:
<?php
$handle = fopen("myFile.txt","w");
fwrite($handle,$_POST['myTextArea'];
fclose($handle);
?>
WARNING: This is an extremely simplistic answer! You will perhaps want to protect your form and your file, or do some different things.... All the above will do is write EXACTLY what was posted in the form to a file. If you want to specify different filenames, overwrite, append, check for bad content/spam etc then you'll need to do more work.
If you have an editor that is publicly accessible and publishes content to a web page then spam protection is a DEFINITE requirement or you will come to regret it!
If you aren't interested in learning PHP then you should think about getting a professional developer to take care of any coding work for you!
I had a similar need so we created a client-friendly solution called stringmanager.com we use on all our projects and places where CMS is not effective.
From your side, you just need to tag string in the code, i.e. from:
echo "Text he wants to edit";
to:
echo _t("S_Texthewantstoedit");
stringmanager.com takes care about the rest. Your client can manage that particular text area in our online application and sync wherever he wants. Almost forgot to mention, it is completely free.
Can use this line of code :
<form action="" method="post">
<textarea id="test" name="test" style="width:100%; height:50%;"><? echo "$test"; ?></textarea>
<input type="submit" value="submit">
</form>
<?php
$file = "127.0.0.1/test.html";
$test = file_get_contents('1.jpg', 'a');
if (isset($_POST['test'])) {
file_put_contents($file, $_POST["test"]);
};
?>
<form action="" method="post">
<textarea id="test" name="test" style="width:100%; height:50%;"><? echo "$test"; ?></textarea>
<input type="submit" value="submit">
</form>
Haven't had time to finish it, simplest possible, will add more if wanted.
I'd like if someone could give me some advice on creating the php file, i know to php language.but where to write it.i have followed some tutorial to run php file in netbeans but its pathethic to download xamp server,apache http server.can u give me the direct of how make configuration and all.i have window7 ultimate and will file i hav to download i don't know. i have netbeans all bundle feature and wamp server.how should i write my php program successfully.plz help me to resolve this.
i m editing the question becoz in comment it is than wordspace given there thatwhy not accepting
thanks its working..
can u tell me why this code doesnot work properly
my php code(or content is this)
<html>
<head>
<title>Binary Search</title>
<style type="text/css">
h1 {color: blue}
</style>
</head>
<body>
<h1 align="center">Computer guess number by using binary search</h1>
<form method="GET">
<?
if (empty($flag_num))
{
$flag_num = -1;
}
if ($flag_num==-1)
{
if (empty($max_num)) $max_num = -1;
if (empty($min_num)) $min_num = -1;
$flag_num = 1;
print <<<Here
<input type="hidden" name="flag_num" value="$flag_num">
<input type="hidden" name="max_num" value="$max_num">
<input type="hidden" name="min_num" value="$min_num">
Input your hidden number: <input type="text" name="hid_num" value="$hid_num"> (1-99)
<br>
<input type="submit" value="Now let's computer guess">
Here;
}
else
{
if ($max_num==-1 && $min_num==-1)
{
$max_num = 100;
$min_num = 0;
$result_num = $hid_num;
}
else
{
if ($comparision == "bigger")
{
$min_num = $guess_num;
}
else if ($comparision == "smaller")
{
$max_num = $guess_num;
}
}
$guess_num = ($max_num + $min_num)/2;
setType($guess_num,"integer");
print "Computer guess <h3> $guess_num </h3>";
if ($guess_num == $result_num)
{
$flag_num = -1;
}
if ($flag_num == -1)
{
print <<<Here
<input type="hidden" name="flag_num" value="$flag_num">
<h1> Congratulation, Computer win </h1>
<input type="submit" value="Next>>>" >
Here;
}
else
{
print <<<Here
<input type="hidden" name="flag_num" value="$flag_num">
<input type="hidden" name="max_num" value="$max_num">
<input type="hidden" name="min_num" value="$min_num">
<input type="hidden" name="guess_num" value="$guess_num">
<input type="hidden" name="result_num" value="$result_num">
<br>
Your intruction: <input type="radio" name="comparision" value="bigger"> Bigger
<input type="radio" name="comparision" value="smaller"> Smaller
<br>
<input type="submit" value="Submit">
Here;
}
}
?>
</form>
</body>
</html>
it doesnot giving the output properly as required
wherever wamp is installed go to the folder "www", put the the php file there
then go to localhost:8080/yourfile.php
that's all there is to it
You could write PHP code in almost anything, and the file will be created as long as you add the .php extension to the new file. I wrote a few simple programs using Notepad and Notepad++ before going onto Eclipse PDT.
To run your file, one out of many ways, you can start up your WAMPserver, browse to http://localhost and drag and drop your file into the browser.
You could also put the .php file inside the www folder (IIRC thats the name of the folder, my memory is a bit hazy) and then browse to http://localhost/name_of_file.php. In either case, if successful, your PHP code should execute on the page.