How to format data when writng to txt file with php? - php

This is my code:
<?php
//check if the form allows user input to be extracted
if(isset($_POST['email']))
//if so loop begins
{
//creates a variable called $data that contains the user input for a particular input name from the form
//writes to txt file
$myfile = fopen("form.txt", "w") or die("Unable to open file!");
$email = "Email: ";
fwrite($myfile, $email);
fclose($myfile);
//appends to txt file
$data=$_POST['email'];
//creates a variable called $fp that contains the function fopen which opens a file called form.txt
$fp = fopen('form.txt', 'a');
//initiates the function fwrite which displays the user input in the txt file
fwrite($fp, $data); //when echo in html use div center tag
//closes txt file with the function fclose
fclose($fp);
}
if(isset($_POST['title']))
{
$data=$_POST['title'];
$fp = fopen('form.txt', 'a');
fwrite($fp, $data);
fclose($fp);
}
if(isset($_POST['date']))
{
$data=$_POST['date'];
$fp = fopen('form.txt', 'a');
fwrite($fp, $data);
fclose($fp);
}
if(isset($_POST['link']))
{
$data=$_POST['link'];
$fp = fopen('form.txt', 'a');
fwrite($fp, $data);
fclose($fp);
}
?>
I want to know how to write the user input to the txt file in php with a space between the header and the input and a linebreak after every one. Whenever I try to use the 'w' more than once the text from the first time it was used is not displayed.

Whenever I try to use the 'w' more than once the text from the first time it was used is not displayed.
Referring to the manual fopen
'w' - write mode will create a new file or reset the pointer to the beginning of the file (overwrite the existing content)
'a' - append mode will set the pointer to the end of the file (add content to the end)
So, that's why you're seeing that behaviour.
With regards to
I want to know how to write the user input to the txt file in php with a space between the header and the input and a linebreak after every one.
I'm unclear from your code and comments what exactly you consider to be the Header, Input and "each one". You code refers to a non-existent loop.
So, with the assumption that this actually all just executes in one go and "header is $email and that "input" and "each one" is every instance of $data. Your code should look something more like the following.
(Caveat: I only had a couple of minutes so it could be improved upon with string formatting and such, and I am assuming some php versioning)
Use PHP_EOL for cross-platform end of line. Refer When do I use the PHP constant "PHP_EOL"? for more information.
Again an assumption that this is all one post action and that you want a clean file for each email. If so, from the code you've provided, there appears no need to open the file multiple times.
if( isset( $_POST['email'] ) ) {
$myfile = fopen("form.txt", "w") or die("Unable to open file!");
fwrite($myfile,
"Email: " . $_POST['email'] . PHP_EOL .
( isset( $_POST['title'] ) ? ( $_POST['title'] . PHP_EOL ) : '' ) .
( isset( $_POST['date'] ) ? ( $_POST['date'] . PHP_EOL ) : '' ) .
( isset( $_POST['link'] ) ? ( $_POST['link'] . PHP_EOL ) : '' ) .
);
fclose($myfile);
}
However, if all fields are not captured at the same time, and there is no need for ordering of the entries to be relevant in the file, nor for it to be "clean" then just use append mode instead of write mode.
$myfile = fopen("form.txt", "a") or die("Unable to open file!");
fwrite($myfile,
( isset( $_POST['email'] ) ? ( "Email: " . $_POST['email'] . PHP_EOL ) : '') .
( isset( $_POST['title'] ) ? ( $_POST['title'] . PHP_EOL ) : '' ) .
( isset( $_POST['date'] ) ? ( $_POST['date'] . PHP_EOL ) : '' ) .
( isset( $_POST['link'] ) ? ($_POST['link'] . PHP_EOL ) : '' )
);
fclose($myfile);

Related

PHP Script doesn't create XML file

