Write to file in php line by line

Php – How to write a text file line by line in PHP

I’m very new to PHP. I have a FORM to input data, the FORM includes 3 fields : name, age, address
I want to get the submitted data and write them to a text file line-by-line.
For example, if I submit the FORM 3 times, I would like the output text file to contain:

john 20 US Simson 18 UK Marry 26 Japan 

I tried to implement it, but there was always a blank space in the beginning or the end of text file. I could not write file line-by-line. How do I do that, please help me? Here is my form:

Best Solution

Php – How to prevent SQL injection in PHP

The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create SQL statement with correctly formatted data parts, but if you don’t fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

You basically have two options to achieve this:

    Using PDO (for any supported database driver):

 $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name'); $stmt->execute([ 'name' => $name ]); foreach ($stmt as $row) < // Do something with $row >
 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?'); $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string' $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) < // Do something with $row >

If you’re connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.

Correctly setting up the connection

Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password'); $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

In the above example the error mode isn’t strictly necessary, but it is advised to add it. This way the script will not stop with a Fatal Error when something goes wrong. And it gives the developer the chance to catch any error(s) which are throw n as PDOException s.

Читайте также:  Сколько зарабатывает джуниор программист python

What is mandatory, however, is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren’t parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).

Although you can set the charset in the options of the constructor, it’s important to note that ‘older’ versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN.

Explanation

The SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute , the prepared statement is combined with the parameter values you specify.

The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn’t intend.

Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains ‘Sarah’; DELETE FROM employees the result would simply be a search for the string «‘Sarah’; DELETE FROM employees» , and you will not end up with an empty table.

Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.

Oh, and since you asked about how to do it for an insert, here’s an example (using PDO):

$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)'); $preparedStatement->execute([ 'column' => $unsafeValue ]); 

Can prepared statements be used for dynamic queries?

While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.

Читайте также:  Как включить css v34

For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.

// Value whitelist // $dir can only be 'DESC', otherwise it will be 'ASC' if (empty($dir) || $dir !== 'DESC')
Python – How to check whether a file exists without exceptions

If the reason you’re checking is so you can do something like if file_exists: open_it() , it’s safer to use a try around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.

If you’re not planning to open the file immediately, you can use os.path.isfile

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

import os.path os.path.isfile(fname) 

if you need to be sure it’s a file.

Starting with Python 3.4, the pathlib module offers an object-oriented approach (backported to pathlib2 in Python 2.7):

from pathlib import Path my_file = Path("/path/to/file") if my_file.is_file(): # file exists 
if my_file.is_dir(): # directory exists 

To check whether a Path object exists independently of whether is it a file or directory, use exists() :

if my_file.exists(): # path exists 

You can also use resolve(strict=True) in a try block:

try: my_abs_path = my_file.resolve(strict=True) except FileNotFoundError: # doesn't exist else: # exists 
Related Question

Источник

Writing Files Line by Line

Writing files builds upon the same approaches as reading files. Writing files will allow us to save any changes we make, and also allow us to change settings and update application details.

Download: File Handling Cheat Sheet

Be careful when manipulating files!

You can do a lot of damage if you do something wrong. Common errors are: editing the wrong file, filling a hard-drive with garbage data, and deleting the content of a file by accident.

PERMISSIONS

If you are having problems with accessing files, a good place to start looking is at the file permissions. To learn more about file permissions, check out our Console Foundations course, specifically the video on File Permissions

File Functions and Modes

fopen() — Opens file or URL
fwrite() — Binary-safe file write
fputs() — Alias of fwrite
fclose() — Closes an open file pointer

For more functions and options, check out the documentation for Directory Functions and File System Functions.

Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
Читайте также:  table-layout

Have questions about this video? Start a discussion with the community and Treehouse staff.

Источник

PHP fwrite(): Write to a File

The PHP fwrite() function is used when we need to write some content to a file. For example:

After executing the above PHP code, the content/text PHP is Fun! will get written in the file named myfile.txt.

Note: To write some text to a file, the file must be opened in w (writing) mode, using the function named fopen().

PHP fwrite() Syntax

The syntax of the fwrite() function in PHP is:

fwrite(filePointer, text, length)

The first two parameters (filePointer and text) are required, but the last one (length) is not (optional).

Note: The filePointer parameter specifies the pointer to the file.

Note: The text parameter is the content or text that has to be written in the file.

Note: The length parameter is used when we need to define the maximum number of bytes to write.

The fwrite() function returns the number of bytes (characters) written to the file. For example:

 else echo "

Unable to open the file

"; ?>

Since the text PHP is Fun! Isn’t it? is of 21 characters, therefore the output of the above PHP example on the fwrite() function should be:

php fwrite write to file

PHP Write to File Line by Line using fwrite()

To write content to a file line by line using the PHP fwrite() function, use PHP_EOL as shown in the example given below:

 else echo "

Unable to open the file

"; ?>

The three texts will be written line by line. Therefore, after executing the above PHP example, here is the snapshot of the file myfile.txt.

php fwrite write line by line

Liked this article? Share it!

Источник

Оцените статью