ACRA Insert report into my server's database - php

I successfully configured ACRA to send my caught exceptions to my server, the problem is I can't insert the report into the database:
#AcraCore(buildConfigClass = BuildConfig.class)
#AcraHttpSender(uri = "http://www.myserver.com/crashreports/addreport.php",
httpMethod = HttpSender.Method.POST)
public class MyApplication extends Application {
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
ACRA.init(this);
}
}
I know it sends somethings because I see an empty entry in my phpMyAdmin, but I can't get the report inside the database:
<?php
$link = mysqli_connect("localhost", "root", "pass", "db");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$report = mysqli_real_escape_string($link, $_REQUEST['']);
// attempt insert query execution
$sql = "INSERT INTO VoiceRemoteCrash (report) VALUES ('$report')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
I've searched docs, but didn't find much info, and my PHP knowledge is somewhat basic.

$_REQUEST[''] will returns NULL and will throw an "undefined index" notice.
You could get your report from POST raw data using file_get_contents('php://input').
I suggest you to have a look to : How can I prevent SQL injection in PHP? and use parameterized queries.

This line references a nonsense variable:
$report = mysqli_real_escape_string($link, $_REQUEST['']);
You want something like:
$report = mysqli_real_escape_string($link, $_REQUEST['form_variable_name']);
But you shouldn't even do that, because the real_escape_string() functions can not be relied on to prevent SQL injection. Instead, you should use prepared statements with bound parameters, via either the mysqli or PDO driver. This post has some good examples.

Related

Php script runs fine but doesn't create the table in the database

Hey guys all the elements of my php script seems to work, it connects to the database, its gets the input from a different page and saves it as a variable, i have echo'd the sql statement and run it in myphpadmin and it works but when i do it from the php script everything runs as expected except no table is created in the database.
appreciate any advice you can throw at me
thanks guys
<?php
$con = mysqli_connect("localhost","odoylegaming","pwd","odoylegaminggallerydb");
if(!$con)
{
die("Connection failed: ". mysqli_connect_error());
}
$Gallery_Name=$_POST['newgallery'];
if($Gallery_Name=="")
{
header("Location:Profile.php");
}
else
{
mysqli_select_db($con, "odoylegaminggallerydb");
$query = "CREATE TABLE IF NOT EXISTS $Gallery_Name(User_Name VARCHAR(25) PRIMARY KEY, Picture VARCHAR(250), Description VARCHAR(250), Date_Posted TIMESTAMP)";
$result = mysqli_query($query, $con);
if(false===$result)
{
die("table create failed: ". mysqli_error($con));
}
else
{
echo $query;
}
}
?>
Please read the manual on mysqli_query():
http://php.net/manual/en/mysqli.query.php
The connection argument comes first, not second as you have it now.
By the way; you're open to a serious sql injection here. Use a prepared statement.
Creating a table from user input isn't safe at all.
Also add exit; after header, otherwise your code may want to continue to execute.
Your code is vulnerable to sql injection please consider using prepared statements or a library like PDO to help guard against that sort of thing, that being said you are creating a dynamic table which is not a thing you can do with parameters in my example I added a few cleaners but this sort of thing isn't a safe design by its very nature. You really shouldn't be creating tables dynamically inside your application, if you need to create separate galleries rely on the relational nature of MySQL and have a Gallery table with a user_id and a User table where that ID is sourced then insert new entries using parameterized queries where if the user doesn't exist you create them and then add a gallery entry with that user's id.
The question
The root of your issue in this case is that you are supplying your arguments out of order for the query, your connection variable should come first. In my example I use object oriented mysqli instead of the procedural way, if you are just learning I would advise you to use classes (like mysqli) as objects even if they happen to have a procedural implementation.
<?php
if (!isset($_POST['newgallery']) || empty($_POST['newgallery'])) {
header("Location:Profile.php");
return;
}
try {
$galleryName = filter_input(INPUT_POST, 'newGallery', FILTER_SANITIZE_STRING);
// If filter fails throw error related to variable cleaning
if (!$galleryName) {
throw new Exception('some descriptive message');
}
// if you really prefer procedural: $mysql = mysqli_connect();
$mysqli = new mysqli('host', 'user', 'password', 'schema');
// if mysqli does not instantiate, throw error
if (!$mysqli) {
throw new Exception($mysqli->error);
}
// this is still not ideal, but you can't create a table with a parameterized value.
// the better question is why are you trying to create dynamic tables, that seems like poorly considered engineering.
$tableName = $mysqli->real_escape_string($galleryName);
/**
* Procedural:
* $tableName = mysqli_real_escape_string($mysqli, $galleryName);
* $result = mysqli_query($mysqli, $sql)
*/
$sql = "CREATE TABLE IF NOT EXISTS `{$tableName}` (User_Name VARCHAR(25) PRIMARY KEY, Picture VARCHAR(250), Description VARCHAR(250), Date_Posted TIMESTAMP)"
$result = $mysqli->query($sql);
if (!$result) {
throw new Exception($mysqli->error);
}
echo 'Table creation success.';
return true;
} catch (Exception $e) {
error_log($e)
}
?>

