Cannot add line break to file - codeigniter

I am going to make function that writes all activity logs on my webpage. I'm using Codeigniter 3x as the framework. Here is the code.
public function writeLog($loc, $user, $activity) {
$this->load->helper('file');
date_default_timezone_set('Asia/Jakarta');
$files = FCPATH . '/assets/logs/logs-' . date('Y-m-d') . ".log";
$data = date("H:i:s") . " | User: " . $user . " from IP " . $loc . " do activity " . $activity . "\n";
write_file($files, $data, "a");
}
When I'm about to call the function by writeLog("192.168.1.3", "blackjack", "login"), it should be written like this:
15:20:22 | blackjack from IP 192.168.1.3 do activity login
But when I call that function again by writeLog("192.168.1.3", "blackjack", "logout"), the result like this:
15:20:22 | blackjack from IP 192.168.1.3 do activity login15:20:39 | blackjack from IP 192.168.1.3 do activity logout
I have inserted "\n" in the end of the $data, but new line isn't created.
Please help me

Different Operating systems use different characters for line endings. On unix-like systems the line ending is \n (called LF) while windows use \r\n (called CRLF). Most windows programs can display \n but not all.
Best way to go about is to use the PHP_EOL constant and let the server decide what line endings to use.
Extra curiosa: Mac OSX uses LF now days but older mac's used only CR.

Related

Laravel: Calling Artisan command from controller not working properly

I'm trying to backup my db when I hit a spesific route.
first I made artisan command: php artisan backupDB
here is the function:
echo "Generating backup file..\n";
$filename = "backup-" . Carbon::now()->format('Y-m-d-H-i-s') . ".sql";
$command = "mysqldump --user=" . env('DB_USERNAME') ." --password=" . env('DB_PASSWORD') . " --host=" . env('DB_HOST') . " " . env('DB_DATABASE') . " > " . storage_path() . "/app/backup/" . $filename;
$returnVar = NULL;
$output = NULL;
exec($command, $output, $returnVar);
echo "Backup file path: ".storage_path() . "/app/backup/".$filename;
I run it in cli and it is working fine.
then when I tried to run it via controller:
use Illuminate\Support\Facades\Artisan;
public function backupDB{
Artisan::call("backupDB");
}
when I hit the route it prints the echo, but nothing else happened. just that.
So, I found a solution. wrap the command inside a job or just put the code inside that job, and then start the queue. By doing that the code works fine when I try to hit the route.
php artisan make:job backupDB
it will create a file inside app>jobs folder
then put the code inside handle() function.
next just call the job inside your controller or route
use App\Jobs\backupDB;
public function backup()
{
$process = new pull();
dispatch($process);
}
and you need to setup the queue, here is the docs
You don't need to reinvent the wheel. Just use this extension.
PS: I can't explain the problem you are facing, because you didn't provide any debug info: logs, backtrace, or smth like that.
PS2: Be careful with exec() functions usage

Scripting telnet mailing

I want to create a script that will be able to send mail easily with the user choices.
I did this but it does not work
mail_sender ()
{
echo " - FROM : "
read from
echo " - TO : "
read to
echo " - Subject : "
read subject
echo " - Message : "
read message
telnet localhost 25
ehlo triton.itinet.fr
mail from: $from
rcpt to: $to
data
subject: $subject
$message
.
}
Do you have an idea ?
Redirect to telnet a here-document:
mail_sender ()
{
echo " - FROM : "
read from
echo " - TO : "
read to
echo " - Subject : "
read subject
echo " - Message : "
read message
telnet localhost 25 << EOF
ehlo triton.itinet.fr
mail from: $from
rcpt to: $to
data
subject: $subject
$message
.
EOF
}
The content of the here-document will be redirected to telnet, effectively executing these SMTP commands in the mail server's shell.
It's important that the lines within the here-document don't have any indentation at all (no spaces or tabs at the start of the lines).
Notice that the indentation looks kind of broken in the way I wrote it above, halfway in mail_sender. It has to be this way,
because that's how here-documents work.
You can read more about here-documents and input redirection in man bash.
I've only used it for the simplest of testing:
http://www.jetmore.org/john/code/swaks/
but it boasts:
Completely scriptable configuration, with option specification via
environment variables, configuration files, and command line
so no need to re-invent the wheel here..

Backup2mail can't send email with database backup..multiple or malformed newlines?

