I did a code in PHP where input is saved to the file 'news'. Now I would like to change it that it will save every input to separate file in special folder(news) which name starts with date.
I wrote something like this but it isn't working (the file isn't being created)
<?php
include "0begin.php";
$title=$_POST["title"];
isset($title) or $title=$_GET["title"];
$msg=$_POST["msg"];
?>
<h1>News</h1>
<form method=post>
Title<br><input type=text input name="title" value=<?=$title?> ><br>
Message<br>
<textarea input name="msg" cols=40 rows=5> </textarea><br>
<input type="submit">
<br><br>
</form>
<?php
$msg = $_POST['msg'];
$dateposted = date("YmdHis");
$fp = fopen("$dateposted.txt", "w");
fwrite($fp,$title, $msg).' ';
fclose($fp);
?>
<?php
include "0end.php";
I think your Problem lies in the fopen and fwrite you are using.
fopen ("$dateposted.txt","w") will create you a file with the name $dateposted.txt. I think you rather want fopen($dateposted."txt","w").
Since the file isn't created, I would check the folder permissions of the destination folder and modify them if the user that runs the script, for example an apache on linux isn't allowed to write there. Or set the complete Destinationpath to be sure the file is stored in the correct destionation.
Another thing regarding the fwrite. From what I know, fwrite accepts 2 Parameters. File and String. The third possible parameter is the maximum length of added bytes. In your case I would call fwrite once for the title and once for the message. Furthermore the string concatenation on the fwrite looks wrong to me, since I assume the concated String should be in the file you would need to write for example fwrite($fp, $title.' ');
Related
OK guys, this is my first post. I have searched all over and spent countless hours and I am still stuck so I asking for help with this relatively easy PHP module.
basically in a nutshell, what I want to do is upload a text file into an uploads directory, and have PHP process the file and perform a string function that will add HTML BREAK TAGS to the end of each line and then save this output to file. I have learned how to echo the formatted text into the browser and it appears the way it should as formatted html, but it doesn't work to write back to the file.
here is the code;
<?php
$form = <<<EOD
<form enctype="multipart/form-data" action="" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000000" />
Choose an file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
EOD;
echo $form;
$target_path = "uploads/"; //SETS THE UPLOAD DIRECTORY
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); // GETS FILEPATH OF UPLOAD FOR OPENING/PROCESSING
$uploadfile = basename($_FILES['uploadedfile']['name']); //GETS FILENAME OF THE UPLOADED FILE IN CASE ITS NEEDED.
//PROCESSING - MOVES TMP FILE INTO TARGET DIRECTORY. NEED STRING FUNCTIONS APPLIED TO ADD <BR/> AT END OF EACH LINE.
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
$file = fopen($target_path, "r");
while(!feof($file))
{
$line = fgets($file); //READS EACH LINE
// STRING PROCESSING PART -- SHOULD I USE str_replace, substr_replace, nl2br, or str_pad ??
..........CODE GOES HERE............PLEASE HELP ME CHOOSE THE RIGHT CODING HERE...THANKS!!! SORRY FOR THE PSEUDOCODE!
/* EXAMPLE SCRIPT:
$line2 = str_replace("\n", "<br />\n", $line);
// THIS WORKS -- GREAT FOR OUTPUTTING FORMATTED HTML INTO BROWSER
echo $line2;
// FOR NICE VIEWING BUT STILL CANNOT GET FORMATTED
// HTML TO SAVE TO FILE USING FWRITE() ...
*/
fwrite($file, $newstr);
} //CLOSES WHILE
fclose($file); //CLOSES FILE HANDLE
} //CLOSES IF
?>
too many late nights, open windows, and troubleshooting steps to make my brain want to explode! When I know one of you guys can knock this out in 2 minutes!!!
I notice I keep getting this error log:
PHP Warning: Module 'mailparse' already loaded in Unknown on line 0
There are a couple of problems with what you're doing currently. First, you've opened the file for reading only, but even if you change that, you won't be able to just replace a line with a longer line in the same file. In order for your current approach to work, you'll need to open a second file for writing, and add the modified lines into the second file as you go. But as long as the files aren't very large, you should be able to create the modified file more simply:
file_put_contents($output_file, nl2br(file_get_contents($input_file)));
Incidentally, the mailparse warning does not appear to be related to the code you've posted here.
EDIT
I have this PHP code now:
$name = isset($_POST['image_file']) ? $_POST['image_file'] : '';
$date_added = date ("F d Y H:i:s.", filectime(basename($_FILES["image_file"]["tmp_name"])));
$path = "../uploads/".basename($_FILES["image_file"]["name"]);
$patient_id = $_POST['patient_id'];
$remark = $_POST['remark'];
//$date_added = $_POST['date_added'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
...
And the result of any file (except images) is: January 01 1970 01:00:00.
And when I try to upload an image it send me to an empty page where no errors are shown and the image isn't uploaded into folder.
END EDIT
I need to add scanned images into patient file using this form:
<form enctype="multipart/form-data" id="myForm" name="myForm" action="add_scan.php" method="post">
<div class="box-body" id="toggleDiv">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label style="float:left">File Description</label>
<input type="text" class="form-control" id="remark" name="remark"/>
<label style="float:left">Upload File</label>
<input type="file" class="form-control" id="image_file" name="image_file"/>
<input type="hidden" class="form-control" id="patient_id" name="patient_id" value="<?php echo $patient_id ?>"/>
</div><!-- /.form-group -->
<button type="submit" class="btn btn-warning" id="add_scan" name="add_scan">Add File</button>
</form>
Usually, my client add a date but sometimes he forgot in what date the image is taken. So I need to access the system date of the image.
I tried the following:
Add_scan.php page:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once('../include/global.php');
//session_start();
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
if(isset($_POST['add_scan']))
{
try
{
$name = isset($_POST['image_file']) ? $_POST['image_file'] : '';
$path = "../uploads/".basename($_FILES["image_file"]["name"]);
$date_added = date ("Y-m-d", filectime(basename($_FILES["image_file"]["name"])));
$patient_id = $_POST['patient_id'];
$remark = $_POST['remark'];
//$date_added = $_POST['date_added'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
move_uploaded_file($_FILES["image_file"]["tmp_name"], $path.$name);
$sqlUpd = "INSERT INTO scan_image(id_logged, patient_id, image_file, remark, date_added)
VALUES(:id_logged, :patient_id, :image_file, :remark, :date_added)";
$stmt = $conn->prepare($sqlUpd);
$stmt->bindValue(':id_logged', $id_logged);
$stmt->bindValue(':patient_id', $patient_id);
$stmt->bindValue(':image_file', $path);
$stmt->bindValue(':remark', $remark);
$stmt->bindValue(':date_added', $date_added);
$stmt->execute();
header("Location: patients.php?patient=".$patient_id);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Where I used this line: $date_added = date ("Y-m-d", basename($_FILES["image_file"]["name"])); to access the date according to PHP PDO documentations in this link.
But nothing added and I only see a blank page of my add_scan.php code and it is not redirected to patient.php page.
SOLUTION:
Because you're uploading a file the date on the system is going to be the upload date. Your solution if it is an image file is to read the image file meta-data, which is a bit of a pain because there are multiple types of meta data for each type of image file and finding the one you want is not in itself efficient.
I think Imagick PHP plugin does this but I can't vouch for the quality or worth of this/these functions.
To clarify further:
When you upload a file from a computer to a server, the server will hold NO filesystem information about the file on the computer.
Meta Data is data about something, and typically data about a file (such as its created date) is not stored within the file itself as a standard, but in the operatng system that stores the file contents.
The server which recieves your uploaded file can not tell you when the file was saved on to the computer it came from, or anything else filesystem related because the server has only been given the file contents data, not the file systems metadata about storage and modification (etc).
If this information is available from within a file, it is stored in what is called "MetaData" inside the file itself, and to reach these bits of metadata you need to use something like Imagick for images .
Alternatively, if you simply want the date the file was added to this system you can read that in this Stack Answer.
NOTES:
You want filectime.
After you header add an exit to cease execution.
You have a $_POST and a $_FILES value with the same name, you are using $_POST['upload_file'] and $_FILES['upload_file'] I'm not sure if this will break your script but the POST values of this will be empty unless you have another field in your form with the same name which is clearly bad practise.
Your require and/or include do not need to be in brackets.
It is also bad practise for pathinfo to be given a relative path, you should as much as possible give PHP functions absolute paths, using $_SERVER['DOCUMENT_ROOT'] or other magical constants.
Remove basename in filectime, it's unneed.
it looks like $path.$name should infact be $path.$name.$ext when using move_uploaded_file
Your problem (from your comment) is that you are looking for the time of a string that is not the file. Replace $_FILES["image_file"]["name"] in you filectime call to instead be ['tmp_name'] because this is the location address of where the uploaded file is (temporarily) stored.
The name array value in $_FILES simply tells you the name of the file from the place it was uploaded from.
BUT This time will simply only tell you the uploaded time.
Your Error log should have shown you that your filectime is tying to get the data from a non-file entity.
filemtime reports the files modification time, not its creation time (this is not available on most operating systems).
That's not the PDO documentation.
The file uploaded is a copy of the data held in the original file - so the mtime you see on the copy will always be about 'now'.
The user can see the modification time on their local machine. If they can't provide this information then the only option would be to take a backup of the files, restore it on your server (using an appropriate method which does not change the mtime, e.g. untar as root) then load the files directly from there rather than uploading over the web.
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>
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);
}
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.