PHP won't interface with MySQL in Apache on Raspberry Pi

I installed MySql on my Raspberry Pi 2 Model B+ a few days ago to see if I could use it, PHP, phpmyadmin, and Apache to make an accessible database to organize and catalog books that are around the house. I have a table in a MySQL database set up as a prototype with three columns; Booknumber (set to auto-increment), title, and authorLastName. I'm trying to use a form to insert books into table beta, in database bookProof.
Here's the code for the form:
<html>
<body>
<form action="catalog.php" method="POST">
<p>Book Title: <input type="text" name="title"></p>
<p>Author's Last Name: <input type="text name="authorlastname"></p>
</form>
</body>
</html>
Which links to "catalog.php", which is:
<?php
define('DB_NAME', 'bookProof');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');
define('DB_HOST', 'localhost');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
die("Could not connect: " . $conn->connect_error);
}
$value = $_POST["title"]
$value2 = $_POST["authorlastname"]
$sql = "INSERT INTO beta ('title', 'authorLastName') VALUES ('".$value."', '".$value2."')"
$query = mysqli_query($conn,$sql);
if ($conn->($sql) === TRUE) {
echo "New entry completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When demoform.php is opened, it functions normally, but when the "Add Books" button is clicked, it goes to catalog.php as intended, but the catalog.php page is blank, the table is unchanged, and Google Chrome's "Inspect" tool gives the error:
POST http://192.168.254.11/Library/catalog.php 500 (Internal Server Error) catalog.php:1
If anyone knows how to get the input to the database, please let me know.
Note: This is just a home system, so security is not a priority (I don't need SQL code injection protection).
Your note, "...security is not a priority (I don't need SQL code injection protection)" - you might think that, but you should do it anyways. Not only does it protect your database should your system be exposed (or made public at a later time), it will handle strings automatically for you, so that your query won't break if your strings have quotes ' in them.
One issue is that you're using singlequotes around column and table names. This should be backticks, or none at all. Then you were missing a semicolon ; after defining your $value, $value2 and $sql strings.
Then you're doing something a bit odd - which is also causing a parse-error (Had you enabled error-reporting and checked your logs, you'd see a "Parse error: syntax error, unexpected (" error in your logs), you're querying the table with mysqli_query(), but then you try to do it again - except you're trying to query on the querystring, and not the query method. Note the comments I've added in the code below.
// Don't use singlequotes ' for columns and table-names
// Use backticks ` - quotes are for strings
$sql = "INSERT INTO beta (`title`, `authorLastName`) VALUES ('".$value."', '".$value2."')"; // You were also missing a semicolon here!
// $query = mysqli_query($conn,$sql); // Remove this line, as you're attempting to query it twice
if ($conn->query($sql) === TRUE) { // You're missing the query() method here
echo "New entry completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Using prepared statements won't be that much of a difference, and you really should do it. There's absolutely no reason to not use prepared statements! Look how little changes that have to be made!
$sql = "INSERT INTO beta (title, authorLastName) VALUES (?, ?)";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("ss", $value, $value2);
$stmt->execute();
$stmt->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You've also got some invalid HTML which would cause issues - the following line had a missing quote to close off the type attribute.
<input type="text" name="authorlastname">
I suggest you read the following documentation and articles
When to use single quotes, double quotes, and backticks in MySQL
How can I prevent SQL injection in PHP?
PHP manual on mysqli_stmt::bind_param
How to get useful error messages in PHP?
PHP Parse/Syntax Errors; and How to solve them?
As a final note, you should check that the form was submitted and that it has values before inserting into the database. Also, using variable-names like $value and $value2 are not really descriptive - you should avoid it and use proper names for your variables.

Grabbing things from database using functions. Is this safe?

I have a simple question. I'm not too good at programming yet but is this safe and correct?
Currently I am using functions to grab the username, avatars, etc.
Looks like this:
try {
$conn = new PDO("mysql:host=". $mysql_host .";dbname=" . $mysql_db ."", $mysql_username, $mysql_password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
config.php ^^
function getUsername($userid) {
require "config/config.php";
$stmt = $conn->prepare("SELECT username FROM accounts WHERE id = ? LIMIT 1");
$stmt->execute([$userid]);
$name = $stmt->fetch();
return $name["username"];
}
function getProfilePicture($userid) {
require "config/config.php";
$stmt = $conn->prepare("SELECT profilepicture FROM accounts WHERE id = ? LIMIT 1");
$stmt->execute([$userid]);
$image = $stmt->fetch();
return $image["profilepicture"];
}
Is this correct and even more important, is this safe?
Yes, it's safe with respect to SQL injections.
Some other answers are getting off topic into XSS protection, but the code you show doesn't echo anything, it just fetches from the database and returns values from functions. I recommend against pre-escaping values as you return them from functions, because it's not certain that you'll be calling that function with the intention of echoing the result to an HTML response.
It's unnecessary to use is_int() because MySQL will automatically cast to an integer when you use a parameter in a numeric context. A non-numeric string is interpreted as zero. In other words, the following predicates give the same results.
WHERE id = 0
WHERE id = '0'
WHERE id = 'banana'
I recommend against connecting to the database in every function. MySQL's connection code is fairly quick (especially compared to some other RDBMS), but it's still wasteful to make a new connection for every SQL query. Instead, connect to the database once and pass the connection to the function.
When you connect to your database, you catch the exception and echo an error, but then your code is allowed to continue as if the connection succeeded. Instead, you should make your script die if there's a problem. Also, don't output the system error message to users, since they can't do anything with that information and it might reveal too much about your code. Log the error for your own troubleshooting, but output something more general.
You may also consider defining a function for your connection, and a class for your user. Here's an example, although I have not tested it:
function dbConnect() {
try {
$conn = new PDO("mysql:host=". $mysql_host .";dbname=" . $mysql_db ."", $mysql_username, $mysql_password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
error_log("PDO connection failed: " . $e->getMessage());
die("Application failure, please contact administrator");
}
}
class User {
protected $row;
public function __construct($userid) {
global $conn;
if (!isset($conn)) {
$conn = dbConnect();
}
$stmt = $conn->prepare("SELECT username, profilepicture FROM accounts WHERE id = ? LIMIT 1");
$stmt->execute([$userid]);
$this->row = $stmt->fetch(PDO::FETCH_ASSOC);
}
function getUsername() {
return $this->row["username"]
}
function getProfilePicture() {
return $this->row["profilepicture"]
}
}
Usage:
$user = new User(123);
$username = $user->getUsername();
$profilePicture = $user->getProfilePicture();
That looks like it would work assuming that your config file is correct. Because it is a prepared statement it looks fine as far as security.
They are only passing in the id. One thing you could do to add some security is ensure that the $userid that is passed in is the proper type. (I am assuming an int).
For example if you are expecting an integer ID coming in and you get a string that might be phishy (possible SQL injection), but if you can confirm that it is an int (perhaps throw an error if it isn't) then you can be sure you are getting what you want.
You can use:
is_int($userid);
To ensure it is an int
More details for is_int() at http://php.net/manual/en/function.is-int.php
Hope this helps.
It is safe (at least this part of the code, I have no idea about the database connection part as pointed out by #icecub), but some things you should pay attention to are:
You only need to require your config.php once on the start of the file
You only need to prepare the statement once then call it on the function, preparing it every time might slow down your script:
The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. - PHP Docs
(Not an error but I personally recommend it) Use Object Orientation to help organize your code better and make easier to mantain/understand
As stated by #BHinkson, you could use is_int to validate the ID of the user (if you are using the IDs as numbers)
Regarding HTML escaping, I'd recommend that you already register your username and etc. HTML escaped.

SQL Query of checking existing entry in database is not working

<?php
error_reporting(0);
$link = mysqli_connect("localhost", "root", "", "checksql");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$myemailaddress=$_POST['useremail'];
$mypassword=$_POST['userpassword'];
$sql = mysqli_query("SELECT * FROM register WHERE Email = '$myemailaddress' ");
$count = mysqli_num_rows($sql);
echo $count;
if($count > 0){
echo "success";
} else{
echo "failed";
}
?>
I am trying to check whether an email exists in the database or not. I searched different thread on stackoverflow and tried to correct it but failed. Even the echo of $count isn't showing it's value. Is there any other way to check it?
You didn't pass db connection to your query
$sql = mysqli_query($link, "SELECT ...
^^^^^^
Btw, your code is open to SQL injection.
Use a prepared statement
https://en.wikipedia.org/wiki/Prepared_statement
More on SQL injection:
https://en.wikipedia.org/wiki/SQL_injection
http://php.net/manual/en/security.database.sql-injection.php
How can I prevent SQL injection in PHP?
Also make sure your POST arrays are not failing you.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
error_reporting(0); doesn't help you, it turns it off.
Add or die(mysqli_error($link)) to mysqli_query() to check for errors.
http://php.net/manual/en/mysqli.error.php
Your form should be using a POST method with name attributes for both your POSTs. That is unclear and wasn't posted in your question; call it an insight.
If you are using both your form and PHP/MySQL inside the same file, then that will trigger undefined index notices on initial page load.
Use !empty() for them.
Reference(s):
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/tutorial.forms.php
http://php.net/manual/en/function.empty.php

Error:NO database is selected

I tried it connection to database connection to database is successful but when i try to match user information with database it gives me a error NO database is selected
i tried it connecting to database using different method but nothing worked
<?php
//CREATING CONNECTION TO DATABASE
$con= new mysqli("localhost", "****", "***", "*****");
$con->select_db("lel_server_user_db_secured");
if(mysqli_connect_errno())
{
echo "Problem With connection to database Please contact administrator regarding this error";
}
/* RETURNS NAME OF DEFAULT DATABASE
if ($result = $con->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
*/
/*
$host="localhost";
$db_user="sky.xpert";
$db_pass="havefun344";
$database="lel_server_user_db_secured";
mysqli_connect($host,$db_user,$db_pass,$database) or die ("Failed to connect");
mysqli_select_db($database) ;
*/
session_start();
//GATHERING DATA FROM USER FORM
$email=$_POST["login"];
$pass=$_POST["pwd"];
//COMMANDING WHERE TO FIND MATCH FOR LGOIN INFORMATION
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$query=mysql_query($veryfy) or die ( mysql_error() );
$match=0;
$match=mysql_num_rows($query);
//IF MATCH FOUND THEN SETTING SESSION AND REDIRECTING IT TO LOGGED PAGE
if($match==1)
{
$_SESSION['loggedin'] = "true";
header ("Location: logged.php"); //REDIRECTING USER TO ITS HOMEPAGE
}
else //IF MATCH NOT FOUND THEN REDIRECTING IT BACK TO LOGIN PAGE
{
$_SESSION['loggedin'] = "false";
header ("Location: index.php");
}
//PERSONAL COMMENTS OR DETIALED COMMENTS
//PROBLEM WITH THIS SCRIPT GIVING OUTPUT ON LOGIN "NO DATABASE SELECTED"
//REFRENCE from http://www.dreamincode.net/forums/topic/52783-basic-login-script-with-php/
?>
You are initializing a connection to your database with mysqli. Then you try to do queries with mysql. Obviously, there is no connection with the database made through that library, and therefore it fails with an error. Change mysql_query to mysqli_query.
General note
Your current code is vulnerable to sql injection attacks, because you do not sanitize the input from the user before putting it in a query. Consider using prepared queries.
The database lel_server_user_db_secured may be not exist.
Content to your mysql:
mysql -hlocalhost -uusername -p
then input your password. After login, type command:
show databases;
check if lel_server_user_db_secured is in the result.
update1*
change the code below:
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$query=mysql_query($veryfy) or die ( mysql_error() );
$match=0;
$match=mysql_num_rows($query);
to:
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$result = mysqli_query($con, $veryfy) or die ( mysqli_connect_errno() );
$match=0;
$match=mysqli_num_rows($result);
var_dump($match);
In the first half of your program you have used mysqli and in the latter half mysql. Either use mysqli or mysql. I would recommend using mysqli in your entire program so that you are not vulnerable to SQL injection
you can simply do it by
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
there is no need to do $con->select_db("lel_server_user_db_secured"); again
and using mysqli isnt mean your code is safe ... your code is still vulnerable to SQL injection Use prepared statement instead or atleast mysqli_real_escape_string
You need to escape all request properly
and its possible that your database isnt exist so check that its exist first
AND you are mixing tow different API
you can not use MySQLi functions with MySQL_* function

Categories