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
}
Related
This might seem stupid, but I have this simple php code, and it is not echoeing the message to the screen, neither is redirecting the page. I am not sure why. I tested the db connection and it is working, also the user and password used for test exist in the db (of course info changed here for security). What am I doing wrong? What am I missing?
<?php
session_start();
include_once("C:/webroot/connect.php");
if (isset($_POST['submit'])){
//$user=$_POST["httpd_username"];
$user="usernameXYZ";
//$pass=$_POST["httpd_password"];
$pass="passXYZ";
$query= "SELECT * FROM regtrack_users WHERE user_name='$user' and password='$pass'";
$result =pg_query($query) or die ("Unable to connect to db");
$numrows=(pg_num_rows($result));
if($numrows>0){
$row=pg_fetch_assoc($result);
$dbuser=$row['user_name'];
$dbpass=$row['pass'];
echo "$dbuser and $dbpass";
}
header("Location:login.php");
}
?>
It might because of this part:
if($numrows==1){
$row=pg_fetch_assoc($result);
$dbuser=$row['user_name'];
$dbpass=$row['pass'];
echo "$dbuser and $dbpass";
}
You should check if the $numrows variable really contains 1, or you should try $numrows>0 instead of $numrows==1
Root of the problem lies in 3rd line, you are providing a path to a file to include in wrong way. Read here about how properly you should be providing paths to files in php code:
http://yagudaev.com/posts/resolving-php-relative-path-problem/
I am been trying to connect my android application with my 000Webhost account's MySql Database using PHP.
My Webhost server details are:
saravananoct14.web44.net
username: xxxx
HomeRoot: /home/xxxx
ServerName: server10.000webhost.com
IPAdress: "ipaddress"
MySQL database name:xxxx_sara
MySQL user name:xxxx_sarav
password for mysql:xxxx!4
my table name is ms.
column names:EMAIL_ID,Q1,Q2,Q3.
I have saved my .php files under public_html folder in phpmnMyAdmin.
config.php file is:
<?php
define ('DB_USER',"xxxx_sarav");
define('DB_PASSWORD',"xxxxx!4");
define('DB_DATABASE',"xxxx_sara");
define('DB_SERVER',"mysql1.000webhost.com");
?>
add.php file:
<?php
$res=array();
if(isset($_POST['EMAIL_ID']) && isset($_POST['Q1']) && isset($_POST['Q2']) && isset($_POST['Q3'])){
$EMAIL_ID=$_POST['EMAIL_ID'];
$Q1=$_POST['Q1'];
$Q2=$_POST['Q2'];
$Q3=$_POST['Q3'];
require_once __DIR__.'connect.php';
$db=new DB_CONNECT();
$result=mysql_query("INSERT into ms (EMAIL_ID,Q1,Q2,Q3) values ('$EMAIL_ID','$Q1','$Q2','$Q3')");
if($result){
$res["success"]=1;
$res["message"]="success";
echo json_encode($res);
}else{
}
}
else
{
$res["success"]=0;
$res["message"]="Required field(s) missing";
echo json_encode($res);
}
?>
I have used the same android program to connect it with my local wamp server and it worked.
I have given the following string as Url to parsed using JSON parser is:
http://"ip address"/add.php .
I am getting errors as Error Parsing the data. Cannot be converted into !Doctype...
I am pretty sure that I must make a change in the url. But could not find what changes I need to implement so that I can connect with the database.
Help me pls....
So after we discussed your Problem a long way I will write an Answer:
Please do not call your webservice via IP, always take the URL (especially when you have a webhoster)
Always check your PHP Script via a Browser on your PC, you will see the errors directly.
Debug the errors shown by your php script
This is my first time transferring my local dev site to another local site to test out, and can't access the database in the new site. Both computers are running XAMPP on Macs. The test site has successfully installed XAMPP, and has placed database files under Applications/XAMPP/xamppfiles/var/mysql. The test user is able to start Apache and MySQL, and see database files in PHPMyAdmin. The test user is also able to access the local web site with no error messages.
EDIT: The database files were copied over by copying/zipping the file on my end, and unzipping/dropping the copied files on the test end.
However, the local web site does not seem to see the database. Pages that are supposed to return data just show the default "sorry, we're sold out" message or show "image not found" graphics, and the admin is unable to log in.
The index page calls
include_once "common/base.php";
which consists of
<?php
// Set the error reporting level
error_reporting(E_ALL);
ini_set("display_errors", 1);
// Start a PHP session
session_start();
$_SESSION['docroot'] = $_SERVER['DOCUMENT_ROOT'] . '/mysite/';
// Include site constants
include_once $_SERVER['DOCUMENT_ROOT'] . "/inc/constants.inc.php";
if ( !isset($_SESSION['token']) )
{
$_SESSION['token'] = md5(uniqid(rand(), TRUE));
$_SESSION['token_time'] = time();
}
// Create a database object
try {
$dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME;
$_db = new PDO($dsn, DB_USER, DB_PASS);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
?>
If there was a connection problem, I would expect to see an error message returned, which I can verify by changing the constants in inc/constants.inc.php to bogus values. So I don't believe there's a connection problem.
If you were in my position, what would you check?
EDIT: I just found out about the Export function in PHPMyAdmin. I'm going to try deleting the db files that were copied over, exporting the files from PHPMyAdmin, and then importing them in the test machine.
EDIT: I just had the test machine do a simple
$sql = "SELECT FirstName From users";
$stmt = $_db->prepare($sql);
$stmt->execute();
$aaData = array();
while($row = $stmt->fetch(PDO::FETCH_NUM)){
$aaData[] = $row;
}
$stmt->closeCursor();
print_r($aaData);
on the index page, it shows the correct list of users. So the connection is good,
and there's an issue elsewhere. Would y'all say that I still need to delete the copied db and use the "correct" way (export/import), or is that a waste of time?
FINAL EDIT: I did redo the move using Export/Import and everything is working well now. Thanks to all.
First off, zipping files in the mysql data directory and moving them is not the best way to go. It can work if you have completely flushed/shut down the mysql server before moving them. You are better off using mysqldump or a similar tool to move entire databases at a time.
It sounds to me like you moved over your app's database files, but you probably forgot to add the user/password credentials to the new MySQL setup. You mentioned you use phpMyAdmin, so when you login on the other machine click the "Privileges" tab and make sure it matches up with the Privileges tab on your dev machine.
If it's not that, then it is entirely likely that by zipping and copying the files some/all of the tables were corrupted. Try using phpMyAdmin's Export and Import capabilities to move the database over. If the data is very large let me know and I can give you some command line entries to run.
Hope this helps.
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).
Here's my config file:
<?php
#config variables
$host = ''; #your database host
$user = ''; #your database username
$password = ''; #your database password
$database = ''; #your database title
$page_title = ''; #this appears at the top of the webpage and in the browser tab/window.
$tbl_prefix = ''; #the prefix on your database tables.
$installed = false; #if false, you'll be redirected to an installation page.
if($installed == false) {
header('Location: install/index.php');
}
else {
#connect to db
$consult_err = ' Consult lib/sqlerrors.html';
$connect = #mysql_connect($host, $user, $password)
or die('Errno(1) - Invalid connection details.' . $consult_err);
#mysql_select_db($database, $connect)
or die('Errno(2) - Couldn\'t connect to database.' . $consult_err); #select database
}
?>
I have an installation script that gets all the variables above from a user, checks to make sure there's a mySQL connection/database present, and creates some tables. However, I haven't found a good way to edit the above file with the user's input.
I'm rather stuck on where to go from here, but I need the end result to be taking input from a form, and having the variables in the configuration file reflect that input.
Any suggestions?
I think that doing this will only lead you down a very difficult, twisty path. May I recommend using PEAR's Config package? It can generate, manipulate, and read configuration files in INI, PHP array or constant, XML, or generic formats.
Another option would be to only store the values that change very rarely (e.g. database connection info) in the configuration file and then store the rest of the configuration options in the database. This is how most larger PHP applications do it, I believe (I'm thinking of WordPress specifically). Users will have to edit the file manually if they want to change those settings, but since the more frequently-changed settings are in the database (and that's easy to hook up to your configuration form), they'll only very rarely have to edit the file.
You can use the PHP filesystem functions to open the file and write out a modified version.