Until 18 June I received all days my backup database on Gmail without problems, I had finally found the solution for this. But after 18 June emails with database are stopped. I don't receive neither normal email with only log file txt..nothing I receive now.
I use Backup2mail http://www.backup2mail.com/
PHP Version 5.6.13, Ubuntu Linux 14.04.1
The database backup file is perfectly created on server but it can't send more to Gmail.
I have this error in index.php file of Backup2mail:
Warning: mail(): Multiple or malformed newlines found in additional_header in > /srv/users/serverpilot/apps/myappname/public/backuptomail/index.php on line 119
Database not sent! Please check your mail settings.
Sent? No
On line 119 there is:
if (mail($send_to, $subject, $body, $headers)) {
$sent = 'Yes';
echo ($file_is_db ? 'Backup file' : 'Report') . ' sent to ' . $send_to . '.<br />';
if ($file_is_db) {
if ($delete_backup) {
unlink($file);
echo 'Backup file REMOVED from disk.<br />';
} else {
echo 'Backup file LEFT on disk.<br />';
}
}
} else {
echo '<span style="color: #f00;">' . ($file_is_db ? 'Database' : 'Report') . ' not sent! Please check your mail settings.</span><br />';
}
echo 'Sent? ' . $sent;
Where is the problem? :( Maybe from 18 june PHP is upgraded and changed something? I'm not expert.
Thank you in advance
The problem is a recent update in PHP. Under this update you can no longer have multiple (\n) new lines in the header. Thus you need to remove the newlines in a few places.
Find the following lines and remove the trailing \n (leave just one):
$body = 'Database backup file:' . "\n" . ' - ' . $file . "\n\n";
$headers .= 'Content-Transfer-Encoding: base64' . "\n\n";
However you also need to remove the \n in the following line as well:
$headers .= chunk_split(base64_encode(implode('', file($file)))) . "\n";
change it to:
$headers .= chunk_split(base64_encode(implode('', file($file)))) . "";
It should work after these changes.
Hope this helps you out mate.

Perl - Using Variables from an Input File in the URL when a Variable has a Space (two words)

What am I doing? The script loads a string from a .txt (locations.txt), and separates it into 6 variables. Each variable is separated by a comma. Then I go to a website, whose address depends on these 6 values.
What is the problem? If there is a space as a character in a variable as part of a string in locations.txt. When there is a space, it does not get the correct url.
The input file is:
locations.txt = Heinz,Weber,Sierra Leone,1915,M,White
Because Sierra Leone has a space, the url is:
https://familysearch.org/search/collection/results#count=20&query=%2Bgivenname%3AHeinz%20%2Bsurname%3AWeber%20%2Bbirth_place%3A%22Sierra%20Leone%22%20%2Bbirth_year%3A1914-1918~%20%2Bgender%3AM%20%2Brace%3AWhite&collection_id=2000219
But that does not get processed correctly in the code below.
I'm using the packages:
use strict;
use warnings;
use WWW::Mechanize::Firefox;
use HTML::TableExtract;
use Data::Dumper;
use LWP::UserAgent;
use JSON;
use CGI qw/escape/;
use HTML::DOM;
This is the beginning of the code :
open(my $l, 'locations26.txt') or die "Can't open locations: $!";
open(my $o, '>', 'out2.txt') or die "Can't open output file: $!";
while (my $line = <$l>) {
chomp $line;
my %args;
#args{qw/givenname surname birth_place birth_year gender race/} = split /,/, $line;
$args{birth_year} = ($args{birth_year} - 2) . '-' . ($args{birth_year} + 2);
my $mech = WWW::Mechanize::Firefox->new(create => 1, activate => 1);
$mech->get("https://familysearch.org/search/collection/results#count=20&query=%2Bgivenname%3A".$args{givenname}."%20%2Bsurname%3A".$args{surname}."%20%2Bbirth_place%3A".$args{birth_place}."%20%2Bbirth_year%3A".$args{birth_year}."~%20%2Bgender%3AM%20%2Brace%3AWhite&collection_id=2000219");
# REST OF THE SCRIPT HERE. MANY LINES.
}
As another example, the following would work:
locations.txt = Benjamin,Schuvlein,Germany,1913,M,White
I have not used Mechanize, so not sure whether you need to encode the URL. Try encoding space to %20 or + before running $mech->get
$url =~ s/ /+/g;
Or
$url =~ s/ /%20/g
whichever works :)
====
Edit:
my $url = "https://familysearch.org/search/collection/results#count=20& query=%2Bgivenname%3A".$args{givenname}."%20%2Bsurname%3A".$args{surname}."%20%2Bbirth_place%3A".$args{birth_place}."%20%2Bbirth_year%3A".$args{birth_year}."~%20%2Bgender%3AM%20%2Brace%3AWhite&collection_id=2000219";
$url =~ s/ /+/g;
$mech->get($url);
Try that.
If you have the error
Global symbol "$url" requires explicit package name.
this means that you forgot to declare $url with :
my $url;
Your use part seems freaky, I'm pretty sure that you don't need all of those modules # the same time. If you use WWW::Mechanize, no need LWP::UserAgent and CGI I guess...

fopen with dynamic filename is not working

I need to make a web site on which people can upload data files that after some treatment will be plotted using the jpgraph. The file is analyzed with a bash script called analfile.sh. The bash script is like this:
#!/bin/bash
file=$1
fecha=`date +%s`
mv $1 $fecha.dat
echo $fecha.dat
So, it gives back another file which name is like: 1321290921.dat. That is the file that I need to plot.
This my current php code:
$target_path = "/home/myhome";
$target_path = $target_path . basename( $_FILES['rdata']['name']);
$target_file = basename( $_FILES['rdata']['name']);
if(move_uploaded_file($_FILES['rdata']['tmp_name'], $target_path)) {
echo "The file ". $target_file. " has been uploaded";
chdir('/home/myhome');
$filetoplot=shell_exec('./analfile.sh'.' '.$target_file);
} else{
echo "There was an error uploading the file, please <a href=\"index.html\">try again!
</a>";
}
//$filetoplot="1321290921.dat"
echo "<br>The file to be opened is ". $filetoplot. "<br>";
if ($file_handle = fopen("$filetoplot", 'r')) {
while ( $line_of_text = fgets($file_handle) ) {
$parts = explode('.', $line_of_text);
echo $line_of_text ;
print $parts[0] . $parts[1]. $parts[2]. "<br>";
}
fclose($file_handle);
}
I have permissions to read and write on the target directory. I find strange that if I uncomment the line $filetoplot="1321290921.dat" then the script works perfectly. I guess I am doing something stupid since this is my first code in php but after some hours googling I was not able to find a solution.
Any help will be appreciated.
First thing I'm seeing is that you don't append trailing slash (/) to your home path, so that the path would be like /home/myhomefoo rather than /home/myhome/foo.
You should also move $target_file earlier, and reuse that within $target_path. There's no reason to do the same thing twice.
If that doesn't help, we'll see what goes next.

Resources