Jump to content

Breif query about reading and writing to a file


IChaps
 Share

Recommended Posts

Hi,

 

Could I please briefly enquire about reading and writing to a file using php?

 

I'm looking for a way of storing a database's, Name, Username and Password. Then reading it back again.

 

Writing to a file, I've written:-

 

// Write to file.
$fp = fopen( dirname(__FILE__).'/sys/dbinfo.txt', 'w' ) or die("Couldn't open file:- ");
fwrite($fp, $hostname);
fwrite($fp, $database);
fwrite($fp, $username);
fwrite($fp, $password);
fclose( $fp );

 

and to read back, I've written:-

 

$fp = fopen( dirname(__FILE__).'/sys/dbinfo.txt', 'r' ) or die("Couldn't open file:- ");
$db_host = fread($fp, $hostname); // $db_host
$db_user = fread($fp, $username); // $db_user
$db_pass = fread($fp, $password); // $db_pass
$db_databasename = fread($fp, $database);
fclose( $fp );

 

However, I'm finding the data is been written in one long string (ie localhostusernamepassworddatabasename).

 

I'd just like to ask if it is possible read the file so that $db_host would hold just hostname, $db_user would hold just the database username and so on?

 

Also (out of interest) is there another way of reading and writing. I've thought about keeping each piece of data in a separate file.

 

Thank You.

 

Link to comment
Share on other sites

You need to manually write the characters to separate everything. You can use line breaks to put each thing on its own line, commas, semicolons, whatever, but you need to write those characters to the file also. When you read the file you would use something like file_get_contents to get all of the file, then split it up on the character that you used to separate everything and set the individual variables. A more common way to do it is to use put all of that in a PHP file which declares those variables with those values, and then you just include the file instead of trying to read and parse it.

Link to comment
Share on other sites

You should look up the documentation of functions before you use them.

 

Here's the manual for fread(): http://php.net/fread

The second parameter is a number indicating how many bytes to read from the file.

 

The rest of the advice I could give you was already presented by justsomeguy.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...