i try to create a little login+survey and try to write all data to a database. Especially it is important, to get a session id for each user in order to add information of each page of the survey to the right line of the database.
My problem is here, that it seems that the session is either not started or i can not create a session id. Writing in the database already works, but not if i include the lines about the session.
After google'ing a lot that always took me to the same answer (which is not working for me) i try it here. Here is my code, first the callDatabase.php is called, in this file a session id is created and the database entry is made (idk if this is the best solution though, i guess not xD):
<script type="text/javascript">
$.post( 'callDatabase.php', { 'entry[]': ["init"]} );
</script>
callDatabase.php:
<?php
header('Content-Type: text/json');
$test = $_POST['entry'];
session_start();
$sID = session_id();
$timestamp = time();
$servername = "local";
$username = "root";
$password = "rootpw";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_select_db($conn, 'myDb');
$sql = "INSERT INTO myTable (sID, timestamp, t1, rating, start, end, color, fight, completed)
VALUES ('$sID', '$timestamp', '-', '4', '_', '_', '_', '_', 'false')";
mysqli_query($conn, $sql);
mysqli_close($conn);
session_unset();
session_destroy();
$_SESSION = array();
?>
Like i said, without the session stuff, it is working fine, with it, the browser is running forever and i get no entry in my database. Since i get no error message i did not find any solution about how to fix it.
It is running locally, with XAMPP and a mysql database.
Problem is caused by Xampp, since some ports might be blocked, code is working with virtual machine, linux and apache server together with phpmyadmin for example. Checking the errorlogs will help to find out if the blocked ports are causing the problem.
To solve the problem together with xampp, it is recommended to deactivate all tools that might block the needed ports (skype, connection via vpn, antivirus tool, ...) or change the ports to have no conflicts there.
Related
i just wanted to insert data into database from a form, with php. i ran the code below in my Localhost using XAMPP and everything was fine but where i upload it to my host it didn't work.
Question is What shold i put for $servername and when should i look for it ?
There is my codes:
Register.php (in localhost)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$Name = $_POST['Name'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$Email = $_POST['Email'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
header("Location:#");
}
//Inserting Data
try{
$sql = "INSERT INTO User (uName , uUsername , uPassword , uEmail) VALUES ('$Name' , '$Username' , '$Password' , '$Email')";
mysqli_query($conn, $sql);
}catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
$conn->close();
header("Location:#");
}
?>
If your MySQL database is on the SAME SERVER as your PHP script, then the usual logical approach is that your host is localhost. The same as you used on your local computer -- because they're on the same machine.
However, if your MySQL database is on ANOTHER SERVER seperate from your PHP scripts the you will need to access that server using a web address for your PHP to connect to yout MySQL.
We can't tell you what that is, and your server hosts (of your MySQL server) will be able to tell you and provide you with the correct login credentials.
I believe it would be more usual for MySQL and PHP to be on the same disk, especially for non-professional systems as your appears to be, so then the issue would be:
Are your login details set up correcty on your server? (same username/password)
Are there any MySQL errors or PDO errors (if you connect with PDO). Don't redirect on error, but instead output the error to a log file so you can read WHY the MySQL in your code didn't connect.
It is still possible for you to set your PHP to communicate with your localhost MySQL via a remote address (such as servername=$_SERVER['SERVER_NAME'];). (see note below)
Many online accounts (in things such as CPanel) will block you from accessing the MySQL as a root or at least will not give you the root MySQL password. Using root to access MySQL via PHP is NOT a good idea and you should instead set up a specific MySQL user for your PHP with only enough privileges that you need to read/write to the DB, and nothing more.
If your MySQL is remote (not localhost) then you may also need to supply a Port Number with the connection details. Usual port numbers are 3306 but this is something you'd need to know from your server hosts.
Immediately after a header(Location:); redirection instruction you should always set die(); or exit to stop PHP processing the rest of the script.
Your SQL insert data is highly suseptible to SQL injection and other SQL attacks and compromise. You should really, REALLY look into using MySQL Prepared Statements, you're already coding in OO style so you're almost there already.
Example remote connection from the manual
<?php
/***
* Remember 3306 is only the default port number, and it could be
* anything. Check with your server hosts.
***/
$conn = new mysqli('remote.addr.org.uk', 'username', 'my_password', 'my_databasa', '3306');
/***
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
***/
if ($conn->connect_error) {
error_log('MySQL Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
/***
* Upon failure, the above will output a connection error notice such as
* user not found or password incorrect. It won't explicity say these
* things but you should be able to deduce which from the notice
***/
echo "Success... \n" . $conn->host_info ;
$mysqli->close();
# : I seem to think that MySQL detects when the remote address given is the same as the server address and auto converts it to localhost, but I'm not sure on this.
The long and the short of it is that if your MySQL is on the same
server as your PHP it makes no sense to open up a network loop to send
data out just to get it back again. Use localhost instead.
I asked my host service providers about the "$servername" and they answered me that the "$serverneme" is localhost.
I want to send form data to a server online.
At the moment i'm using xampp so the username and password are 'root' and ''
If I was to put this online I would have to put my hosting login details. Is that correct?
Clearly that would be a very serious security issue as anybody could see it written in my process file.
I have found a lot of info about prepared statements to prevent SQL injection but nothing about how to hide username/password, which I would have thought would be a bigger thing.
Am I missing something essential about usernames/passwords?
(I am not trying to create user login accounts, just basic newsletter signup)
<?
// database details
$servername = 'localhost';
$username = 'username';
$password = 'password';
$database = 'database';
// form submission
$email=$_POST['email'];
// connect to database
mysql_connect($servername, $username, $password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
mysql_query("INSERT INTO newsletter VALUES ('$email')");
Print "Your information has been successfully added to the database.";
mysql_close();
?>
Update:
Ok, so I have since included prepared statements into my code, and it now looks like this:
<?php
// database details
$servername = 'localhost';
$username = 'username';
$password = 'password';
$database = 'database';
// form submission
$email=$_POST['email'];
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO scenariosubmission (Email) VALUES (?)");
$stmt->bind_param("s", $email);
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
My code should prevent SQL injection
So what I want to know is if I was to enter my username password database and upload this to the server, would those details be safe if I uploaded them like any other web page to public_html?
So when you move this to your hosting, the code will be something like this:
<?
// database details
$servername = 'localhost';
$username = 'your userid with your hosting company';
$password = 'hosting company provided mysql password';
$database = '';
Will that be a big security issue of everyone being able to see your MySQL password?
Not really, because only you and the people working for the hosting company should be able to see the PHP code. And the people working at the hosting company will have the root password to the database anyway, so they could look at what you have in the database without your particular mysql credentials.
But using <? rather than <?php may cause your code to be transmitted instead of run on some server setups. So if you upload it that way, initially some users may end up seeing the passwords you have in the code before you figure it out and fix it.
Another more serious issue than this is if the hosting company has you using phpmyadmin over http rather than https, because every time you login to it your credentials will be transmitted in plain text.
Well there a couple of things in play here.
Since you mentioned SQLi and considering you're using PHP + MySQL, you should look into doing prepared statements, by using the prepare(), bind() and execute() functions.
Second, even before thinking about putting something online or using SQL properly is to change the default username/password.
Now if you want to put your server online, I'm assuming you have a server or the credentials to someplace where you can ran either XAMP or configure its services by hand. Anyway, those credentials are the Database's, which are different from your host server login credentials.
As long as that .php file is properly secured on the server, it's common practice to have the username/password there in the file.
I am trying to send two values to my server to be input into a database in the same row, the problem I have is that it isn't possible to send both values in one request. So what I want to do is send both the values in separate requests but handle them on the server at once so I can add the values into a database as one entry. My php isn't very strong, and I have no idea how to go about doing this. Is it possible? How would I do it?
Here's what I have so far:
<?php
$user = "user";
$pass = "pass";
$table = "database";
if(isset($_POST['currentUser']))
{
$userID = 'currentUser';
}
if(isset($_POST ['e.regid']))
{
$regid = 'e.regid';
}
if ($regid && $userID != null)
{
$con = mysqli_connect("localhost", $user, $pass);
mysqli_select_db($con, $table);
if (mysqli_connect_errno$con))
{
echo "Error connecting to the DB: " . mysqli_connect_errno());
}
else
{
"INSERT INTO gek_devices('regid', 'pin') VALUES ($regid, $userID)";
}
}
No, due to network latency and unreliability there's not even any guarantee that both requests will ever arrive at the server, let alone within a minute apart, let alone that you could run code once handling both requests. In practice chances are over 90% that both requests will not even be handled by the same Apache process on the server, given that a default Apache install on *nix will prefork 10 'spare' instances.
If you need to process the data 'simultaneously` you need to send them in the same request, that's the only way to guarantee atomicity.
Your intended solution is completely impossible, but also a glaring XY problem. Solve why you can't send the values simultaneously right now instead of focusing on hacky workarounds following that.
This is the code that connects to my SQL database. I'm new with this stuff and it seems to be semi-working but certain features on my website still don't work.
<?php
$con = mysql_connect("localhost","username","password");
$select_db = mysql_select_db('database1',$con);
/*$con = mysql_connect("localhost","username2","password2");
$select_db = mysql_select_db('database2',$con);*/
?>
This is the site in question: http://tmatube.com keep in mind the credentials above are filled in with what the programmer used for testing on his own server... ;) unfortunately I don't have access to him for support anymore.
Anyway, here's my thoughts on how this code needs to be edited maybe someone can chime in and let me know if I'm correct in my assumptions:
<?php
$con = mysql_connect("localhost","username1","password1"); -------------<<< leave this line
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con);
/*$con = mysql_connect("localhost","DB_USERNAME_HERE","DB_PASSWORD_HERE");
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con);*/
?>
Ok - now on to a few problems I noticed...
What does this do? /* code here */? It doesn't work at all if I leave that bit in.
Why is it connecting to database twice? and is it two separate databases?
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con); <<<---- single '
When I tried to see if that line was correct the examples I saw had quotes like this
$select_db = mysql_select_db("DATABASE_NAME_HERE",$con); <<<---- double "
Which one is right?
He didn't leave it out. What he did was leave the database to be connected using the root, which has no password. The other connection (which is commented out) is using another user, rajvivya_video, with a password defined.
In testing it MIGHT be okay to connect to root and leave it without password, but even that is not recommended, since its so easy to work with a user and password defined (besides root).
Here is php mysql connect with mysqli:
<?php
$link = mysqli_connect("myhost","myuser","mypassw","mybd");
?>
No difference here with ' or ". (Anyway use mysqli and you can the wanted db as 4th parameter.) php quotes
/* comment */ is a commented out so the php does not care what is inside so only 2 first rows of are affecting (they are same mysql database on the local machine and 2 different user + password combinations). Comment in general are used to explain the code or removing part of the code with out erasing it. php commenting
I am EXTREMELY new to the html/php scene but I have been working at this for hours. I am stumped.
I am trying to connect to a sql database that will store username and password information. I use fortune city for hosting and I have already used their phpAdmin to setup up all of the necessary stuff (db, tables, etc..).
I am using Eclipse with Zend on the side. I am also running Sql Server and Apache 2.2.
I believe my issue is the following:
I have a db located at a certain ip address (remote fortunecity server) and I am testing my project on the local server. Fortune city offers two different host names, one for internal connections and one for external connections. I get different results from each one:
If I connect to the internal site it doesn't make any connection, I know this because of my die statement. If I connect to the external host it connects, but doesn't allow me to connect to the database. (see cases below code)
Currently my process is as follows. (PLEASSSSE TELL ME A BETTER WAY IF I'M DOING THINGS THE INEFFICIENTLY, I feel dirty every time I do it!!)
Create or edit my index.php, login.php, etc... in eclipse.
Copy the files that I edit into my Apache root.
Go back to eclipse and run the project in a browser "firefox."
repeat n to the n times.
Keep in mind my sql database is located on the net
Can this be done? Testing locally while accessing a db on the net?
Here is the code:
<?php
if (!isset($_POST['username']) || !isset($_POST['password'])) {
header( "Location: http://localhost/index.php" );
}
elseif (empty($_POST['username']) || empty($_POST['password'])) {
header( "Location: http://localhost/index.php" );
}
else{
$user = addslashes($_POST['username']);
$pass = md5($_POST['password']);
$dbHost = "mysql3341.dotsterhost.com";
$dbUser = "*********";
$dbPass = "******";
$dbDatabase = "**********";
$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
$result=mysql_query("select * from userInfo where username='$user' AND password='$pass'", $db);
$rowCheck = mysql_num_rows($result);
if($rowCheck > 0){
while($row = mysql_fetch_array($result)){
session_start();
session_register('username');
echo 'Success!';
header( "Location: checkLogin.php" );
}
}
else {
echo 'Incorrect login name or password. Please try again.';
}
}
?>
Again, I have never made it past
Case :1 $db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
Case :2 mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
Thanks for reading my novel!
Can this be done? Testing locally while accessing a db on the net?
Yes you can, but be aware if you are storing anything sensitive in your database you probably wouldn't want to be sending that data unencrypted over the net. (Unless you are connecting over a VPN or another type of secure network connection.)
Usually you'd want to setup a development environment on your local box or you can edit your files locally in something like Aptana (http://www.aptana.com/) and have it automatically deploy your files to the server every time you save.
Also, as suggested in the comments, using a framework to develop on usually give you a powerful database library without the need to reinvent it on your own. (That is unless you feel like wrapping your own!)