PHP - Difficulties Writing New Line [duplicate] - php

This question already has answers here:
Writing a new line to file in PHP (line feed)
(4 answers)
Closed 6 years ago.
I am encountering difficulties with writing to a new line in a basic text file. All the other text (including the comma) appears just fine, but no new line (no space or anything either). I would greatly appreciate any direction.
<?php
session_start();
$user = $_SESSION['store'];
function format($input) {
$input = trim($input);
$input = stripcslashes($input);
$input = htmlspecialchars($input);
return $input;
}
$file = "messages/reminder.txt";
$image;
$secFreqLabel;
$freqLabel;
$uploadDirectory = "corpImages/";
if(!file_exists($file)) {
$temp = fopen($file, "w"); // create file
fclose($temp);
}
$con = new PDO("sqlite:bk.db");
if($_SERVER['REQUEST_METHOD'] == "POST") {
$secFreqLabel = 'reminder.jpg';
$freqLabel = 'reminderHourly.jpg';
$thirdFreqLabel = 'reminderThree.jpg';
$fourthFreqLabel = 'reminderFour.jpg';
$freqUploadFile = $uploadDirectory . $freqLabel;
$secFreqUploadFile = $uploadDirectory . $secFreqLabel;
$thirdFreqUploadFile = $uploadDirectory . $thirdFreqLabel;
$fourthFreqUploadFile = $uploadDirectory . $fourthFreqLabel;
$statement = $con->prepare("INSERT INTO slides (image, label) VALUES (:image, :label)");
if(!empty($_FILES['freqImage'])) {
$con->exec("DELETE FROM slides where label = 'reminder.jpg'");
}
if(!empty($_FILES['secFreqImage'])) {
$con->exec("DELETE FROM slides where label = 'reminderHourly.jpg'");
}
if(!empty($_FILES['thirdFreqImage'])) {
$con->exec("DELETE FROM slides where label = 'reminderThree.jpg'");
}
if(!empty($_FILES['fourthFreqImage'])) {
$con->exec("DELETE FROM slides where label = 'reminderFour.jpg'");
}
$image = file_get_contents($_FILES['freqImage']['tmp_name']);
move_uploaded_file($_FILES['freqImage']['tmp_name'], $freqUploadFile);
$statement->bindParam(":label", $freqLabel);
$statement->bindParam(":image", $image);
$statement->execute();
$image = file_get_contents($_FILES['secFreqImage']['tmp_name']);
move_uploaded_file($_FILES['secFreqImage']['tmp_name'], $secFreqUploadFile);
$statement->bindParam(":label", $secFreqLabel);
$statement->bindParam(":image", $image);
$statement->execute();
$image = file_get_contents($_FILES['thirdFreqImage']['tmp_name']);
move_uploaded_file($_FILES['thirdFreqImage']['tmp_name'], $thirdFreqUploadFile);
$statement->bindParam(":label", $thirdFreqLabel);
$statement->bindParam(":image", $image);
$statement->execute();
$image = file_get_contents($_FILES['fourthFreqImage']['tmp_name']);
move_uploaded_file($_FILES['fourthFreqImage']['tmp_name'], $fourthFreqUploadFile);
$statement->bindParam(":label", $fourthFreqLabel);
$statement->bindParam(":image", $image);
$statement->execute();
$text = format($_POST['freq']) . "," . format($_POST['freqMessage']) . "\n" . format($_POST['secFreq']) . "," . format($_POST['secFreqMessage']) . "\n" . format($_POST['thirdFreq']) . "," . format($_POST['thirdFreqMessage']) . "\n" . format($_POST['fourthFreq']) . "," . format($_POST['fourthFreqMessage']);
$writer = fopen($file, "w");
fwrite($writer, $text);
fclose($writer);
touch("update.txt");
}
$handler = fopen($file, "r");
$firstReminder = fgetcsv($handler, ",");
$secondReminder = fgetcsv($handler, ",");
$thirdReminder = fgetcsv($handler, ",");
$fourthReminder = fgetcsv($handler, ",");
fclose($handler);
?>

Instead of using \n use constant called PHP_EOL which represents end of line according to your enviroment.
PHP_EOL (string)
The correct 'End Of Line' symbol for this platform. Available since PHP 5.0.2
$text = format($_POST['freq']) . "," . format($_POST['freqMessage']) . PHP_EOL . format($_POST['secFreq']) . "," . format($_POST['secFreqMessage']) . PHP_EOL . format($_POST['thirdFreq']) . "," . format($_POST['thirdFreqMessage']) . PHP_EOL . format($_POST['fourthFreq']) . "," . format($_POST['fourthFreqMessage']);
PHP_EOL in windows will be CR+LF and in unix system LF
CR - Carriage Return, U+000D
LF - Line Feed, U+000A

Related

Cant store image in Db Laravel

