How to write in between content of existing file?
I tried to use fseek() to seek a new position and write the new content, but it replaces old content to the new string after seek position.
My aim is to put new contents after 5 characters of existing file.
Old content: AAAAABBBBB, desired content: AAAAAnewcontentBBBBB
$file_handler = fopen('putty.log','w');
$new_content = 'this is new content';
fseek($file_handler,5);
echo ftell($file_handler); //5
fwrite($file_handler,$new_content);
old content replaced with NULLNULLNULLNULLNULLthis is new content
You can't do it that way.
You can only truncate the content with ftruncate and write later the old content
A not so clean example
<?php
$file_handler = fopen('putty.log','rb+');
$new_content = 'this is new content';
fseek($file_handler,5);
$restOfContent = fread($file_handler,filesize('putty.log')-5);
ftruncate($file_handler,5);
fseek($file_handler,5);
echo ftell($file_handler); //5
fwrite($file_handler,$new_content);
fwrite($file_handler,$restOfContent);
fclose($file_handler)
Load contents to variable using file_get_contents().
Do this on your buffer.
Save your contents to this file using file_put_contents();
if you're using fseek() to write data to a file, remember to open the file in "r+"
mode, example:
$fp=fopen($filename,"r+");
Writing in the middle of the file won't cause it to stretch and push the content forward (like when inserting content in a text editor) but rather to overwrite the content at the position you start writing.
What you need to do is:
read the first part of the old data until the point where you need to write the new content & write that part to a temporary file.
write the new content to the temporary file (the stuff you wish to add).
read the rest of the content from the old file & write it to the temporary file.
delete the old file.
rename the temporary file to the name of the old file.
Example:
$original_file_name = '/tmp/putty.log';
$temp_file_name = '/tmp/putty.tmp';
$temp_file = fopen( $temp_file_name, 'w' );
$file_handler = fopen( $original_file_name, 'r' );
$old_data_size = 5;
fwrite( $temp_file, fread( $file_handler, $old_data_size ) );
$new_content = 'this is new content';
fwrite( $temp_file, $new_content, strlen( $new_content ) );
fwrite( $temp_file, fread( $file_handler, filesize( $original_file_name ) - $old_data_size ) );
fclose( $file_handler );
fclose( $temp_file );
unlink( $original_file_name );
rename( $temp_file_name, $original_file_name );
Make sure that putty.log has read/write permissions for the user used by your webserver (apache/lighttpd etc.) process or that it's accessible for everyone (not recommended).
Related
I'm using this jquery plugin to capture or draw a signature.
http://keith-wood.name/signature.html
And FPDF php plugin to generate pdf
Now I must include signature into pdf...
With FPDF I can insert an image, but I have problem exporting signature to jpeg/png (I don't even know if is possibile)
How I can do this
On the page you gave link to (this one) in Save/Restore tab you have possibility to save it as a base64 encoded picture (jpeg or png).
So you can use that and to save base64 encoded picture as a file here is a solution
The problem is that data:image/png;base64, is included in the encoded contents. This will result in invalid image data when the base64 function decodes it. Remove that data in the function before decoding the string, like so.
function base64_to_jpeg($base64_string, $output_file) {
// open the output file for writing
$ifp = fopen( $output_file, 'wb' );
// split the string on commas
// $data[ 0 ] == "data:image/png;base64"
// $data[ 1 ] == <actual base64 string>
$data = explode( ',', $base64_string );
// we could add validation here with ensuring count( $data ) > 1
fwrite( $ifp, base64_decode( $data[ 1 ] ) );
// clean up the file resource
fclose( $ifp );
return $output_file;
}
To clarify variable $base64string is a string that in your case is generated by plugin, and $output_file is a filpath where to save the picture.
So:
// Setup mail class, recipients and body
$mailer->AddAttachment('/home/mywebsite/public_html/file.zip', 'file.zip');
The AddAttachment function has four arguments:
AddAttachment(PATH_TO_FILE, FILENAME, ENCODING, HEADER_TYPE)
I used to use xmail() and when I added a attachment here, I passed the filename and the content, that should be in it.
Like this:
$xmail->addAttachment('myamazingfile.pdf', $content);
How can I make it work the same way, so when i call AddAttachment() from the PHPmailer class, I can either pass the same or something like it, so I dont need to have a actual file on my server to send?
AddStringAttachment($string,$filename,$encoding,$type)
eg
$mail = new PHPMailer();
$mail->AddStringAttachment($string,$filename,$encoding,$type);
https://phpmailer.github.io/PHPMailer/classes/PHPMailer-PHPMailer-PHPMailer.html#method_addStringAttachment
since that AddAttachment() function is expecting a path rather than byte data, you should do a php convert to temp file function and then pass that path string into your function
$prefix = 'ConvertMediaArgs_'.time().'_';
$tempfile = tempnam( $this->tempdir, $prefix );
// Args file create failure: kill script with TEMPFILEFAIL error
if($tempfile === false) {
die('file could not be created');
}
// Write args as Key=Val (\n) to file
$fullpath = $this->tempdir.$tempfile;
$content = $someContent // <---------------- this is your file's data
$handle = fopen( $tempfile, "w");
fwrite( $handle, $content );
// $fullpath is the path you wanna pass to your function
$xmail->addAttachment( $fullpath, $content );
Im trying to update a text file using the code below:
$filename = "flat-file-data.txt"; // File which holds all data
$rowToUpdate = $_REQUEST['number']; // This is line need to be updated
$newString = $_REQUEST['line'].'\r\n'; // This is what you want to replace it with
$arrFp = file( $filename ); // Open the data file as an array
// Replace the current element in array which needs to be updated with new string
$arrFp[$rowToUpdate-1] = $newString;
$numLines = count( $arrFp ); // Count the elements in the array
$fp = fopen( $filename, "w" ); // Open the file for writing
for($i=0; $i < $numLines; $i++)
{
fwrite($fp, $arrFp[$i]);
}
fclose( $fp ); // Close the file
as you can see from the above codes, it will update the line 1 with the data from $newString and it should be able to create a new line after each line with this '\r\n'.
Unfortunately, it doesnt create a new line, it just goes along with the same line or in the current line like for example 'this is the firstline\r\nthis is the second line'. Is there any accurate way that I could make it in a new line like
this is the firstline
this is the secondline
and so on and so forth?
You have to put \r\n in double quotes:
$newString = $_REQUEST['line']."\r\n";
So:
// Setup mail class, recipients and body
$mailer->AddAttachment('/home/mywebsite/public_html/file.zip', 'file.zip');
The AddAttachment function has four arguments:
AddAttachment(PATH_TO_FILE, FILENAME, ENCODING, HEADER_TYPE)
I used to use xmail() and when I added a attachment here, I passed the filename and the content, that should be in it.
Like this:
$xmail->addAttachment('myamazingfile.pdf', $content);
How can I make it work the same way, so when i call AddAttachment() from the PHPmailer class, I can either pass the same or something like it, so I dont need to have a actual file on my server to send?
AddStringAttachment($string,$filename,$encoding,$type)
eg
$mail = new PHPMailer();
$mail->AddStringAttachment($string,$filename,$encoding,$type);
https://phpmailer.github.io/PHPMailer/classes/PHPMailer-PHPMailer-PHPMailer.html#method_addStringAttachment
since that AddAttachment() function is expecting a path rather than byte data, you should do a php convert to temp file function and then pass that path string into your function
$prefix = 'ConvertMediaArgs_'.time().'_';
$tempfile = tempnam( $this->tempdir, $prefix );
// Args file create failure: kill script with TEMPFILEFAIL error
if($tempfile === false) {
die('file could not be created');
}
// Write args as Key=Val (\n) to file
$fullpath = $this->tempdir.$tempfile;
$content = $someContent // <---------------- this is your file's data
$handle = fopen( $tempfile, "w");
fwrite( $handle, $content );
// $fullpath is the path you wanna pass to your function
$xmail->addAttachment( $fullpath, $content );
Assume, I've got MSWord file source.doc with next content "Content of Microsoft Word file".
For example, I'd like to open it via PHP and replace word "Microsoft" to "Openoffice" and save the result into result.doc.
Here is the code using preg_replace:
$content = file_get_contents( SOMEPATH . '/source.doc' );
$new_content = preg_replace( '/Microsoft/i', 'Openoffice', $content );
file_put_contents( SOMEPATH . '/target.doc', $new_content );
Or using str_replace:
$content = file_get_contents( SOMEPATH . '/source.doc' );
$new_content = str_replace( 'Microsoft', 'Openoffice', $content );
file_put_contents( SOMEPATH . '/target.doc', $new_content );
None of them doesn't work. Code runs without any exceptions, but target.doc is the same as source.doc. Replacement not performs.
I've tried a lot of different reciepts, such as regular expression modificators, iconv and so on, but nothing helps.
var_dump of $content shows raw structure of source.doc that is full of unusual characters and as I suppose some of it stops str_replace or preg_replace scanning. Can't figure out which char is it and what should I do if I'll find it.
var_dump of $new_content is identical to $content.
Thanks forward for any help!
If you have a DOCX file you need to replace something in, its basically a zipped up xml archive.
Here's an example on how to replace the word "Microsoft" with "Openoffice" in a DOCX file.
$zip = new ZipArchive;
//This is the main document in a .docx file.
$fileToModify = 'word/document.xml';
$wordDoc = "Document.docx";
if ($zip->open($wordDoc) === TRUE) {
//Read contents into memory
$oldContents = $zip->getFromName($fileToModify);
//Modify contents:
$newContents = str_replace('Microsoft', 'Openoffice', $oldContents);
//Delete the old...
$zip->deleteName($fileToModify);
//Write the new...
$zip->addFromString($fileToModify, $newContents);
//And write back to the filesystem.
$return =$zip->close();
If ($return==TRUE){
echo "Success!";
}
} else {
echo 'failed';
}
Hope this helps!
I think this is what you are looking for :) http://phpword.codeplex.com/ since doc files are not ordinary text files (try opening one with notepad..you'll get my point)