I am having some trouble with a PHP script. I am trying to do two things:
Create an XML file in /usr/local/ezreplay/data/XML/ directory and add contents to it using inputs passed to it from a HTML form;
Upload a PCAP file which is included in the submitted HTML form.
Here is my PHP (apologies it is a little long but I believe all of it is relevant here):
<?php
// Check if the 'expirydate' input is set
if (isset($_POST['expirydate'])) {
// Convert the input string to a timestamp using 'strtotime'
$timestamp = strtotime($_POST['expirydate']);
// Format the timestamp as a 'mm/dd/yyyy' string using 'date'
$expirydate = date('m/d/Y', $timestamp);
}
// Check if all required POST variables are set
if ( isset($_POST['destinationip']) && isset($_POST['destinationport']) && isset($expirydate) && isset($_POST['multiplier']) && isset($_POST['pcap']) ) {
// Set the path for the XML file
$path = '/usr/local/ezreplay/data/XML/' . trim($_POST['destinationip']) . ':' . trim($_POST['destinationport']) . ':' . $expirydate . ':' . trim($_POST['multiplier']) . ':' . trim($_POST['pcap']) . '.xml';
// Initialize the contents of the XML file
$contents = "";
// Open the XML file in append mode
if ( $fh = fopen($path,"a+") ) {
// Add the opening 'config' tag to the XML file
$contents .= '<config>';
// If the 'destinationip' and 'destinationport' POST variables are not empty, add a 'destination' tag to the XML file
if ( trim( $_POST['destinationip'] ) != "" && trim( $_POST['destinationport'] ) != "" ) {
$contents .= "\n" . '<destination>' . $_POST['destinationip'] . ':' . $_POST['destinationport'] . '</destination>';
}
// If the 'multiplier' POST variable is not empty, add a 'multiplier' tag to the XML file
if ( trim( $_POST['multiplier'] ) != "" ) {
$contents .= "\n" . '<multiplier>' . $_POST['multiplier'] . '</multiplier>';
}
// If the 'pcap' POST variable is not empty, add a 'pcap' tag to the XML file
if ( trim( $_POST['pcap'] ) != "" ) {
$contents .= "\n" . '<pcap>/usr/local/ezreplay/data/PCAP/' . $_POST['pcap'] . '</pcap>';
// Add default tags to XML config file to ensure the pcap does not fail and loops continuously until expiration date hits
$contents .= "\n" . '<loop>0</loop>';
$contents .= "\n" . '<nofail>true</nofail>';
}
// Add the closing 'config' tag to the XML file
$contents .= "\n" . '</config>';
// Write the contents to the file
if ( fwrite( $fh, $contents ) ) {
// Success
} else {
echo "The XML config could not be created";
}
// Close the file
fclose($fh);
}
}
// Set the target directory and file name
$target_dir = "/usr/local/ezreplay/data/PCAP/";
$basename = basename($_FILES["pcap"]["name"]);
$target_file = $target_dir . $basename;
// Check if the file has a pcap extension
$allowedExtensions = array('pcap');
$basenameWithoutExt = null;
foreach ($allowedExtensions as $allowedExtension) {
if (preg_match('#\\.' . $allowedExtension . '$#',$basename)) {
$basenameWithoutExt = substr($basename,0,-1 - strlen($allowedExtension));
break;
}
}
// Accept only .pcap files
if (is_null($basenameWithoutExt)) {
echo "Sorry, only .pcap files are allowed. Please try creating your Packet Replay again using a .pcap file.";
exit;
}
// Check if the file already exists
if (file_exists($target_file)) {
echo "The Packet Replay could not be started, the PCAP is already running.";
exit;
}
// Try to upload the file
if (move_uploaded_file($_FILES["pcap"]["tmp_name"], $target_file)) {
// Success
} else {
echo "Sorry, there was an error uploading your file.";
exit;
}
// Start the Packet Replay
$command = '/usr/local/ezreplay/bin/startreplay.sh ' . $path;
system($command);
echo "The Packet Replay has been started.";
?>
Now the file upload is working and I can see the final echo message being returned in my browser however the XML file is never created. I have changed the directory ownership to the apache user and even chmod 777 to eliminate any permissions issues but it still doesn't create the file.
Any ideas why this is not working? The PHP and apache error logs don't show any issues and as I mentioned the script seems to be working to a degree as the file upload takes place perfectly.
Thanks!
I think the file is not being created due to "/" in the filename. As mentioned at Allowed characters in filename
I managed to fix this with the following edits.
<?php
// Set the target directory and file name
$target_dir = "/usr/local/ezreplay/data/PCAP/";
$basename = basename($_FILES["pcap"]["name"]);
$target_file = $target_dir . $basename;
// Check if the file has a pcap extension
$allowedExtensions = array('pcap');
$basenameWithoutExt = null;
foreach ($allowedExtensions as $allowedExtension) {
if (preg_match('#\\.' . $allowedExtension . '$#',$basename)) {
$basenameWithoutExt = substr($basename,0,-1 - strlen($allowedExtension));
break;
}
}
// Accept only .pcap files
if (is_null($basenameWithoutExt)) {
echo "Sorry, only .pcap files are allowed. Please try creating your Packet Replay again using a .pcap file.";
exit;
}
// Check if the file already exists
if (file_exists($target_file)) {
echo "The Packet Replay could not be started, the PCAP is already running.";
exit;
}
// Try to upload the file
if (move_uploaded_file($_FILES["pcap"]["tmp_name"], $target_file)) {
//Success
} else {
echo "Sorry, there was an error uploading your file.";
exit;
}
// Check if the 'expirydate' input is set
if (isset($_POST['expirydate'])) {
// Convert the input string to a timestamp using 'strtotime'
$timestamp = strtotime($_POST['expirydate']);
// Format the timestamp as a 'mm-dd-yyyy' string using 'date'
$expirydate = date('m-d-Y', $timestamp);
}
// Check if 'destinationip', 'destinationport', 'multiplier' and 'pcap' required POST variables are set
if (isset($_POST['destinationip']) && isset($_POST['destinationport']) && isset($_POST['multiplier'])) {
// Set the filename and path for the XML file
$file = '/usr/local/ezreplay/data/XML/' . trim($_POST['destinationip']) . ':' . trim($_POST['destinationport']) . ':' . trim($_POST['multiplier']) . ':' . $expirydate . ':' . $_FILES["pcap"]["name"] . '.xml';
// Initialize the contents of the XML file
$contents = "";
// Add the opening 'config' tag to the XML file
$contents .= '<config>';
// If the 'destinationip' and 'destinationport' POST variables are not empty, add a 'destination' tag to the XML file
if (trim($_POST['destinationip']) != "" && trim($_POST['destinationport']) != "") {
$contents .= "\n" . '<destination>' . $_POST['destinationip'] . ':' . $_POST['destinationport'] . '</destination>';
}
// If the 'multiplier' POST variable is not empty, add a 'multiplier' tag to the XML file
if (trim($_POST['multiplier']) != "") {
$contents .= "\n" . '<multiplier>' . $_POST['multiplier'] . '</multiplier>';
}
// If the 'pcap' POST variable is not empty, add a 'pcap' tag to the XML file
if (trim($_FILES["pcap"]["name"]) != "") {
$contents .= "\n" . '<pcap>/usr/local/ezreplay/data/PCAP/' . $_FILES["pcap"]["name"] . '</pcap>';
}
// Add default tags to XML config file to ensure the pcap does not fail and loops continuously until expiration date hits
$contents .= "\n" . '<loop>0</loop>';
$contents .= "\n" . '<nofail>true</nofail>';
// Add the closing 'config' tag to the XML file
$contents .= "\n" . '</config>';
// Write the contents to the file
if (file_put_contents($file, $contents)) {
// Success
} else {
echo "The XML config could not be created";
}
}
// Start the Packet Replay
$command = '/usr/local/ezreplay/bin/startreplay.sh ' . $path;
system($command);
echo "The Packet Replay has been started.";
?>

