Earlier today I asked a question about what I was doing wrong, I got this working but now I'm running into another problem with this script.
Previously
The code gave a warning(), that's fixed now. You can read the post Here
What's the problem?
The code automatically empty itself. When you refresh the page where the script is the text file is empty. I have no idea why...
This is the code
<?php
$fn = "file.txt";
$file = fopen($fn, "w+");
$size = filesize($fn);
if($_POST['addition']) fwrite($file, $_POST['addition']);
fclose($file);
?>
<form action="<?=$PHP_SELF?>" method="post">
<input type="text" name="addition" value="<?php echo file_get_contents('file.txt');?>"/>
<input type="submit"/>
</form>
I use this script to display a youtube video on my website, so I got to update it often.
You can find a working example of the script with this link: http://beta.martijnmelchers.nl/private/Test/test.php
What have i tried?
I didn't try many because I couldn't find a solution for this on the internet and also not in the code.
Please help me again! Thanks in advance!
According to the manual with the w+ option:
Open for reading and writing; place the file pointer at the beginning
of the file and truncate the file to zero length. If the file does not
exist, attempt to create it.
It looks like you want to replace all contents when a post is made, so the easiest solution is to put all file-handling calls in the POST condition:
// To avoid warnings, this is better.
// You can add your original condition after it if you need it.
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$file = fopen($fn, "w+");
// not sure why you need this...
// $size = filesize($fn);
fwrite($file, $_POST['addition']);
fclose($file);
}
Related
Is there a way I can have 5 logs files cleared on a frontend, without emptying the file data manually or deleting them?
I want to add a button or such on a page that will empty them if possible.
You can not clear a file on your server on frontend. You can push a button on frontend and call a backend script.
w+ : Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
$handle = fopen ("/path/to/file.txt", "w+");
fclose($handle);
clearlogs.php
<?php
$logfiles = array(
"1-LOG.txt",
"2-LOG.txt",
"3-LOG.txt",
"4-LOG.txt",
"5-LOG.txt",
);
foreach ($logfiles as $logfile){
$clearlogs = #fopen("$logfile","r+");
#ftruncate($clearlogs, 0);
}
header("Location:logs.php");
?>
logs.php
<form action="clearlogs.php" method="POST">
LOGS <input type="submit" value="Clear Logs" />
</form>
I have a form:
<form method="POST" action="">
<textarea id="input_text" name="input_text"></textarea>
<input type="submit" name="decrypt" value="sm">
</form>
now I submit it, php is try to write $_POST['input_text'] to a file then do another action, after complete action, php 'll delete the file created.
<?php
$Path = dirname(__FILE__).'/temp/';
$File_NAME = time().'.txt';
$input_text = stripslashes($_POST['input_text']);
$fp=fopen($Path.$File_NAME,'w');
fwrite($fp,$input_text);
fclose($fp);
//do some curl action with the file, then delete the file
if(file_exists($Path.$File_NAME))
unlink($Path.$File_NAME);
but if the text too strong, user submit the form, then they abort the page, so the file doesn't delete.
I want to direct change the $_POST['input_text'] to type='file', but user also can use it such as a textarea. so php don't need to delete the file because it is a tmp file.
As per your Edit to the question, the possible solution is to first check the $_POST['input_text'] for length before even opening the file. If the text is too long, show an error message.
I don't think that file is even required in that case.
OLD ANSWER:
Fetching the $_POST['input_text], you can :
$txt = $_POST['input_text'];
$file = fopen("file.txt", "w+"); //w+ indicates read + write
fwrite($file,$txt); //to ride the 'input_txt'
Then perform the actions you want and finally delete the file if required using:
fclose($file);
delete("file.txt");
But make sure to grant the PHP page the permissions to Read/Write first.
I am PHP noob, but i am trying to learn it. I have handled some variables and obtaining variable from html form and I wanted to take a string that users types in form -here is code of the form on the page
<form method="POST" action="/php/write.php">
<input type="text" name="string"><input type="submit">
</form>
and in subfolder php I have file "write.php" and it looks like this
<?php
chmod(/write.txt, 0755);
$write == $_POST['string'];
$file = fopen("write.txt","w") or die("cant open file");
fwrite($file, $write);
fclose($file);
?>
I have tried to put into normal HTML file but didnt work too.
The problem is, when I type in the form and press submit, it redirects me on write.php but nothing happens, "cant open file" isnt written nor some error and the file stays empty and no fwrite works for me. Could someone help me please?
A few problems with your code:
chmod(/write.txt, 0755);
The file name must be quoted, and it probably shouldn't be located in the root. The chmod() function only works on existing files. If your file already exists, this is not an error.
$write == $_POST['string'];
The == is the comparison operator. You want assignment =.
You code should look something like this:
$write = $_POST['string'];
$file = fopen('write.txt','w') or die('cant open file');
fwrite($file, $write);
fclose($file);
chmod('write.txt', 0755);
(I prefer single-quoted strings when I don't need to have variables expanded inside.)
Also, in a well-written program, you should:
check if $_POST['string'] actually exists before accessing it, using isset ($_POST['string']).
check the return values of fopen(), fwrite(), fclose() and chmod(), and deal with potential errors.
My last question wasn't explained very well.
What I'm trying to do here is insert data into a PHP File, Using the fwrite feature on another .php file.
To keep this simple, I'm labelling the one I want data inserted as file.php and the one I'm using fwrite to execute on, is edit.php
Now, I got the writing thing down, what my problem is, is I need to INSERT that data, Before the closing php tag on file.php.
What I tried doing was, deleting the closing php tag, writing the data, and then rewriting the tag.
Here is my source code for that:
<?php
$rows = file("file.php");
$tagremove = "?>";
foreach($rows as $key => $row) {
if(preg_match("/($tagremove)/", $row)) {
unset($rows[$key]);
}
}
file_put_contents("file.php", implode("", $rows));
$User = $_GET["user"];
$File = "file.php";
$Handle = fopen($File, "a");
fwrite($Handle, "");
fwrite($Handle, $User);
fwrite($Handle, "\r\n");
fwrite($Handle, "?>");
print "Data Written";
fclose($Handle);
?>
When I run this on Edit.php, it inserts that data into the file, but its only writing to the first line, and replacing whatever is already there. (In my case its the opening php tag). I don't know what I'm doing wrong, or if there is another way to do this, but any assistance would be appreciated.
Edit: this is again for a chat client.
I'm having a file, that sends a message into a .txt file that the client then reads.
And that file is reading file.php (staff.php) to check if the user submitting is a staff member.
If it comes up true that the user is a staff member, then it changes the username variable in the send.php.
And so far, the send.php has only sucessfully, included the Staff.php, I've tried staff.txt, and the reason is, php code is in the staff.php.
Try this:
$data="echo 'hello world!';";
$filecontent=file_get_contents('file.php');
// position of "?>"
$pos=strpos($filecontent, '?>');
$filecontent=substr($filecontent, 0, $pos)."\r\n".$data."\r\n".substr($filecontent, $pos);
file_put_contents("file.php", $filecontent);
Please don't forget, that you need to check data from user.
Ok much better alternative use a data file. Ill use json because its easy to use an very easy to parse by human eyes as well:
// read file
$data = file_get_contents('data.json');
$json = json_decode($data, true);
// manipulate data
$json['users'][] = $_GET['user'];
// write out file
$dataNew = json_encode($json);
file_put_contents('data.json', $dataNew);
the reason is, php code is in the staff.php
Well this isnt something you workaround. You should be writing/reading this kind of information form a data stor - that could be a file or a database... but not an actual script.
I have a form with the possibility to upload an image from the computer to a server, but it won't work. I don't get any error message, so that's quite annoying. (First I got permission denied, but that was solved by changing the rights), but now when I submit the form, everything goes normally, but the file isn't copied to the destination folder. (The folder exists: I tried it with file_exist()...)
Here's part of the code:
<form action='/changingfruit/index.php?item=bad' name='form' method='post' enctype='multipart/form-data'>
<tr>
<td><input type='text' name='titel_nl' value="titel nl" /><br/><input type='text' name='titel_fr' value="titel fr"/></td>
<td><input type='file' name='text_nl' id='text_nl' accept="image/*"/><br/><input type='file' name='text_fr' id="test_fr" accept="image/*"/></td>
<td class="vTop"><input type="submit" value="Bewaar"/></td>
</tr>
</form>
Part where the values are being send to the db:
$str_titel_nl = $_POST["titel_nl"];
$str_titel_fr = $_POST["titel_fr"];
$str_text_nl = $_FILES["text_nl"]["name"];
$str_text_fr = $_FILES["text_fr"]["name"];
if(!empty($_FILES["text_nl"]["name"])){
$tmp = $_FILES['text_nl']['tmp_name'] ;
$foto = $_FILES['text_nl']['name'] ;
$copied = copy($tmp, $images_nl.$foto);
unlink($tmp);
}
(of course the above is just a part of the code: but it's this part that wont work:
if(!empty($_FILES["text_nl"]["name"])){
$tmp = $_FILES['text_nl']['tmp_name'] ;
$foto = $_FILES['text_nl']['name'] ;
$copied = copy($tmp, $images_nl.$foto);
unlink($tmp);
}
The code below this part also works fine, so no error, but also no image.
Does someone knows where the problem could be?
Thanks so much in advance!
FOUND THE ANSWER
So it was indeed a permission problem. Everything was 777, but the last folder where the image was put had 755. (/fruits/img/2012/thumb/) the thumb was 755.I just overlooked it. Thanks everyone for the help!
Your upload code is very messy. Instead of using copy you should be using move_uploaded_file, and also validate that it actually worked and then perform whatever actions needed.
I'm also not sure why each of your line is starts with <?php and ends with ?> ?
You can write it all as one block instead, and i think it would also make more sense and would make your code cleaner for sure.
Last thing i would recommend is reading "Handling File Uploads" from the PHP Manual. It might shed some light on the problems you're having.
P.S. Try adding on top ini_set("display_errors","On"); error_reporting(E_ALL); and see if you're getting any error messages.
please have a look on below link.
PHP upload file to web server from form. error message
http://patelmilap.wordpress.com/2012/01/30/php-file-upload/
you can try this
$flag = #copy($temp, $move);
if ( $flag === true )
{
print "Uploaded";
}
I have posted a simple solution for file uploading without worrying about the implementation .
Click to see the thread
image uploading issue in codeigniter 2.1.0
Please read this section
in that $uploader->getMessage(); will return error string related to the upload failure . So you can understand why the uploading failed .
Thanks