I tried to store the image in DB along with some other data in another table ,but I get
"message": "Undefined variable $filenameA"
//for picture refrences
if (!empty($request->picture_a)) {
$fileA = $request->file('picture_a');
$extensionA = $fileA->getClientOriginalExtension();
$filenameA = 'picture_a' . '_' . time() . '.' . $extensionA;
$fileA->storeAs('uploads/picture_refrences', $filenameA);
$data['picture_a'] = 'public/uploads/' . $filenameA;
}
if (!empty($request->picture_b)) {
$fileB = $request->file('picture_b');
$extensionB = $fileB->getClientOriginalExtension();
$filenameB = 'picture_b' . '_' . time() . '.' . $extensionB;
$fileB->storeAs('uploads/picture_refrences', $filenameB);
$data['picture_b'] = 'public/uploads/' . $filenameB;
}
if (!empty($request->picture_c)) {
$fileC = $request->file('picture_c');
$extensionC = $fileC->getClientOriginalExtension();
$filenameC = 'picture_c' . '_' . time() . '.' . $extensionC;
$fileC->storeAs('uploads/picture_refrences', $filenameC);
$data['picture_c'] = 'public/uploads/' . $filenameC;
}
This is what I used and it was working when I used it to store in public directory now since I tried to store in storage it does not upload images
enter image description here
you can use this code, it is working and tested
$image = $request->file('picture_a');
if (isset($image))
{
$currentDate = Carbon::now()->toDateString();
$imageName = $currentDate.'-'. uniqid() .'.'. $image->getClientOriginalExtension();
if (!file_exists('uploads/photos')){
mkdir('uploads/photos',0777,true);
}
$image->move('uploads/photos',$imageName);
}

Problem with deleting a new line character

I've tried everything I could think of yet I still couldn't get the code to delete the new line character that is appended at each new entry.
if ($_POST['what_to_do']==1){
if ((isset($_POST['chat_name'])) and ($_POST['chat_name']!=NULL)){
$chat_name=$_POST['chat_name'];
$myfile = fopen("users.txt", "a");
fwrite($myfile, "user_id" . $user_id . " " . "chat_name" . $chat_name . ";\n");
fclose($myfile);
$_SESSION['is_chat_logged'] = 1;
}
}
elseif ($_POST['what_to_do']==2){
if ($_SESSION['is_chat_logged'] = 1){
$actual_file=file_get_contents("users.txt");
$position_start=strpos($actual_file, "user_id" . $user_id . " ");
$line=file_get_contents("users.txt",FALSE,NULL,$position_start);
$position_end=strpos($line, ";")+1+$position_start;
$part_to_be_replaced=substr($actual_file, $position_start, $position_end-strlen($actual_file));
$new_actual_file= str_replace($part_to_be_replaced, "", $actual_file);
$myfile = fopen("users.txt", "w");
fwrite($myfile, $new_actual_file);
fclose($myfile);
$_SESSION['is_chat_logged'] = 0;
}
}
The users.txt looks like this:
user_id1 chat_nameJake;
user_id2 chat_nameSomeone;
user_id43 chat_nameZeke;
user_id22 chat_nameBilly;
Any help would be appreciated.
EDIT: I've found out what the problem was. I was using the substr() function the wrong way. Instead of $position_end-strlen($actual_file) I should have put $position_end-$position_start+1
change
fwrite($myfile, "user_id" . $user_id . " " . "chat_name" . $chat_name . ";\n");
to
fwrite($myfile, "user_id" . $user_id . " " . "chat_name" . $chat_name . ";");
The \n represents a new line.
notice when you are writing file (fwrite) you are appending a "/n" char which is a new line char. in order to remove new line char you just need to remove that "/n" from your fwrite function

String adding new lines and I don't understand why

I have got this code to open each file in a folder, decrease a value by 5 and then overwrite the existing content.
<?php
foreach (glob("users/*.php") as $filename) {
$array = file($filename);
$wallet = $array[0];
$time = $array[1];
$status = $array[2];
$steamid = $array[3];
$process = fopen($filename, "w") or die("Unable to open file!");
$time = $time - 5;
$newdata = $wallet . "\n" . $time . "\n" . $status . "\n" . $steamid;
fwrite($process, $newdata);
fclose($process);
}
?>
Before I execute the script, the files that are opened look like this:
680
310
0
74892748232
After the script was executed, the file looks like this:
680
305
0
74892748232
If the script is executed again, it adds more lines and just breaks the files even more.
The string for the file is created here:
$newdata = $wallet . "\n" . $time . "\n" . $status . "\n" . $steamid;
Why does it add an empty line after $wallet and $status, but not after $time? How can I avoid this and instead write down:
$wallet
$time
$status
$steamid
Thanks a lot in advance.:)
Try with this solution
You can also use file_put_contents():
file_put_contents($filename, implode("\n", $array) . "\n", FILE_APPEND);
from this SO question
https://stackoverflow.com/a/3066811/1301180

