i have written a script that takes the users input from an textarea and puts it in a text file. It also checks if the users piece of text already exists in the text file, in that case it does not write to the file (to prevent duplicate entries). In my code below, the file in question is 'textfile.txt'. Instead of that one i want to edit a file on a SFTP server. I've read something about ssh2_sftp but i didn't understand how to use it. Please help me!
Also, is there any security risk to let people edit a text file on a server using the code below? (except spamming and the file getting ridicously large, as i am using a CAPTCHA for the input form).
Thank you!
<?
$text = $_POST['update'];
$handle = file_get_contents("textfile.txt",NULL);
$text=str_replace(",","",$text);
$text=explode(" ",$text);
$c=0;
foreach($text as $y){
if (stristr($handle,"$text[$c]")) $b[]= 'yes';
else $b[]='no';
$c++;
}
echo $handle;
if (开发者_如何学Pythonin_array("no",$b)) /*här */if($_POST['Submit']){
$open = fopen("textfile.txt","a+");
$text = $_POST['update'];
fwrite($open, "".$text."\n");
fclose($open);
echo "<br/><br/><br/>".$text." has been saved.";
foreach($file as $text) {
echo $text."<br />";
}
}else{
}
else echo '<br/><br/>Thats already in there.';
?>
Yes. Unless you're sanitizing how the content of the file is shown (from what I see, you're using an echo $handle;
to display it), then a person could submit crafted HTML and create an XSS attack.
You might want to consider using strip_tags() on the input data to help prevent this.
Also, a DOS attack could be launched fairly easily because of the usage of file_get_contents
on a file of unknown size. This can be lessened by simply looping through the file line-by-line or by putting a limit on how long the user submitted text can be. This attack isn't likely as serious because you're using CAPTCHA which will slow down most users from submitting text rapidly, but if file_get_contents()
is called without usage of CAPTCHA (say, for viewing the file's contents) then you'll still have a problem.
Edit: I rewrote most of your code snippet for you and added lots of comments. Hopefully you can pick up a few tips and tricks from it and gain a better understanding of best programming practices. (I haven't tried running the code, but it should work fine. Make modifications to it as needed.)
http://pastebin.com/W1EQ3fSm
Using phpseclib, a pure PHP SFTP implementation...
<?php
include('Net/SFTP.php');
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
echo $sftp->pwd() . "\r\n";
$sftp->put('textfile.txt', $sftp->get('textfile.txt') . $_POST['update']."\n");
?>
精彩评论