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).
Related
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.
So i have this code which is supposed to send name and email address to the database. Not only is it not doing that, but in my second line of code where I want it to print_r whatever has been entered I still get a blank screen. Is there a setting to show what errors are occurring in my code that I've got turned off or is this code wrong?
//Only process the form if $_POST isn't empty
if(! empty($_POST)){
print_r($_POST); exit;
//Connect to MYSQL
$mysqli = new mysqli('localhost', 'root','','snippets');
//Check connection
if($mysqli ->connect_error){
die('Connect Error: '. $mysqli->connect_errno . ': ' . $mysqli->connect_error);
}
//Insert data
$sql = "INSERT INTO user(name, email) VALUES ('{$mysqli->real_escape_string($_POST['name'])}','{$mysqli->real_escape_string($_POST['email'])}' )";
$insert = $mysqli->query($sql);
//Print reponse from MySQL
if($insert){
echo "Success! Row ID: {$mysqli->insert_id}";
}else{
die("Error: {$mysqli->errno}:{$mysqli->error}");
}
//Close connection
$mysqli ->close();
}
?>
<form method="post" action="">
<input name="name" type="text">
<input name="email" type="email">
<input type="submit" value="Submit Form">
</form>
$_POST is not being populated on POST requests. The most likely cause is that your PHP is set to not create the superglobals ($_POST, $_GET...).
The fix may be in your php.ini file. Open that file and look for the setting variables_order (See the docs). I suspect that this has been commented out (or doesn't exist) in your configuration file. Set it to:
variables_order = "EGPCS"
If you're not sure where the active php.ini is located, change your PHP file to have just the code below:
<?php
phpinfo(); exit;
A lot of info about your installation will appear. The value of Loaded Configuration File will tell you which file to edit to change your PHP settings.
If all else fails, you can extract the submitted values yourself; it's really simple:
$args = []; //will hold the submitted arguments
parse_str(file_get_contents('php://input'),$args);
From there, just use $args as you would use $_POST. It contains your form inputs. Just be aware that it would also contain the inputs that you'd typically see in $_GET, when a "GET" request is made
Turns out that there was a conflict between my WAMP server and the built-in server provided by Phpstorm which is the IDE I am using. as #Beetlejuice suspected there was also an issue in my php.ini file. This should have been uncomented and set to On: ;enable_post_data_reading = Off
Thank you to everyone who helped.
"INSERT INTO user(name, email) VALUES ('{$mysqli->real_escape_string($_POST['name'])}','{$mysqli->real_escape_string($_POST['email'])}' )"
Try using a backslash for "name" and "email" attributes. This will reduce ambiguity in quotes. Most of the time, that is the issue.
So, it would look like this:
"INSERT INTO user(name, email) VALUES ('{$mysqli-
>real_escape_string($_POST[\'name\'])}','{$mysqli->real_escape_string($_POST[\'email\'])}' )"
However, I think it would be best practice use "real_escape_string" before this query. Generally, the php is not run when used in a query string. So, save
$mysqli->real_escape_string($_POST['name'] in one variable AND
$mysqli->real_escape_string($_POST['email'] in another variable and then,
add it to the query
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
}
I am using LAMP stack to develop a PHP application. I am using require_once to include class files. I need to use the functions in those class files in more than one PHP page. So, I am including those class files in all the required PHP pages using require_once. But, if I include those class files in more than one page, the PHP file goes blank. It displays nothing. View source also displays nothing.
Files: test.php, process.php and class.test.php
test.php has
<?php
session_start();
require_once 'classes/class.test.php';
.
Few more classes
.
.
?>
<html>
<form name = "myForm" method="POST" action="process.php">
<input type = "text" name="username" value=""/>
<input type = "submit" value="Submit" />
</form>
</html>
process.php
<?php
session_start();
require_once 'classes/class.test.php';
$obj_test = new test();
$obj_test->test();
?>
class.test.php
<?php
session_start();
require_once 'class.misc.php';
require_once 'config.php'; //DB connection details
function test()
{
$obj_misc = new misc();
$id = $obj_misc->random_ID();
$username = $_POST['username'];
$query = "INSERT INTO test_table VALUES ('$id','$username',NOW());
mysql_query($query);
}
?>
Now, it returns a blank page. If I comment out the require_once in process.php, the test.php page displays the form, but on submitting the form the process.php throws an error "class test not found".
I am struggling with this problem for the past 2 weeks. :( It was working fine before that. I don't understand what went wrong. Please help.
You have an error in the PHP code for process.php; you are missing a semicolon:
require_once 'classes/class.test.php'
should be:
require_once 'classes/class.test.php';
If that doesn't fix it, then there is probably some other error somewhere in your code. Without access to the full source, we won't be able to do much.
For future reference, if a page goes blank, there is usually a problem with the PHP source code (ie, some type of interpreting error). As part of good debugging tactics, look into display_errors and error_reporting
Try out with
error_reporting(E_ALL);
Sounds like your error reporting is turned off. You should check your error logs to see what exception is being thrown when it's failing silently (that will give you a little more insight).
Additionally, you may want to add this at the top of your process script:
error_reporting(E_ALL);
Require once is a function ...
try adding the parens ...
require_once( 'classes/class.test.php' );
looks like you are missing a closing qoute on the sql query
$query = "INSERT INTO test_table VALUES ('$id','$username',NOW());
mysql_query($query);
should be
$query = "INSERT INTO test_table VALUES ('$id','$username',NOW())";
mysql_query($query);
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.