How to write php code inside a new php file

$np = $_POST["np"]; // `sky` for example
$a = "inc/" . $np . ".php";
$new = fopen($a, "w") or die("Unable to open file!");
$str="$np='" . $np . "';";
fwrite($new, $str);
fclose($new);
I need to create a new inc/.sky.php file and write the following inside it:
$np = 'sky';
But what I get is:
sky='sky';
Any idea?
This should work for you:
$np = $_POST["np"]; // `sky` for example
$a = "inc/" . $np . ".php";
$new = fopen($a, "w") or die("Unable to open file!");
$str='$np = \'' . $np . "';";
fwrite($new, $str);
fclose($new);
The problem was that you are using " to define the string $str. Therefore, the content of $np was printed instead of the string '$np'.
Use single comma's
This will insert the $np variable into your sting
$str="$np='" . $np . "';";
This will insert np as text
$str='$np=\'' . $np . '\';';

Why my PHP defined constants are not evaluated when file is executed using command line?

I am creating a plugin for a WP site and I have to make an initial import of a huge amount of files from another directory. (The plugin is working well, etc etc.) I want to run the import using command line. Everything is OK if executing on local (Windows), but when I execute from Linux bash the defined constants are not evaluated but printed as a string.
define("ASCOR_RECORDINGS_TBL", $wpdb->prefix . "recordings");
Is there any setting I have to make to enable evaluation of PHP defined constants? My website is running on Dreamhost server.
When I execute the folowing line:
[myserver]$ /usr/local/php5/bin/php /home/path/to/import.php
I get:
WordPress database error Table 'db_ro.ASCOR_RECORDINGS_TBL' doesn't exist for query INSERT INTO `ASCOR_RECORDINGS_TBL` ...........
The content of the file I execute:
<?php
require_once dirname(dirname(dirname(dirname(__FILE__)))) . "/wp-load.php";
require_once "class/AscorDbHelper.php";
$origin = realpath("/path/to/files");
$upload_dir = wp_upload_dir();
$subdir = $upload_dir['subdir'];
mkdir(ASCOR_UPLOAD_DIR . "/" . $subdir, 777, true);
require_once $origin . "/classes/PConfFiles.inc.php";
$db = new AscorDbHelper();
$cf = new PConfFiles('/^PC_([0-9\-]+)_(.*)\.([a-z0-9]{2,4})$/i', $origin);
$list = $cf->getFilesList();
$catPC = $db->addCategory("Special");
$catOther = $db->addCategory("Other");
if($list){
$pc = $db->addAuthor("Ciprian V.");
foreach($list as $rec){
$fileUrl = $subdir . "/" . $rec[0];
$desc = str_replace("-", " ", $rec[2]);
copy(realpath($origin . "/" . $rec[0]), ASCOR_UPLOAD_DIR . "/" . $fileUrl );
$db->addRecording($fileUrl, $catPC->id, $pc->id, $desc, null, $rec[1]);
echo "Added: " . $rec[0] . "\n";
}
}
$cf = new PConfFiles('/^([0-9\-]+)\_([^\_]+)_(.*)\.([a-z0-9]{2,4})$/i', $origin);
$list = $cf->getFilesList();
if($list){
foreach($list as $rec){
$authorName = str_replace("-", " ", $rec[2]);
$date = $rec[1];
$desc = str_replace("-", " ", $rec[3]);
$fileUrl = $subdir . "/" . $rec[0];
$authorId = $db->getAuthorIdOrSaveIt($authorName);
copy(realpath($origin . "/" . $rec[0]), ASCOR_UPLOAD_DIR . "/" . $fileUrl );
$db->addRecording($fileUrl, $catOther->id, $authorId, $desc, null, $date);
echo "Added: " . $rec[0] . "\n";
}
}
echo "done";
The constants are defined in the main file of the plugin:
define("ASCOR_RECORDINGS_TBL", $wpdb->prefix . "recordings");
define("ASCOR_RECORDINGS_AUTHORS_TBL", $wpdb->prefix . "recordings_authors");
define("ASCOR_RECORDINGS_CATEGORIES_TBL", $wpdb->prefix . "recordings_categories");
define("ASCOR_RECORDS_PER_PAGE", 50);
define("ASCOR_EXTEND_DIR", dirname(__FILE__));
define("ASCOR_EXTEND_URL", plugins_url("", __FILE__));
define("ASCOR_NOTIFY_UPDATED", "updated");
define("ASCOR_NOTIFY_ERROR", "error");
define("ASCOR_UPLOAD_DIR", ABSPATH . "/wp-content/uploads/recordings");
Is the file loaded? Introduce a parse error into it and see if it fails. And try it on Windows too.

Categories