Determine if a PDF is Corrupt

How can I determine if a PDF file is corrupt (not openable) in PHP? I have downloaded thousands of PDFs via CURL and a small number are incomplete.
$part = 'pdffile.pdf';
$escPath = str_replace( " ", "\\ ", escapeshellcmd( $part ) );
$out = shell_exec( 'pdfinfo ' . $escPath . ' 2>&1' );
if( $out != null && !preg_match( '~Error~i', $out ) )
echo "GOOD: $part\n";
else
echo "CORRUPT: $part\n";
I can only find a way to do this via the command line. The second line is required to escape file paths.

Adding Text to End of the File PHP [duplicate]

This question already has answers here:
Need to write at beginning of file with PHP
(10 answers)
Closed 9 years ago.
I've got this PHP script:
<?php
if ('POST' === $_SERVER['REQUEST_METHOD'] && ($_POST['title'] != 'Title') && ($_POST['date'] != 'Date'))
{
$fileName = 'blog.txt';
$fp = fopen('blog.txt', 'a');
$savestring = PHP_EOL . "<h2><center><span>" . $_POST['title'] . "</span></center></h2>" . "<div class=fright><p><em>|<br><strong>| Posted:</strong><br>| " . $_POST['date'] . "<br>|</p></em></div></p></em>" . "<p><em>" . $_POST['paragraph'] . "</em></p>" . PHP_EOL . "<hr>";
fwrite($fp, $savestring);
fclose($fp);
header('Location: http://cod5showtime.url.ph/acp.html');
}
?>
It works perfectly but it has a slight problem. The text is added at the end of the file. Is there a way to make it add the $savestring at the beginning of the text file ? I'm using this for my blog and I just noticed this slight problem.
You need to use the correct writing mode:
$fp = fopen('blog.txt' 'c');
http://us1.php.net/manual/en/function.fopen.php
You can you use
$current = file_get_contents($file);
// Append a data to the file
$current .= "John Smith\n";
file_put_contents($file, $current, FILE_APPEND | LOCK_EX);

