PHP Security JSON - php

I have this PHP Script that receives data from an android Application. What Security methods are used to ensure that this PHP script is secure?! like isset function?!
<?php
require ('config.php');
$connection=mysqli_connect($servername,$username,$password,$db);
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$movie_name=$obj['movie_name'];
mysqli_query($connection,"insert into movie (movie_id, movie_name) VALUES (NULL,'$movie_name');");
echo "inserted";
?>
Thanks in advance.

I've edited your example code to check for connection / json_decode failing, and to make use of prepared statements. You might consider doing some validation on the movie name e.g. is it shorter than the length of the database field for example. However, the prepared statements should stop any SQL injection:
<?php
require ('config.php');
$connection=mysqli_connect($servername,$username,$password,$db);
if (!$connection) {
// mysql connection failed - error
exit();
}
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
if( $obj == null ) {
// json decode failed
exit();
}
$stmt = $connection->prepare("INSERT INTO movie (movie_id, movie_name) VALUES (NULL, ?)");
$stmt->bind_param('s', $obj['movie_name']);
$stmt->execute();
$stmt->close();
echo "inserted";

Related

How do I insert simple rows of json data into a mysql table using PHP? [duplicate]

Hi I'm trying to insert the json array into my MySQL database. I'm passing the data form my iphone there i have converted the data into json format and I'm passing the data to my server using the url its not inserting into my server.
This is my json data.
[{"name":"0","phone":"dsf","city":"sdfsdf","email":"dsf"},{"name":"13123123","phone":"sdfsdfdsfsd","city":"sdfsf","email":"13123123"}]
This is my Php code.
<?php
$json = file_get_contents('php://input');
$obj = json_decode($data,true);
//Database Connection
require_once 'db.php';
/* insert data into DB */
foreach($obj as $item) {
mysql_query("INSERT INTO `database name`.`table name` (name, phone, city, email)
VALUES ('".$item['name']."', '".$item['phone']."', '".$item['city']."', '".$item['email']."')");
}
//database connection close
mysql_close($con);
//}
?>
My database connection code.
<?php
//ENTER YOUR DATABASE CONNECTION INFO BELOW:
$hostname="localhost";
$database="dbname";
$username="username";
$password="password";
//DO NOT EDIT BELOW THIS LINE
$link = mysql_connect($hostname, $username, $password);
mysql_select_db($database) or die('Could not select database');
?>
Please tell where I'm doing wrong in the above code basically I'm not a php developer I'm mobile application developer so I'm using the php as a server side scripting please tell me how to resolve this problem.
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
I think you are passing the wrong variable. You should pass $json in json_decode as shown above.
You are missing JSON source file. Create a JSON file then assign it to var data:
<?php
require_once('dbconnect.php');
// reading json file
$json = file_get_contents('userdata.json');
//converting json object to php associative array
$data = json_decode($json, true);
// preparing statement for insert query
$st = mysqli_prepare($connection, 'INSERT INTO users(firstname, lastname, gender, username) VALUES (?, ?, ?, ?)');
// bind variables to insert query params
mysqli_stmt_bind_param($st, 'ssss', $firstname, $lastname, $gender, $username);
// processing the array of objects
foreach ($data as $user) {
$firstname = $user['firstname'];
$lastname = $user['lastname'];
$gender = $user['firstname'];
$username = $user['username'];
// executing insert query
mysqli_stmt_execute($st);
}
There is no such variable as $data. Try
$obj = json_decode($json,true);
Rest looks fine. If the error still persists, enable error_reporting.
Its simple you can insert json datatype as below. reference link: click here for more details
insert into sgv values('c-106', 'admin','owner',false,'[{"test":"test"},
{"test":"test"}]',0,'pasds');
$string=mysql_real_escape_string($json);
header("Access-Control-Allow-Origin: http://localhost/rohit/");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
//files needed to connect to database
include_once 'config/database.php';
include_once 'objects/main.php';
//get Database connection
$database = new Database();
$db = $database->getConnection();
//instantiate product object
$product = new Product($db);
//get posted data
$data = json_decode(file_get_contents("php://input"));
//set product property values
$product->b_nm = $data->Business_Name;
$product->b_pno = $data->Business_Phone;
$product->b_ads = $data->Business_Address;
$product->b_em = $data->Business_Email;
$product->b_typ = $data->Business_Type;
$product->b_ser = $data->Business_Service;
$name_exists = $product->nameExists();
if($name_exists){
echo json_encode(
array(
"success"=>"0",
"message" => "Duplicate Record Not Exists."
)
);
} else{
if($product->b_nm != null && $product->b_pno != null && $product->b_ads != null && $product->b_em != null && $product->b_typ != null && $product->b_ser != null){
if($product->create()){
//set response code
http_response_code(200);
//display message: Record Inserted
echo json_encode(array("success"=>"1","message"=>"Successfully Inserted"));
}
}
else{
//set response code
http_response_code(400);
//display message: unable to insert record
echo json_encode(array("success"=>"0","message"=>"Blank Record Not Exists."));
}
}

mysql_real_escape_string() expects parameter 1 to be string, object given

Hey I'm a PHP newbie setting up a "fetch, post to db, allow delete" project here and I've fetched the data, printed the DB rows and now I'm adding functionality to delete each row by '$id' but I'm running into this error.
I highlighted line 81 with astricks as well as two comment blocks above and below so you can find it easily.
Thanks for helping me learn.
<?php
// ***** MagicQuoteFix ***** //
if (get_magic_quotes_gpc())
{
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
// ***** Begin Connection Info ***** //
$connection = mysqli_connect('localhost', 'ijdbuser', 'ijdbpw');
if (!$connection)
{
$error = 'Unable to connect to the database server.';
include 'error.html.php';
exit();
}
if (!mysqli_set_charset($connection, 'utf8'))
{
$output = 'Unable to set database connection encoding.';
include 'output.html.php';
exit();
}
if (!mysqli_select_db($connection, 'ijdb'))
{
$error = 'Unable to locate the joke database.';
include 'error.html.php';
exit();
}
// ***** Display DB ***** //
$result = mysqli_query($connection, 'SELECT id, joketext FROM joke');
if (!$result)
{
$error = 'Error fetching jokes: ' . mysqli_error($connection);
include 'error.html.php';
exit();
}
while ($row = mysqli_fetch_array($result))
{
$jokes[] = array('id' => $row['id'], 'text' => $row['joketext']);
}
if (isset($_GET['addjoke'])) {}
else
{
include 'jokes.html.php';
}
//
// ***** Begin Add/Remove DB Options ***** //
if (isset($_GET['addjoke']))
{
include 'form.html.php';
exit();
}
if (isset($_GET['deletejoke']))
{
// LINE 81 //
******81.****** $id = mysql_real_escape_string($connection, $_POST['id']);
// LINE 81 //
$sql = "DELETE FROM joke WHERE id='$id'";
if (!mysqli_query($connection, $sql))
{
$error = 'Error deleting joke: ' . mysqli_error($connection);
include 'error.html.php';
exit();
}
//header('Location: .');
exit();
}
if (isset($_POST['joketext']))
{
$joketext = mysql_real_escape_string($connection, $_POST['joketext']);
$sql = 'INSERT INTO joke SET
joketext="' . $_POST['joketext'] . '",
jokedate=CURDATE()';
if (!mysqli_query($connection, $sql))
{
$error = 'Error adding submitted joke: ' . mysqli_error($connection);
include 'error.html.php';
exit();
}
header('Location: .');
exit();
}
?>
Your problem is with this line (the one that has the error)
$id = mysql_real_escape_string($connection, $_POST['id']);
instead it should be
$id = mysqli_real_escape_string($connection, $_POST['id']);
You are mostly handling things as mysqli_ functions (which is the better way), however in this case you are a using mysql_ connection for your escape. Don't use this, it is deprecated, and soon will no longer work because it is vulnerable to sql injection The syntax is different for each. You have the order set up correctly, but have a typo (since everything else is using mysqli. Also Do not use magic quotes! Dangerous and deprecated
Note, there are better ways of handling queries, and you wouldn't need to escape it at all if you use prepared statements (and also not need to worry about whether your variable needs quoting or not). These are just as secure (some would say more so, so you don't need to remember to escape all your variables), and have the advantage of being much faster for larger queries.
For instance, see below. Here's an example using your delete statement:
First connect to the database using an object oriented style like so:
$connection = new mysqli("localhost", "user", "password", "database");
(note it's a good idea to store your database variables in a separate script, and then call it as a require_once include)
Then, handle your query like this
$sql = $connection->prepare("DELETE FROM joke WHERE id=?");
$sql->bind_param("i", $id);
$sql->execute();
$sql->close();
Note that the "i" is specifying that this is an integer (as most ids are), however if this variable were a string, you would call specify this as "s"
for more information on mysqli prepared statements, take a look here: mysqli prepared statements
You are using mysqli to query to your database therefore you need to use mysqli_real_escape_string() instead of mysql_real_escape_string() and also remove the first argument that you have passed to the function which is $connection. This is a very common mistake every developer makes.
Therefore you can replace line 81 by
$id = mysqli_real_escape_string($_POST['id']);
similar situation:
please see:www.westwoodpavillion/ecommerce/admin_area/login.php (source code)
include("includes/db.php");
if(isset($_POST['login'])){
$email = mysqli_real_escape_string($con, $_POST['email']);
$pass = mysqli_real_escape_string($con, $_POST['password']);
it works for me....eloisa..Thank YOu very much.
change:
if (!ini_get("safe_mode")) $success = mail($to, $subject, $message, $headers, $params);
to:
if (!ini_get("safe_mode")) $success = #mail($to, $subject, $message, $headers, $params);
works like magic.. just change your mail($to... and the rest to the
specified above)

How to insert json array into mysql database

Hi I'm trying to insert the json array into my MySQL database. I'm passing the data form my iphone there i have converted the data into json format and I'm passing the data to my server using the url its not inserting into my server.
This is my json data.
[{"name":"0","phone":"dsf","city":"sdfsdf","email":"dsf"},{"name":"13123123","phone":"sdfsdfdsfsd","city":"sdfsf","email":"13123123"}]
This is my Php code.
<?php
$json = file_get_contents('php://input');
$obj = json_decode($data,true);
//Database Connection
require_once 'db.php';
/* insert data into DB */
foreach($obj as $item) {
mysql_query("INSERT INTO `database name`.`table name` (name, phone, city, email)
VALUES ('".$item['name']."', '".$item['phone']."', '".$item['city']."', '".$item['email']."')");
}
//database connection close
mysql_close($con);
//}
?>
My database connection code.
<?php
//ENTER YOUR DATABASE CONNECTION INFO BELOW:
$hostname="localhost";
$database="dbname";
$username="username";
$password="password";
//DO NOT EDIT BELOW THIS LINE
$link = mysql_connect($hostname, $username, $password);
mysql_select_db($database) or die('Could not select database');
?>
Please tell where I'm doing wrong in the above code basically I'm not a php developer I'm mobile application developer so I'm using the php as a server side scripting please tell me how to resolve this problem.
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
I think you are passing the wrong variable. You should pass $json in json_decode as shown above.
You are missing JSON source file. Create a JSON file then assign it to var data:
<?php
require_once('dbconnect.php');
// reading json file
$json = file_get_contents('userdata.json');
//converting json object to php associative array
$data = json_decode($json, true);
// preparing statement for insert query
$st = mysqli_prepare($connection, 'INSERT INTO users(firstname, lastname, gender, username) VALUES (?, ?, ?, ?)');
// bind variables to insert query params
mysqli_stmt_bind_param($st, 'ssss', $firstname, $lastname, $gender, $username);
// processing the array of objects
foreach ($data as $user) {
$firstname = $user['firstname'];
$lastname = $user['lastname'];
$gender = $user['firstname'];
$username = $user['username'];
// executing insert query
mysqli_stmt_execute($st);
}
There is no such variable as $data. Try
$obj = json_decode($json,true);
Rest looks fine. If the error still persists, enable error_reporting.
Its simple you can insert json datatype as below. reference link: click here for more details
insert into sgv values('c-106', 'admin','owner',false,'[{"test":"test"},
{"test":"test"}]',0,'pasds');
$string=mysql_real_escape_string($json);
header("Access-Control-Allow-Origin: http://localhost/rohit/");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
//files needed to connect to database
include_once 'config/database.php';
include_once 'objects/main.php';
//get Database connection
$database = new Database();
$db = $database->getConnection();
//instantiate product object
$product = new Product($db);
//get posted data
$data = json_decode(file_get_contents("php://input"));
//set product property values
$product->b_nm = $data->Business_Name;
$product->b_pno = $data->Business_Phone;
$product->b_ads = $data->Business_Address;
$product->b_em = $data->Business_Email;
$product->b_typ = $data->Business_Type;
$product->b_ser = $data->Business_Service;
$name_exists = $product->nameExists();
if($name_exists){
echo json_encode(
array(
"success"=>"0",
"message" => "Duplicate Record Not Exists."
)
);
} else{
if($product->b_nm != null && $product->b_pno != null && $product->b_ads != null && $product->b_em != null && $product->b_typ != null && $product->b_ser != null){
if($product->create()){
//set response code
http_response_code(200);
//display message: Record Inserted
echo json_encode(array("success"=>"1","message"=>"Successfully Inserted"));
}
}
else{
//set response code
http_response_code(400);
//display message: unable to insert record
echo json_encode(array("success"=>"0","message"=>"Blank Record Not Exists."));
}
}

Why do I have to start a transaction using PDO and then commit it before I can delete data from MySQL DB

When I ran this piece of code
<?php
include '../bin/config.php';
connect();
if (isset($_GET['id']) && is_numeric($_GET['id'])){
$id = $_GET['id'];
$stmt = $conn->prepare("DELETE FROM noteline WHERE Nid = ?");
$stmt->bindParam(1, $id, PDO::PARAM_INT);
$outcome = $stmt->execute();
if ($outcome){
echo 'it was successfully deleted';
header("Location: ../noteline");
}else {
echo 'it was not successful due to something';
}
}
?>
it echoed "it was successfully deleted" but nothing was deleted from my database...
but when I started a transaction by modified this code like this:
<?php
include '../bin/config.php';
connect();
if (isset($_GET['id']) && is_numeric($_GET['id'])){
$id = $_GET['id'];
$stmt = $conn->prepare("DELETE FROM noteline WHERE Nid = ?");
$stmt->bindParam(1, $id, PDO::PARAM_INT);
$conn->beginTransaction();
$outcome = $stmt->execute();
if ($outcome){
$conn->commit();
echo 'it was successfully deleted';
header("Location: ../noteline");
}else {
echo 'it was not successful due to something';
}
}
?>
My data was finally deleted from my MySQL database!
I want to know why?
Because the PDO connection is operating with auto-commit mode disabled. Look into the connect() function to ensure that you don't disable this mode.
(Also, I see you're using a global variable to store the connection object. Avoid global variables where possible.)
Sounds like your server might have autocommit turned off?
http://dev.mysql.com/doc/refman/5.0/en/commit.html
By default, MySQL runs with autocommit mode enabled. This means that
as soon as you execute a statement that updates (modifies) a table,
MySQL stores the update on disk to make it permanent.
There might be a line in your code somewhere that sends
SET autocommit=0;
to your server.

Saving JSON string to MySQL database

I have a JSON string with me
{"name":"jack","school":"colorado state","city":"NJ","id":null}
I need it to be saved in the Database. How could i do this ?
My PHP code (I have only establish the connection to MySQL, but i am unable to save the records)
<?php
// the MySQL Connection
mysql_connect("localhost", "username", "pwd") or die(mysql_error());
mysql_select_db("studentdatabase") or die(mysql_error());
// Insert statement
mysql_query("INSERT INTO student
(name, school,city) VALUES(------------------------- ) ") // (How to write this)
or die(mysql_error());
echo "Data Inserted or failed";
?>
We'll use json_decode json_decode documentation
Also be sure to escape! here's how I would do it below...
/* create a connection */
$mysqli = new mysqli("localhost", "root", null, "yourDatabase");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* let's say we're grabbing this from an HTTP GET or HTTP POST variable called jsonGiven... */
$jsonString = $_REQUEST['jsonGiven'];
/* but for the sake of an example let's just set the string here */
$jsonString = '{"name":"jack","school":"colorado state","city":"NJ","id":null}
';
/* use json_decode to create an array from json */
$jsonArray = json_decode($jsonString, true);
/* create a prepared statement */
if ($stmt = $mysqli->prepare('INSERT INTO test131 (name, school, city, id) VALUES (?,?,?,?)')) {
/* bind parameters for markers */
$stmt->bind_param("ssss", $jsonArray['name'], $jsonArray['school'], $jsonArray['city'], $jsonArray['id']);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
Hope this helps!
This is example for help you
<?php
$json = '{"name":"jack","school":"colorado state","city":"NJ","id":null}';// You can get it from database,or Request parameter like $_GET,$_POST or $_REQUEST or something :p
$json_array = json_decode($json);
echo $json_array["name"];
echo $json_array["school"];
echo $json_array["city"];
echo $json_array["id"];
?>
Hope this help !
Decode into an array and pass it in your mysql_query, the code below is not using mysql_real_escape_string or any other means of security, which you should implement.
Assume $json is {"name":"jack","school":"colorado state","city":"NJ","id":null}
$json_array = json_decode($json);
You now have indexes in a php array, such as: $json_array['name']
mysql_query("INSERT INTO student (name, school,city) VALUES('".$json_array['name']."', '".$json_array['school']."', '".$json_array['city']."') ") or die(mysql_error());

Categories