PHP chat application: Accumulation+Concatenation working, but only on individual hosts? - php

I have a textarea in which you type your message and a textarea that is supposed to output all messages from any hosts on my page:
<form action= "chatroom.php" method="post">
Chatbox:<textarea name="results" rows="10" cols="40">
<?php
$accum = $results . $message;
echo $accum;
?>
</textarea>
<br>
Send message:<textarea name="message" rows="7" cols="30"></textarea>
<input type="submit" value="Send" name="send">
</form>
It works fine, but only on any individual computer.
I don't believe it's a server issue (using WAMP). The site is on the web, and other echoes do appear on other clients such as
echo "<br>Connected to MySQL.<br>";
But, when I send a message on my server computer, it does not appear in the Chatbox textarea on my host computer, or vice versa.
Already tried moving the Chatbox textarea outside the form, which did not solve the problem.
Tried just echoing $accum straight onto the page and not into the textarea, which did not fix the problem.
<?php session_start(); ?>
at the start of chatroom.php didn't work either.
As a side note I'm using mySQL and used "localhost" rather than my external IP in mysqli, in my php code. I don't think this is the problem because the database does add a new user when they sign up remotely.
I thought that all PHP was executed on the server, so shouldn't $accum be picking up text from all hosts?
I'm wondering if the problem is that all clients have their own $message, $results and $accum variable because each client is connected to the server, and not to each other? So would that explain the behavior? (Or am I not completely correct?)
And forgot to mention, I am refreshing the page via clicking Send again to check if the text appeared; I haven't implemented auto-refresh yet.
edit:
in chatroom.php:
<?php
$message = $_POST["message"];
$results= $_POST["results"];
?>
I'm just turning the html name parameter into a php variable, then posting that variable right back onto the page in a different location.
Also have:
<?php
$username = $_POST["username"];
$word = $_POST["word"];
$conn = new mysqli("localhost", "user", "pw", "", 8080);
if($conn->connect_error)
echo $conn->connect_error;
else
echo "<br>Connected to MySQL.<br>";
if ($conn->query("create database chatdb")===TRUE)
echo "Created database";
else
echo $conn->error;
if ($conn->query("use chatdb")===TRUE)
echo "using chatdb";
else
echo "<br>Not using chatdb<br>";
if (
$conn->query("create table
users(
id INT(6) unsigned auto_increment primary key,
username varchar(30),
word varchar(30)
)")===TRUE)
{
echo "table created";
}
else
echo $conn->error;
if ($conn->query("insert into users (username, word) values ('$username',
'$word')")===TRUE)
echo "<br>inserted values<br>";
else
echo $conn->error;
?>
My sign-up page:
Sign Up:
<form action="chatroom.php" method="post">
Username:<input type="text" name="username"><br>
Password:<input type="text" name="word"><br>
<input type="submit" value="Sign Up!" name="signup">
</form>
Again, I don't think the mySQL has anything to do with it-- but I could be wrong.

The HTTP protocol is a Request/Response protocol. When someone displays the chat page, I assume your code reads messages from the database and shows those.
There was a request (GET /chat.php, Response is HTML for chatpage) and at that point the connection between the web browser and server is closed.
After that, there is no way for that web client to know that someone posted a new message into the database unless:
There is a persistent socket connection (websockets) OR
Your application is polling the server (perhaps using a timer and ajax calls OR
Your client application is refreshing at some interval
Solutions 1,2 and 3 require some level of javascript competency.

Related

Securing a PHP form and MySQL database

I started using php and MySQL last week so I apologise if my lack of basic understanding is frustrating.
I have a simple html form on my website that records a name, an email address and a short message.
<form action="insert.php" method="post">
Your full name:<input type="text" name="name">
Email address:<input type="text" name="email">
Short message:<textarea cols="30" rows="3" name="message"></textarea>
And insert.php looks something like this...
<?php
$con=mysqli_connect();
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$message = mysqli_real_escape_string($con, $_POST['message']);
$sql="INSERT INTO Donators (name, email, message, date)
VALUES ('$name', '$email', '$message', NOW())";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
header('Location: thankyou.php');
exit;
mysqli_close($con);
?>
This is then sent to a mysql database which i manage with php my admin.
My questions are...
Is the code safe for the user i.e. are there email addresses protected?
Is the code safe for me i.e. is the data being submitted protected in my database?
And finally what is the best way to stop "bots" filling in the forms i.e. is recaptcha the best thing to implement? I tried using googles recaptcha but maybe because of my css or something, it didn't appear correctly.
Thank you very much for your help!
James
1) It's never 100% secure. The code seems find but you should be aware of new patches and releases to update your MySQL instance as well as PHP and HTTP services.
2) Again... yes and no... it's your role to be sure it is. So as long as you don't display them on any webpage we can assume it's "secure"
3) The best way is to make your own module so you won't suffer from bots that are "generics". By generic I mean those that counter generic captcha module. You can for example ask a simple humain question to the user. This should be sufficient enough to avoid the biggest spamming bots.
Best regards, hope this will help.

Protecting database password in a PHP file?

I have a php file which retrieves some important data from my database, for now if anybody access the php file via URL, it directly displays the data which i don't want to happen.
Is it possible create a password input box which will prompt for the database password and assign its value to $password variable (see the code below) , so that only if the user inputs the correct password, only then the file will interact with the database?
UPDATE TO THE EXAMPLE CODE :
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result)) {
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
mysqli_close($con);
?>`
When this php file is accessed via a browser, it displays :
Peter Parker
Glenn Forbes
I don't want people to see the output directly! I want them to first input the password, so that php file interacts with the database and displays the output!
Hope you people got me this time!
If I were you (and if I'm understanding your problem correctly) I would use an htaccess file. Basically, you will create two files in the directory you want to protect. The first, you will name .htaccess. That's all you need in the file name. Open the file in an editing program (e.g: Notepad++) and insert the following code:
AuthType Basic
AuthName "restricted area"
AuthUserFile "the/path/to/the/directory/you/are/in/.htpasswd"
require valid-user
The .htpasswd you see is the file name of the second file you will create. Create that file (with the name .htpasswd), and open it to edit it. In that file, type in the username of the person who is to enter the directory.
JohnDoe
Followed by a colon.
JohnDoe:
Now, go to a website like http://www.htaccesstools.com/htpasswd-generator/ and type in the Username (just put in "test") and password you want in the fields provided. Submit the information.
After you do that, it will pop up with a formatted line of information. Copy the mess of letters after the colon and paste them after the colon in your .htpasswd file. Save your work.
JohnDoe:$apr1$eBsB98Mg$93ckYxSmT5BBfPqOS5a/6.
Now that you have done all that, when someone goes to the directory on your website, they will be prompted to give the username and password. If they know it, it will let them in, and then display what is in your PHP file (you will need to make sure the file is named index.php.
I hope that helps!
There are many ways...
<?php
if($_GET['token'] != 'a1a2a3a4a5') {
die('Wrong request!');
}
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result)) {
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
mysqli_close($con);
?>
Then access your page from:
http://www.example.com/readdata.php?token=a1a2a3a4a5
Apache (or any other server) will execute files based on the file extension it sees and that it has been told what to do with. If that isn't told specifically, it will display it simply as text.
If your server is running PHP files fine, you can include any filename you like - that includes the extension and PHP will assume it is simply PHP. If you try to get tricky however and call it a .php5 or a .include and you haven't set up your server to run these file types as PHP, it will be output to the user as simply text.
Set up the file types properly on your server or call them all by the default extension.
Based on the code you provided:
<?php
$host = "localhost";
$db_name = "NAME_OF_THE_DATABASE";
$username = "root";
$password = "PASSWORD_OF_THE_DATABASE";
?>
A user entering this exact URL will see a grand total of NOTHING. That is because when the file is being executed as PHP, it simply assigns the variables values - it doesn't ever display them.
If the file isn't associated as a PHP executable file, your server will send the contents to the user as they are - showing all your code as you wrote it.
From your question what i understood is you don't want any body to see the password, so i think
you can encrypt you php code and still run it on the server
user the following tools
you can definitely hide/encode/encrypt the php source code and 'others' can install it on their machine. You could use the below tools to achieve the same.
Zend Guard
IonCube
SourceGuardian
phpSHIELD
You should not see the code in the screen unless your file add .php, check extension.
I suggest you separate database detail in a new php file, and move it in up level directory
HTML CODE:
<form action="{your url}">
Please enter you password:<input name="password" type="password" />
<input type="submit" value="Submit" />
</form>
PHP code:
$password=$_GET['password'];
if($password=="1234"){
echo 'correct password';
//and add your code here
}

How to use mysql_connect(...) on a web hosting service

I just started using a web hosting service and I'm new to PHP and MySQL. I was trying to use the video I see here https://www.youtube.com/watch?v=gvGb5Z0yMFY as a simple recipe on adding a row to a table. I have a table called forumites in my MySQL database and it has 3 columns -- username, email and password.
HTML form:
<div class="boardbox hidden" id="regdiv">
<form id="regform" action="newuser.php" method="post">
<p>Username:<input class="threadipt" type="text" name="username"></p>
<p>Email address:<input class="threadipt" type="text" name="email"></p>
<p>Password:<input class="threadipt" type="text" name="password"></p>
<button onlick="phpfunction">Create Account</button>
</form>
</div>
newuser.php:
<?php
$conn = mysql_connect();
if (!$conn)
echo 'could not connect';
$db = mysql_connect_db('forumites');
$name = $_Post['username'];
$em = $_Post['email'];
$pass = $_POST['password'];
if (!mysql_query("INSERT INTO forumes VALUES('$name','$em','$pass')"))
echo 'Could not enter user info:';
?>
I think the part that is confusing me is the mysql_connect(...) command. In the video I'm watching, the guy writes mysql_connect('localhost', 'root', ''), but I'm not sure if he's using a web hosting service like I am. I read the W3Schools page on the command http://www.w3schools.com/php/php_mysql_connect.asp but it's not very informative.
Long story short, I'm trying to connect to the databse on my web hosting service and I'm probably doing a ton of things wrong. I was wondering if you guys could point out a few of the things I'm doing wrong.
to answer your question about 'localhost' when creating a database connection, and this applies to mysqli and PDO as well, which as John Conde commented, you should be using instead of mysql_
if your database is hosted on a computer other than your local machine, the hostname 'localhost' can be replaced either with an IP address, or with a domain address.
for example if you're on an internal network, and your database is on another computer within your network, you can use '192.168.1.15' (if the database computer's IP ends with 15, that's just an example, you need the actual IP of that machine)
if it's on a website, you can use the website, for example, if msn is hosting your database, your hostname would be www.msn.com. your host provider should have something like cpanel which provides you with that sort of information

Whats wrong with this PHP/MySQL script? It Will Not Work Properly

PLEASE CLOSE THIS I HAVE FIGURED OUT THE
------------MY PROBLEM----------------------------------------
mysql_select_db("members") or die(mysql_error());
echo "Database Found! ";
----------------SOLUTION------------------------------------------------------------------
mysql_select_db("a2670376_Pass") or die(mysql_error());
echo "Database Found! ";
Here's my script
<?php
$ud_ID = $_REQUEST["ID"];
$ud_firstname = $_POST["ud_firstname"];
$ud_surname = $_POST["ud_surname"];
$ud_FBID = $_POST["ud_FBID"];
$ud_IMG = $_POST["ud_IMG"];
mysql_connect('mysql13.000webhost.com'… 'a2670376_Users', 'Password') or die(mysql_error());
echo "MySQL Connection Established! <br>";
mysql_select_db("members") or die(mysql_error());
echo "Database Found! <br>";
$query = "UPDATE stokesley_members SET firstname = '$ud_firstname', surname = '$ud_surname',
FBID = '$ud_FBID' WHERE ID = '$ud_ID'";
$res = mysql_query($query);
if ($res)
echo "<p>Record Updated<p>";
else
echo "Problem updating record. MySQL Error: " . mysql_error();
?>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?=$UID;?>">
IMGNU: <input type="text" name="ud_img" value="<?=$IMGNU;?>"><br>
First Name: <input type="text" name="ud_firstname" value="<?=$firstname?>"><br>
Last Name: <input type="text" name="ud_surname" value="<?=$surname?>"><br>
FB: <input type="text" name="ud_FBID" value="<?=$FBID?>"><br>
<input type="Submit">
</form>
Here's my error
MySQL Connection Established!
Access denied for user 'a2670376_Users'#'10.1.1.40' to database 'members'
I don't know what the 10.1.1.40 is about though I have tried changing it to
("mysql13.000webhost.com", "a2670376_Users", "Password")
and still the same thing
now this confuses me a lot so I'm not even sure there is an error but i think there is cause if there was no error the script would show
could this error be caused because I haven't made the file update.php yet?
i have worked out many bugs in this already but cant seem to get this one out please help me you will be a lifesaver and give me credit for noobish script I'm only 13
I don't need to grant rights because I already have rights I have a file named connect.php it connects the register and login scripts that I have that works fine but this wont..
http://fni.site11.com/edit.php is the page I am working on
Please check database location and set the privileges for user.
first of all switch from mysql_ to mysqli_ or PDO they are more reliable.
Then, check the spelling (host, user and password) and the case ! password and username are case sensitive.
Be sure that user a2670376_Users has privilege for selecting, updating and inserting
First make sure that the user specified above enough privileges to select the data from the db given. you can login to the db hosting account and check the privileges of the user "a2670376_Users". And 10.1.1.40 might be your hosted server IP Address.
If your db hosted on other server then you need to grant the access from * not only for localhost.
When creating MySQL databases and users, you then need to grant the user privileges to databases. This allows you to create multiple users with different access levels, for example a user that can do everything, and another user who may only have read (SELECT) access, so they can’t INSERT/UPDATE/DELETE or DROP databases and tables.
If you use something like cPanel, you can add users to your database from there.

php sqlite not storing data

I am trying out sqlite with php. On the server when I execute the command sqlite3, it shows the version and help option suggesting that sqlite is installed there. My folder structure is like this: /username/public_html/
Now I created a db called "chatuser.db" with a table "Users" and two columns "Username" and "Password" using sqlite3 command at /username
I then copied the db using WinSCP to my windows folder and then copied it back to the server here: /username/public_html/ (I know it is not a good idea to keep db file in public_html, but am just trying out an example). Now I have the following php file:
add.php:
<?php
$password = $_POST['password'];
$username = $_POST['username'];
$name_es = sqlite_escape_string($username);
$password_es = sqlite_escape_string($password);
if (!empty($username)) {
$dbhandle = sqlite_open('chatuser.db', 0666, $error);
if (!$dbhandle) die ($error);
$stm = "INSERT INTO Users(Username, Password) VALUES('$name_es', '$password_es')";
$ok = sqlite_exec($dbhandle, $stm, $error);
if (!$ok) die("Error: $error");
else echo "Success";
}
?>
index.html:
<html>
<head>
<title>Login Trial</title>
</head>
<body style="font-size:12;font-family:verdana">
<form action="add.php" method="post">
<p>
Name: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br><br>
</p>
<p>
<input type="submit">
</p>
</form>
</body>
</html>
On clicking the submit button, it loads add.php, but does not show me the success message nor any error message. I am not able to figure out why. As an added note, I have done chmod 777 of chatuser.db as well. This is my first introduction to sqlite, any help would be great. Thanks
[SOLVED]
Found the issue, it was version mismatch. sqlite_open will not work. Alternative from this solution:
Error: file is encrypted or is not a database
My guess would be that sqlite_open triggers a fatal error and your PHP isn't configured to show them.
Try placing one echo before the sqlite_open and one after - if only the first one is echo'ed, you know what the issue is.
You will probably want to load the sqlite3 module in PHP.
-edit-
Actually, that only applies to PHP 4, which you're probably not using anymore. Either way, make sure that your PHP outputs errors (go into php.ini and set display_errors to On and error_reporting to E_ALL).

Categories