New line character not working in php - php

I am creating a log file for all api call in my application which is written in php (Symfony).
While creating log file I have used "\n" as new line characters but it's not working.
my code is -
$log = "\n Account: ".$Account."---ID: ".$ID;
$log .= "\n Params: ".$params."\n";
$log .= "\n response: ".$response."\n";
It gives me out put in one line, I also tried "\r\n" and "PHP_EOL" but it doesn't works.
How can I able to fix this issue?
Thanks

I think you should replace \n with <br>, but without space in the brackets

Below should work. And I am using this on my all projects to find the error
$contents = file_get_contents('text.txt'); // TO LOAD THE EXISTING CONTENTS OF ERROR LOG FILE
$contents .= PHP_EOL."\n Account: ".$Account."---ID: ".$ID; // CONCAT. ACCOUNT NUMBER
$contents .= PHP_EOL."\n Params: ".$params."\n"; // CONCAT. PARAMS
$contents .= PHP_EOL."\n response: ".$response."\n"; // CONCAT. RESPONSE
file_put_contents('text.txt', $contents, FILE_APPEND); // WRITING ENIRE LOG BACK INTO LOG FILE

Related

using fopen to add some text after multiple appearance of a text

what I am trying to do is to create an installer for my world calendar in a script.
I need to make some changes to one of the files in. the main script.
I have managed to use the code above to make the change that I want. the problem is that there is more than one occurrence. how do I make the same change every time that the string is repeated. it could happened 0 or 1 or 2 times
$target_line='$second = (int)substr($raw_date, 17, 2);';
$lines_to_add= '$raw_date = translate_from_gregorian($raw_date);'. PHP_EOL.
'$year = (int)substr($raw_date, 0, 4);'. PHP_EOL.
'$month = (int)substr($raw_date, 5, 2);'. PHP_EOL.
'$day = (int)substr($raw_date, 8, 2);'. PHP_EOL;
$config ='includes/functions/general.php';
$file=fopen($config,"r+") or exit("Unable to open file!");
$insertPos=0; // variable for saving //Users position
while (!feof($file)) {
$line=fgets($file);
if (strpos($line,$target_line)!==false) {
$insertPos=ftell($file); // ftell will tell the position where the pointer moved, here is the new line after //Users.
$newline = $lines_to_add;
} else {
$newline.=$line; // append existing data with new data of user
}
}
fseek($file,$insertPos); // move pointer to the file position where we saved above
fwrite($file, $newline);
fclose($file);
Read the entire file into a variable. Use str_replace() to make all the replacements. Then write the result back to the file.
$contents = file_get_contents($config);
$contents = str_replace($target_line, $target_line . PHP_EOL . $lines_to_add, $contents);
file_put_contents($config, $contents);

php - one time access by looking up serial in a .dat file