PHP lock text file for editing?

I've got a form that writes its input to a textfile.
Would it be possible to lock a text file for editing, and perhaps give a friendly message "the file is edited by another user, please try again later."
I'd like to avoid conflicts if the file has multiple editors at the same time.
Here's how the entry is currently added.
$content = file_get_contents("./file.csv");
$fh = fopen("./file.csv", "w");
fwrite($fh, $date_yy . '-' . $date_mm . '-' . $date_dd . '|' . $address . '|' . $person . '|' . $time_hh . ':' . $time_mm);
fwrite($fh, "\n" . $content);
fclose($fh);
Any thoughts?
You can use flock() function to lock the file. For more see this
Something like:
<?php
$content = file_get_contents("./file.csv");
$fp = fopen("./file.csv", "w"); // open it for WRITING ("w")
if (flock($fp, LOCK_EX))
{
// do your file writes here
fwrite($fh, $date_yy . '-' . $date_mm . '-' . $date_dd . '|' . $address . '|' . $person . '|' . $time_hh . ':' . $time_mm);
fwrite($fh, "\n" . $content);
fclose($fh);
flock($fh, LOCK_UN); // unlock the file
}
?>
In order of desirability:
Use a database.
Use more than one text file.
Use locks:
eg:
$lockwait = 2; // seconds to wait for lock
$waittime = 250000; // microseconds to wait between lock attempts
// 2s / 250000us = 8 attempts.
$myfile = '/path/to/file.txt';
if( $fh = fopen($myfile, 'a') ) {
$waitsum = 0;
// attempt to get exclusive, non-blocking lock
$locked = flock($fh, LOCK_EX | LOCK_NB);
while( !$locked && ($waitsum <= $lockwait) ) {
$waitsum += $waittime/1000000; // microseconds to seconds
usleep($waittime);
$locked = flock($fh, LOCK_EX | LOCK_NB);
}
if( !$locked ) {
echo "Could not lock $myfile for write within $lockwait seconds.";
} else {
// write out your data here
flock($fh, LOCK_UN); // ALWAYS unlock
}
fclose($fh); // ALWAYS close your file handle
} else {
echo "Could not open $myfile";
exit 1;
}
You can use PHP's flock function to lock a file for writing, but that lock won't persist across web requests and doesn't work on NFS mounts (at least in my experience).
Your best be may be to create a token file in the same directory, check for its existence and report an error if it exists.
As with any locking scheme, you're going to have race conditions and locks that remain after the operation has completed, so you'll need a way to mitigate those.
I would recommend creating a hash of the file before editing and storing that value in the lock file. Also send that hash to the client as part of the edit form (so it comes back as data on the commit request). Before writing, compare the passed hash value to the value in the file. If they are the same, commit the data and remove the lock.
If they are different, show an error.
You could try flock — Portable advisory file locking ?
http://php.net/manual/en/function.flock.php
I would just use a simple integer or something like that.
$content = file_get_contents("./file.csv");
$fh = fopen("./file.csv", "w");
$status = 1;
...
if($status == 1){
fwrite($fh, $date_yy . '-' . $date_mm . '-' . $date_dd . '|' . $address . '|' . $person . '|' . $time_hh . ':' . $time_mm);
fwrite($fh, "\n" . $content);
fclose($fh);
$status = 0;
}
else
echo "the file is edited by another user, please try again later.";
Is that what you mean?

