-1

I just want to replace a few things in a file called "config.php"! Here is i section of the file that I want to edit. I want to use a form to set the values of the text in caps. I am stuck and I looked all over StackOverflow and google. I could not find anything.

$dbhost = "DBHOST";                          /*      "localhost"      */
$dbuname = "DBUSERNAME";                     /* "database user name"  */
$dbpass = "DBPASSWORD";                      /* "database password"   */
$dbname = "DBNAME";                          /*    "database name"    */

Also, how should the form look for this?

I have this..

<form action="edit.php">
        DB Server: <input type="text" name="host" placeholder="localhost"><br>
        DB Username: <input type="text" name="dbuser" placeholder="admin"><br>
        DB Password: <input type="password" name="dbpassword" placeholder="********"><br>
        DB Name: <input type="text" name="db_name" placeholder="pnc"><br>
        <button type="submit">Next Step</button>
</form>
Blood_Wolf89
  • 45
  • 1
  • 6
  • 2
    what did you try so far? – chresse Jun 22 '14 at 13:48
  • Use `file_get_contents()` to get the script into a variable. Then use `str_replace()` to replace the values you want replaced (you want those values to be unique in the script). Then use `file_put_contents()` to right the variable back to the filename. It's not difficult. – Jared Farrish Jun 22 '14 at 13:54
  • I have tryed a lot! I have been up for about 6 hours trying to figure it out and this area is very new to me. Never messed with editing files like this. – Blood_Wolf89 Jun 22 '14 at 13:58
  • If you really must use a file I'd suggest making it an xml file and using domdocument or simplexml – andrew Jun 22 '14 at 13:59
  • do you have an example? Sorry I did not go to bed yet, it is 9 am and I am trying to get this done before I enter a coma!! lol – Blood_Wolf89 Jun 22 '14 at 13:59
  • This config file connects to the database, there for I can not do that.. – Blood_Wolf89 Jun 22 '14 at 14:00
  • Not 100% sure as to what the question is. If you want the values to be in uppercase (caps) passed from a POST, then use [`strtoupper()`](http://www.php.net//manual/en/function.strtoupper.php). Example `$dbhost = strtoupper($_POST['host']);` – Funk Forty Niner Jun 22 '14 at 14:16
  • no, look at the file I posted.. ( DBHOST, DBUSERNAME, DBPASSWORD, DBNAME ) Thats what I want to change – Blood_Wolf89 Jun 22 '14 at 14:31
  • @Blood_Wolf89 - The answer provided shows the basic means to do what you're asking, or have I misunderstood? – Jared Farrish Jun 22 '14 at 14:34
  • In other words, you want to be able to take user input, write it file then read from that in order to be used as your DB config, correct? – Funk Forty Niner Jun 22 '14 at 14:40
  • Thanks to everyone for their help! I have it working now! – Blood_Wolf89 Jun 22 '14 at 15:52

3 Answers3

3

Say you had this file:

/home/websites/example.com/conf.php

<?php

$dbhost = "DBHOST";                          /*      "localhost"      */
$dbuname = "DBUSERNAME";                     /* "database user name"  */
$dbpass = "DBPASSWORD";                      /* "database password"   */
$dbname = "DBNAME"; 

To replace those placeholder values, all you need is to get the page source in a variable and do some string replacing, then write it back to a file.

$confpath = '/home/websites/example.com/conf.php';
$confphp = file_get_contents($confphp);

// Note the POST values need to be CLEANED and validated first.
// This especially means whitelisting what characters are allowed
// in the POST-received variables, encoding and removing " and '.
// You have to be VERY careful to authentic the user, and verify
// that user has permissions to do what they're doing, with the 
// databases/tables they're working with, unless this is part of
// an install script, which would need to be removed immediately
// upon finishing the install.
$confphp = str_replace(
    array('DBHOST','DBUSERNAME','DBPASSWORD','DBNAME'),
    array(
        addslashes($post_cleaned_dbhost), 
        addslashes($post_cleaned_dbusername), 
        addslashes($post_cleaned_dbpassword), 
        addslashes($post_cleaned_db_name)
    ),
    $confphp
);

file_put_contents($confpath, $confphp);

Note the values you're replacing need to be unique to the text content of the file (e.g, no $DBUSERNAME in the same file), or it will replace those as well. It returns false if the file was not written, so you can test the return of file_put_contents() to verify it worked.

http://www.php.net/manual/en/function.file-get-contents.php

http://www.php.net/manual/en/function.file-put-contents.php

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
  • How would this be better than writing to an external dedicated data file? – Chris Barrett Jun 22 '14 at 14:08
  • 2
    But parsing and replacing data for a commonly used php is frought with perils, your solution doesn't account for the fact that the DBHOST, DBUSERNAME etc is changed meaning it will only work the first time, what if a user enters "; exit; for the DBUSERNAME? terminating the script – Chris Barrett Jun 22 '14 at 14:12
  • @JaredFarrish I +1 your comment by the way, that many downvote just out of spite (*been victim of that too*). OP's question seems to have expanded and wasn't clearly written as to what the actual goal was. It turns out that it is now part of an "install". See [`OP's comment`](https://stackoverflow.com/questions/24351883/use-php-file-to-replace-a-few-parts-of-a-line-in-another-file#comment37652188_24351907) --- *"The files will be in an install directory and will require removal once installed."* --- I voted to close as to unclear what is being asked. – Funk Forty Niner Jun 22 '14 at 14:50
  • 1
    @Fred-ii- I predicted it was part of an install script in the comments within the second code block. I recognized what this was for from the beginning. It's not uncommon behavior. – Jared Farrish Jun 22 '14 at 14:51
  • @JaredFarrish You have a good sense of prediction then ;-) cheers – Funk Forty Niner Jun 22 '14 at 14:52
  • @JaredFarrish OP placed a pastebin file http://pastebin.com/Z04GP3v8 under another answer given - from [`this comment`](https://stackoverflow.com/questions/24351883/use-php-file-to-replace-a-few-parts-of-a-line-in-another-file#comment37652371_24351995). What I feel OP should do is replace those 4 lines of code with an include statement, use a function to write to (config) file, reading those values written from user input. – Funk Forty Niner Jun 22 '14 at 14:59
  • When I use this it makes my config.php all blank – Blood_Wolf89 Jun 22 '14 at 15:12
  • Oh I see... Than I can just write out the 4 lines instead of the whole file – Blood_Wolf89 Jun 22 '14 at 15:14
  • @Blood_Wolf89 - Are you verifying you have anything in the `$confphp` variable and that the `$confpath` is correct? – Jared Farrish Jun 22 '14 at 15:15
  • Thanks to everyone for their help! I have it working now! – Blood_Wolf89 Jun 22 '14 at 15:51
  • @Blood_Wolf89 - Which solution did you use? – Jared Farrish Jun 22 '14 at 15:53
2

Do you want to create a form that will take user input and change the lines in the file? I wouldn't recommend setting your database connection from a form directly. But if it's necessary try using a normal format for storing data such as JSON

 $data = json_decode(file_get_contents($dataFileName));

to write

 file_put_contents(json_encode($data, $dataFileName));

for reference check http://www.php.net//manual/en/book.json.php

It will become clear that your file contains data if it is in a typical data format. You could name this database.json for instance

Create a file named database.json containing the following:

{
     "username": "...",
     "password": "...",
     "database": "...",
     "host": "..."
}

Then to read this data you can use

$data = json_decode(file_get_contents('database.json'));
$data['username'] = $newValue;
$username = $data['username'];

Once you set new values

file_put_contents(json_encode('database.json', $data));

There are issues with connecting to a database from user submitted data, eg switching to a different database and showing malicious data in your page that could be used for XSS http://en.wikipedia.org/wiki/Cross-site_scripting

Chris Barrett
  • 516
  • 3
  • 12
  • 1
    @JaredFarrish I think is suggesting that the Op store configuration as a json file or another parsable format, so that it is easily readbale/writeable. – Ozair Kafray Jun 22 '14 at 13:54
  • I think it would be more like on this page http://stackoverflow.com/questions/13314898/replace-a-particular-line-in-a-text-file-using-php I dont think that is quite correct for what I need. I just need an example – Blood_Wolf89 Jun 22 '14 at 13:56
  • Nice man, this is very useful. Never even though of this one. – Abandoned Account Jun 22 '14 at 14:26
  • [Code injection](http://en.wikipedia.org/wiki/Code_injection) is the vulnerability you're referring, not cross-site scripting, which is related to arbitrarily run client-side scripts. – Jared Farrish Jun 22 '14 at 14:32
  • The files will be in an install directory and will require removal once installed. – Blood_Wolf89 Jun 22 '14 at 14:38
  • @Blood_Wolf89 You need to be more precise with your question and include everything in an edit stating your exact goal. You never mention the fact that it's an install etc. – Funk Forty Niner Jun 22 '14 at 14:47
  • 1
    It's nobody's fault but the OP's. OP should have stated the full intention right away in the question, instead of having everyone guess. – Funk Forty Niner Jun 22 '14 at 15:02
  • Thanks to everyone for their help! I have it working now! – Blood_Wolf89 Jun 22 '14 at 15:49
2

Make a form with a controller

Form code in HTML

<form name="dbSet" id="dbSet" action="form_set_db.php" method="POST" />
    <label>Host</label> <input type="text" name="host" id="host" /><br />
    <label>Username</label> <input type="text" name="username" id="username" /><br />
    <label>Password</label> <input type="password" name="password" id="password" /><br />
    <label>Database</label> <input type="database" name="database" id="database" />
</form>

form_set_db.php

require_once 'config.php';
if(isset($_POST["host"], $_POST["username"], $_POST["password"], $_POST["database"]))
{
    $dbhost = $_POST["host"];
    $dbuname = $_POST["username"];
    $dbpass = $_POST["password"];
    $dbname = $_POST["database"];
}

This would replace the values of $dbhost $dbuname $dbpass $dbname with the values you entered in the form.

EDIT

Note that this only replaces it temporarily. If you want a permanently stored config file (if you're building an installer for example), I'd create the config.php file on the fly instead of having it created from the start. You'd then do something like this inside of form_set_db.php

if(isset($_POST["host"], $_POST["username"], $_POST["password"], $_POST["database"]))
{
    $file = fopen("config.php", "w");
    if(!is_resource($file)) { return false; }

    fwrite($file, "$dbhost = '" . $_POST["host"] . "';\n");
    fwrite($file, "$dbuname = '" . $_POST["username"] . "';\n");
    fwrite($file, "$dbpass = '" . $_POST["password"] . "';\n");
    fwrite($file, "$dbname = '" . $_POST["database"] . "';");

    fclose($file);
}
CmdrSharp
  • 1,085
  • 13
  • 30
  • Nice, I want to change the text that is in Caps. – Blood_Wolf89 Jun 22 '14 at 14:21
  • ps: it may be because im so tired... i can not get it to work.. – Blood_Wolf89 Jun 22 '14 at 14:21
  • Try it now, I updated the edited example, @Blood_Wolf89 – CmdrSharp Jun 22 '14 at 14:26
  • Here is the config.php that I have now ( http://pastebin.com/Z04GP3v8 ) I would just like to change the values of the variables... example: $dbhost = "CHANGE THIS"; – Blood_Wolf89 Jun 22 '14 at 14:47
  • @Blood_Wolf89 - I'm starting to wonder if you've seen my answer. – Jared Farrish Jun 22 '14 at 14:49
  • We've given you several methods to change those values. Have you tried any of them? What happens? Does it show you an error? You need to be clear about what happens and actually try the methods you're being given - otherwise it's hard to help you. I'm upvoting @JaredFarrish's solution as it seems better for your config.php (which I falsely assumed contained only the database connection variables). – CmdrSharp Jun 22 '14 at 14:56
  • Thanks to everyone for their help! I have it working now! – Blood_Wolf89 Jun 22 '14 at 15:51