i've now written this short script.
It records a serial or token number, checks to see if its in a .dat file, and allows access if its present. Otherwise it denies access to the site.
It also removes the token from the file once it has been redeemed as it were.
However, when i add multiple tokes in the dat file, the code doesn work properly. It only works with a single entry. How would i make it work for multiple entries.
im thinking of maybe implementing some sort of array somewhere? or explode?
index.php
require_once "married.php";
session_start();
$url_request = (isset($_SERVER['HTTPS']) ? "https" : "http") .
"://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$ip = $_SERVER['REMOTE_ADDR'];
$token = substr($url_request,45);
$_SESSION["cookie"] = $token;
$tk = $_SESSION["cookie"];
$ips = array();
$page = file("urls.dat");
foreach($page as $line)
{
array_push($ips, $line);
}
if(in_array($tk, $ips))
{
//header("Location: mysite.co.uk");
echo "<title>My Site</title>Here is my site";
$file = fopen("ip_match.dat","a");
fwrite($file,$tk . " " . $ip . "\r\n");
fclose($file);
$oldMessage = $_SESSION["cookie"];
$deletedFormat = "";
$str=file_get_contents('urls.dat');
$str=str_replace("$oldMessage", "$deletedFormat",$str);
file_put_contents('urls.dat', $str);
exit;
} else {
echo ("<title>404 Not Found</title>
<h1>Not Found</h1>The requested URL was not found on this server.
<br>
<br>
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. test");
exit;
}
urls.dat
1089yht
url: http://mmmmmmmmmmmmm.co.uk/url/index.php?key=1089yht
ps. Happy Holidays all!
Look at JSON. You could do something like this:
$tokens = ['foo', 'bar'];
file_put_contents('urls.json', json_encode($tokens));
// and then you can decode it back
// returns ['foo', 'bar']
$decodedTokens = json_decode(file_get_contents('urls.json'));
If you still want to use simple text file, you could save every record at new line and then load line by line.
$tokens = [];
while(! feof($file)) {
$line = fgets($file);
// or save to array
$tokens[] = $line;
}
fclose($file);
try
$str = preg_replace("/{$oldMessage}/", $deletedFormat, $str, 1);
Instead of
$str=str_replace("$oldMessage", "$deletedFormat",$str);
Because: str_replace replaces everything.
preg_replace lets you limit how many replacements.

PHP - copy() fails on URL with curly braces/brackets

I'm having an issue with the copy() function in PHP.
I need to copy a remote URL that looks like: https://example.co.uk/{8d988e90-a325-4a1c-a340-a489166286b8}/{14409287-2c29-4b51-91e4-0891b5619659}/main/imgnew-(2).jpg, to my local drive.
Here is the part of my code that fails, along with some context for the $RemoteURL variable:
$replace = array('%7B', '%7D','%28','%29');
$entities = array('{', '}','(',')');
$RemoteURL = str_replace($entities, $replace, "https://example.co.uk/{8d988e90-a325-4a1c-a340-a489166286b8}/{14409287-2c29-4b51-91e4-0891b5619659}/main/imgnew-(2).jpg");
$PicName = "new.jpg"
if(copy($RemoteURL,"C:\Users\Me\Downloads\Pictures\" . $PicName)){
echo "<script>console.log(\"(" . $RemoteURL . ") copied to waiting.\")</script>";
} else {
echo "<p class='float red'>READ ERROR</p>";
}
However, this throws the error:
Warning: copy(https://example.co.uk/%7B8d988e90-a325-4a1c-a340-a489166286b8%7B/%7B14409287-2c29-4b51-91e4-0891b5619659%7B/main/imgnew-%282%29.jpg): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
What is it exactly I'm missing here, or what is it that PHP doesn't like about the URL itself?
Turns out the issue that was producing the error above was that I had an accented character that was problematic.
è was giving an error, which was fixed by creating a function that replaced certain parts:
function URLEncodeRules($string) {
$replacements = array('%C3%A9','%C3%A8');
$entities = array('é','è');
return str_replace($entities, $replacements, $string);
}
$RemoteURL = URLEncodeRules($CaptureRow['URL']);
if(copy($RemoteURL,"image.jpg")){
echo "Success!;
}
Try using url_encode();
Hope this will help you.
Thanks,

Writing a new and appending a file in PHP without erasing contents

How could one write a new line to a file in php without erasing all the other contents of the file?
<?php
if(isset($_POST['songName'])){
$newLine = "\n";
$songName = $_POST['songName'];
$filename = fopen('song_name.txt', "wb");
fwrite($filename, $songName.$newLine);
fclose($filename);
};
?>
This is what the file looks like
Current view
This is what is should look like Ideal View
Simply:
file_put_contents($filename,$songName.$newLine,FILE_APPEND);
Takes care of opening, writing to, and closing the file. It will even create the file if needed! (see docs)
If your new lines aren't working, the issue is with your $newLine variable, not the file append operations. One of the following will work:
$newLine = PHP_EOL; << or >> $newLine = "\r\n";
You have it set for writing with the option w which erases the data.
You need to "append" the data like this:
$filename = fopen('song_name.txt', "a");
For a complete explanation of what all options do, read here.
To add a new line to a file and append it, do the following
$songName = $_POST['songName'];
$filename = fopen('song_name.txt', "a+");
fwrite($filename, $songName.PHP_EOL);
fclose($filename);
PHP_EOL will add a new line to the file

Create directories and write files using PHP from a sendmail pipe to program

I have a script that reads emails (with attachments) from a pipe and I'm trying to save the attachment(s) to disk for further processing. I've cobbled together some code from a few sites and for the life of me I cannot get the files to save. I'm using 777 as the chmod value so permissions don't seem to be a problem but I wanted to know if maybe I'm limited to certain PHP commands when using the command line processor rather than the browser. Also, I've even hardcoded the "include" directories in the event the file is not executed from the directory where it is located. Any help would be greatly appreciated!
#!/usr/bin/php
<?php
//debug
#ini_set ("display_errors", "1");
#error_reporting(E_ALL);
include('/var/www/simple_html_dom.php');
//include email parser
require_once('/var/www/rfc822_addresses.php');
require_once('/var/www/mime_parser.php');
// read email in from stdin
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);
//create the email parser class
$mime=new mime_parser_class;
$mime->ignore_syntax_errors = 1;
$parameters=array(
'Data'=>$email,
);
$mime->Decode($parameters, $decoded);
//---------------------- GET EMAIL HEADER INFO -----------------------//
//get the name and email of the sender
$fromName = $decoded[0]['ExtractedAddresses']['from:'][0]['name'];
$fromEmail = $decoded[0]['ExtractedAddresses']['from:'][0]['address'];
//get the name and email of the recipient
$toEmail = $decoded[0]['ExtractedAddresses']['to:'][0]['address'];
$toName = $decoded[0]['ExtractedAddresses']['to:'][0]['name'];
//get the subject
$subject = $decoded[0]['Headers']['subject:'];
$removeChars = array('<','>');
//get the message id
$messageID = str_replace($removeChars,'',$decoded[0]['Headers']['message-id:']);
//get the reply id
//$replyToID = str_replace($removeChars,'',$decoded[0]['Headers']['in-reply-to:']);
//---------------------- FIND THE BODY -----------------------//
//get the message body
if(substr($decoded[0]['Headers']['content-type:'],0,strlen('text/plain')) == 'text/plain' && isset($decoded[0]['Body'])){
$body = $decoded[0]['Body'];
} elseif(substr($decoded[0]['Parts'][0]['Headers']['content-type:'],0,strlen('text/plain')) == 'text/plain' && isset($decoded[0]['Parts'][0]['Body'])) {
$body = $decoded[0]['Parts'][0]['Body'];
} elseif(substr($decoded[0]['Parts'][0]['Parts'][0]['Headers']['content-type:'],0,strlen('text/plain')) == 'text/plain' && isset($decoded[0]['Parts'][0]['Parts'][0]['Body'])) {
$body = $decoded[0]['Parts'][0]['Parts'][0]['Body'];
}
$my_dir = base64_encode($fromEmail);
shell_exec('mkdir -p /var/www/tmp/' . $my_dir . ' -m 777');
//mkdir($_SERVER['DOCUMENT_ROOT'] . "tmp/" . $my_dir, 0777, true);
$target_path = "var/www/tmp/" . $my_dir;
//chdir($target_path);
//------------------------ ATTACHMENTS ------------------------------------//
//loop through email parts
foreach($decoded[0]['Parts'] as $part){
//check for attachments
if($part['Content-Disposition'] == 'attachment'){
//format file name (change spaces to underscore then remove anything that isn't a letter, number or underscore)
$filename = preg_replace('/[^0-9,a-z,\.,_]*/i','',str_replace(' ','_', $part['FileName']));
// write the data to the file
$fp = fopen($target_path . "/" . $filename, 'w');
$written = fwrite($fp,$part['Body']);
fclose($fp);
//add file to attachments array
$attachments[] = $part['FileName'];
}
}
$html = file_get_html($attachments);
Update: Thanks for the informative response...I've been trying to figure out how to run from the command line. I'm getting some errors now, but they still don't make much sense:
PHP Notice: Undefined index: name in /var/www/catcher.php on line 38
PHP Notice: Undefined index: Content-Disposition in /var/www/catcher.php on line 80
PHP Notice: Undefined index: Content-Disposition in /var/www/catcher.php on line 80
PHP Notice: Undefined variable: attachments in /var/www/catcher.php on line 97
PHP Warning: file_get_contents(): Filename cannot be empty in /var/www/simple_html_dom.php on line 39
I have already specified the full include path to the other files and the smmta user should have read access as the /var/www/ directory is 755.
Using 0777 permissions on the mkdir command in your script does not matter at all if the user that the script is running under cannot write to your target directory. So, if this script is running as used sendmail for example, make sure that this user can write to /var/www/tmp.
Some debugging tips: Get a complete e-mail and save it to a file. Figure out what user this script runs as (e.g. sendmail). Then execute the script manually from the commandline and watch for errors. E.g:
sudo -u sendmail /path/to/script.php < /path/to/saved-email.eml
Make sure you have error reporting turned on etc.
Edit: Looking at the errors you posted, it seems that the mime decoder cannot properly parse your message the way you're expecting it. You appear not to be doing any error checking, so instead you get notices and warnings about undefined indexes.
Check in the input and output of the decoder. Make sure the message is decoded the way you expect it to be.

Categories