Mercury mail and php email creation script

I need help creating a script or program that can add users to my mercury mail server when they sign up on a form. I'm using a basic php post form, it does create all the necessary files to run the account but when I open mercury mail the new user account has not been added to the accounts list. And the new account cannot sign in.
Please assist me in creating a client email signup script or program so that my clients can easily create an email on my server for free.
Link to the form code: http://pastebin.com/bEtv4eck
Link to the php post code: http://pastebin.com/rwBJatap
P.S. I have the script working to where it can create the new user and everything, but it won't allow a login unless the email server is restarted. Any way to fix this?
Try using the RELOAD USERS after making the changes to the pmail.usr and mail, directories.
You need to also add user in the PMAIL.USR file
Try
const MERCURY_PATH = 'C:\Apache\xampp\MercuryMail';
$userFile = MERCURY_PATH . DIRECTORY_SEPARATOR . "PMAIL.USR";
$mailDir = MERCURY_PATH . DIRECTORY_SEPARATOR . "MAIL";
$newName = "Baba Konko";
$newUsername = "baba";
$newPassword = "pass";
$host = "localhost";
if (! is_writeable ( $userFile )) {
die ( "You don't have permission to Create new User" );
}
if (! is_writeable ( $mailDir )) {
die ( "You don't have permission to add mail folder" );
}
// Check if user exist
if (is_file ( $userFile )) {
$users = file ( $userFile );
foreach ( $users as $user ) {
list ( $status, $username, $name ) = explode ( ";", strtolower ( $user ) );
if (strtolower ( $newUsername ) == $username) {
die ( "User Already Exist" );
}
}
}
$userData = "U;$newUsername;$newName";
$fp = fopen ( $userFile, "a" );
if ($fp) {
fwrite ( $fp, $userData . chr ( 10 ) );
fclose ( $fp );
}
$folder = $mailDir . DIRECTORY_SEPARATOR . $newUsername;
if (! mkdir ( $folder )) {
die ( "Error Creating Folder" );
}
$pm = '# Mercury/32 User Information File' . chr ( 10 );
$pm .= 'POP3_access: ' . $newPassword . chr ( 10 );
$pm .= 'APOP_secret: ' . $newPassword . chr ( 10 );
$pmFile = $folder . DIRECTORY_SEPARATOR . 'PASSWD.PM';
file_put_contents ( $pmFile, $pm );

Categories