Jay Wit
Jay Wit

Reputation: 3057

How can I save data from one site to another sites database?

How can I save data from one site to another sites database? I need to make a form which saves data to an external database. I tried using fopen but I don't think this is the correct way to do it:

$externalsave = fopen('http://onewebsite.com/folder/this_page_INSERTS_INTO_DB.php?datavalue1='.$data1.'&datavalue2='.$data2, 'r');
$data = '';
while(!feof($externalsave)) 
   $data .= fread($externalsave, 4092); 
fclose($externalsave); 

echo $data;

Does someone know how I can save values inserted in a form on one website, in an external database?

I'm using an Apache server, and the code above works fine, I just don't trust it. Or can I?

Upvotes: 0

Views: 1680

Answers (3)

grunk
grunk

Reputation: 14948

There is 3 main solutions :

1. Remote action

The easiest one is to simply point your form on the remote server. For exemple :

<form method="post" action="http://myothersite.com/myphpscript.php">
</form>

And in myphpscript.php simply handle the form like you will in localhost.

2. Proxy action (require the allow_url_fopen directive to be enabled)

You could also point your form on a php script on the same server which gonna send your data on the other server. This solution can be usefull to bypass security like csrf token :

<form method="post" action="proxy.php"></form>

proxy.php :

$postdata = http_build_query($_POST); //Need some filtering !!!

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);
$result = file_get_contents('http://myotherserver.com/submit.php', false, $context);

No need of curl here ;)

3. Remote database

Finally you can use a database with remote access and simply connect to the database with its remote host like :

$mysqli = new mysqli('mydbHost.com', 'my_user', 'my_password', 'my_db');

Unfortunately this solution is rarely allowed because it could represent a big security risk (anyone in the world can try to connect to the database).

Upvotes: 2

cptHammer
cptHammer

Reputation: 460

you should set mysql (I suppose your database is MySQL) to listen for network connection and connect directly to it.

on DB server comment 'bind-address = 127.0.0.1' in /etc/mysql/my.cnf and restart Mysql daemon.

on web server, do :

$dbconnection = mysql_connect('IP_OF_DB_SERVER', 'username', 'userpassword');

and simply insert your data in database.

Upvotes: 0

user399666
user399666

Reputation: 19909

Simplest answer:

  • Setup a form on SITE A.

  • Point the form action towards a script on SITE B.

  • Have SITE B validate the incoming variables and insert.

You could also use cURL if you don't actually want to create a form on SITE A.

Upvotes: 2

Related Questions