Strengthening the security of PHP using JSON

I'm working on a PHP script that receives data from an Android application. What security measures should I implement to ensure the safety of this script? Are functions like isset enough?

<?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";
?>

Any advice on securing this script would be greatly appreciated.

Answer №1

After reviewing the example code provided, I have made improvements to ensure that connection and json_decode processes are checked for failures. Additionally, I included the use of prepared statements to prevent SQL injection attacks. It is advisable to add validation checks for the movie name field length in comparison with the database field size. The implementation of prepared statements should mitigate any risk of SQL injection:

<?php 
require ('config.php');

$connection=mysqli_connect($servername,$username,$password,$db);
if (!$connection) {
  // Unable to establish MySQL connection - exit with an error message
  exit();
}

$json = file_get_contents('php://input');
$obj = json_decode($json,true);

if( $obj == null ) {
  // JSON decoding failed - exit
  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 "Record successfully inserted";

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Check for existing data and update it if found, otherwise insert new data in WordPress

In my WordPress project, I am trying to handle the insertion of a row only if it does not already exist. If the row exists for the current user, I want to update it with a new value. However, when I try to run the code below on an ajax call, it returns no ...

PHP Jira OAuth: Error 401 - Unauthorized due to oauth_problem: "signature_invalid"

Currently, I am working on creating tools for logging into Jira using OAuth. For this, I am referring to a sample tutorial available at this link. Upon implementation, the response I receive is as follows: [response] HTTP/1.1 401 Unauthorized Server: Apa ...

Displaying Form Results on the Same Page in Drupal: A Step-by-Step Guide

Is there a way to display the results of a form submission on the same page as the form itself? Here is the relevant hook_menu code: $items['admin/content/ncbi_subsites/paths'] = array( 'title' => 'Paths', ...

Tips for Sending Data in the Payload Instead of FormData

I am attempting to call an Alfresco service from a custom web-script, sending JSON data in the payload. Here is the Alfresco service: http://localhost:8080/share/proxy/alfresco/api/internal/downloads The JSON array I need to pass includes script nodes l ...

Looking for Precise Matching within JSON Using JavaScript

I've been experimenting with creating a form that submits data and then checks it against a JSON array to see if there's a matching object already present. Here is a snippet of my JSON data for reference: [ { "ASIN":"B0971Y6PQ3 ...

Transform Objects Array from AJAX Response into a Distinct JSON Entity

I am encountering a problem with a sample endpoint that is returning [object Object] for JSON data, and I can't figure out why. Mock API Initially, my code was a bit confusing, but fortunately, I found a clearer solution in another answer. functio ...

The response from AngularJS $resource can be considered as both an array and an object

Recently, I obtained this JSON file: [ { "name": "paprika", "imgSrc": "img/paprika.jpg" }, { "name": "kurkku", "imgSrc": "img/kurkku.jpg" }, { "name": "porkkana", "imgSrc": "img/porkkana.jpg" }, { "name": "lehtisalaatti", " ...

Eliminating the occurrence of the dot character within column names in R while employing a JSON dataset

I have been attempting to tidy up the column names in my R code. The data I am working with is from a JSON dataset that I imported into R using the "stream_in" function from the jsonlite package. Initially, I tried using both the "gsub" command and the "p ...

Limiting Manager user access in Laravel 5.5

I am relatively new to using Laravel. During a tutorial, I encountered an issue related to restricting access for manager users. Currently, I have successfully assigned roles (manager and members) to my users. However, I am facing a problem with the Manage ...

Implementing a file size restriction in C# when writing a lengthy JSON string using the System.IO.Stream

I have a large array stored in Json format, and the result is saved in a variable called "sz" (string). However, when I attempt to save this Json result (string sz) to a file, it seems that not all of the string gets saved. Why is this happening? The siz ...

Struggling to create an API endpoint in express for handling database requests... receiving a 404 error code

I have a specific route set up in my application: app.post('/api/:type/*/*/*', apiRoute.api); Inside my route file, I've implemented the following logic: exports.api = function(req, res) { var type = req.params.type; var entity = ...

I've encountered the error of receiving a __PHP_Incomplete_Class Object when attempting to create a session using jQuery-ajax

I have defined a new class named FinalResult class FinalResult { var $ReuestAnswer = null; var $givenAnswer = null; var $questionScore = 0; function setScore() { } function getScore() { return $this->question ...

Transmitting a sequence of JSON information from php to JavaScript,

I am struggling to fetch a series of JSON data from PHP to my JavaScript file. Initially, I have multiple JSON data stored in an array in PHP, and I am echoing each one by looping through the array in my JavaScript file. <?php $result = array('{ ...

The command "json_encode($array)" does not seem to be encoding the complete array

I ran a test on the following: <? echo json_encode($array) ?> result: ["PG","Kevin Sad","8000","12"] Upon placing it within a form option value to be selected by my script function: <option value=<? echo json_encode($array) ?> > op ...

Jersey allows for easily sending both image and JSON data together in a multipart response

Currently, I am in the process of learning Jersey by working on creating a Rest service that can receive an image from a client, process it, and then return a new image with additional information related to the processing. The uploading functionality is w ...

Reformat a JSON file and save as a new file

I have a lengthy list of one-level JSON data similar to the example below: json-old.json [ {"stock": "abc", "volume": "45434", "price": "31", "date": "10/12/12"}, {"stock": "abc", "volume": "45435", "price": "30", "date": "10/13/12"}, {"stock": "xyz", "vo ...

When a form input is submitted, the webpage will refresh with a new

I have a form embedded on my WordPress page. I want to identify users without referrers so that I can set the referrer for them automatically (the referrer part is handled by a plugin). The registration form URL looks like this: The code provided below w ...

The PHP blocking code in Zend Server not only blocks the response of the current ajax call but also impacts the handling

I encountered a peculiar problem. Suppose I have an ajax call like this; $.ajax({ url:"url1.php", }) Following this ajax call, I have another ajax call as follows; $.ajax({ url:"url2.php", success:function(data){console.log(data);} }) ...

Issue with resizing keyboard/dropdown popup in Android hybrid app when navigating offscreen

Here is the offscreen navigation menu I have set up. When I open a keyboard or dropdown, the offscreen menu changes and exhibits a small gap on the left side after the popup (highlighted in red). It seems like the menu is shifting further away from the ed ...

What is the best way to extract a session variable from a class in PHP?

Is there a way to access variables outside of the class? ...