how to forbid to send data to sql - php

I'm using strlen to check my inputs values. I want to forbid to the users to send data to my database if the strlen is too long. I didn't find any way to forbid it, so anyone can send as long values as he wants right now. Here's my code:
if (isset($_POST['sub'])) {
$name = $_POST['name'];
$phone = $_POST['phone'];
$phone2 = $_POST['phone2'];
$email = $_POST['email'];
$zipcode = $_POST['zipcode'];
$address = $_POST['address'];
$job = $_POST['job'];
$description = $_POST['description'];
$userid = $_SESSION['id'];
$stmt = $mysqli -> prepare('UPDATE cards SET name=?, phone=?, phone2=?, email=?, zipcode=?, address=?, job=?, description=?, visibility=?, confirmed=? WHERE id = ?');
if (
$stmt &&
$stmt->bind_param('ssssisssiii', $name, $phone, $phone2, $email, $zipcode, $address, $job, $description, $visibility, $confirmed, $id) &&
$stmt -> execute()
) {
echo "Sikeres módosítás!";
} else {
echo $mysqli -> error;
}
}
$getstmt = $mysqli->prepare("SELECT * FROM cards WHERE id= ?");
if ($getstmt and
$getstmt->bind_param('i', $id) and
$getstmt->execute() and
$result = $getstmt->get_result() and
$row = $result->fetch_assoc()
) {
if($row['userid'] == $_SESSION['id']){
$name = $row['name'];
$phone = $row['phone'];
$phone2 = $row['phone2'];
$email = $row['email'];
$zipcode = $row['zipcode'];
$address = $row['address'];
$job = $row['job'];
$description = $row['description'];
}else{
header("Location: index.php");
}
I check the length of inputs here:
if(strlen($name) > 30)
{
echo "test";
exit();
}
if(strlen($job) > 50)
{
echo "test";
exit();
}
if(strlen($email) > 50)
{
echo "test";
exit();
}
//more of these strlen checks
//and html code under that
How can I modify the echo parts to forbid to send the datas?

Well, if you really have to do it your way, you can throw an exception.
However, more common way is to bind your data to model, validate the model checking any business constraints (using the validator) and then acting accordingly. There is plenty of web frameworks providing such an abstraction in any programming language, for PHP see Laravel for inspiration.

Related

Deny other users to edit someone else's cards

I'm making an update page where users can edit their business cards' informations, like phone, address..
The problem is, I'm getting their cards id in this way:
Edit
so they can see their card id in the search bar and if they just simply change the id, they can edit anyone's card informations. I wanted to check if the user's id equals to his card userid - (this is a foreign key in the database) and if not, redirect him to the index page. The problem is, I'm still allowed to edit anyone's card because the userid doesn't change.
my update code:
session_start();
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'reg');
/* Attempt to connect to MySQL database */
$mysqli = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($mysqli === false){
die("HIBA: Nem sikerült csatlakozni. " . mysqli_connect_error());
}
$id = $_GET['id'];
var_dump($_SESSION);
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$phone = $_POST['phone'];
$phone2 = $_POST['phone2'];
$email = $_POST['email'];
$zipcode = $_POST['zipcode'];
$address = $_POST['address'];
$job = $_POST['job'];
$description = $_POST['description'];
$userid = $_SESSION['id'];
if( $_SESSION['id'] != $userid){
header("Location: index.php");
}
$stmt = $mysqli -> prepare('UPDATE cards SET name=?, phone=?, phone2=?, email=?, zipcode=?, address=?, job=?, description=?, visibility=?, confirmed=? WHERE id = ?');
if (
$stmt &&
$stmt->bind_param('ssssisssii', $name, $phone, $phone2, $email, $zipcode, $address, $job, $description, $visibility, $confirmed) &&
$stmt -> execute()
) {
echo 'Updated';
} else {
echo $mysqli -> error;
}
}
$getstmt = $mysqli->prepare("SELECT * FROM cards WHERE id= ?");
if ($getstmt and
$getstmt->bind_param('i', $id) and
$getstmt->execute() and
$result = $getstmt->get_result() and
$row = $result->fetch_assoc()
) {
$name = $row['name'];
$phone = $row['phone'];
$phone2 = $row['phone2'];
$email = $row['email'];
$zipcode = $row['zipcode'];
$address = $row['address'];
$job = $row['job'];
$description = $row['description'];
my database: (users)
id- username- password- created- admin-
----------------------------------------------
1 John 112 2020-12-23 2435
cards:
id- name- phone- phone2- email- zipcode- address- job- description- visibility- userid-
-----------------------------------------------------------------------------------------------------
1 John 112 233 a#a.com 2435 dfdf 34. test uzlh 0 1
Something Like that
$getstmt = $mysqli->prepare("SELECT * FROM cards WHERE id= ?");
if ($getstmt and
$getstmt->bind_param('i', $id) and
$getstmt->execute() and
$result = $getstmt->get_result() and
$row = $result->fetch_assoc()
) {
if($row['userid'] == $_SESSION['id']){
$name = $row['name'];
$phone = $row['phone'];
$phone2 = $row['phone2'];
$email = $row['email'];
$zipcode = $row['zipcode'];
$address = $row['address'];
$job = $row['job'];
$description = $row['description'];
}else{
header("Location: index.php");
}
}
you are trying to match $userid with $_SESSION['id'] both of these variable pointing to same value use $_GET['id'] instead of $userid
if( $_SESSION['id'] != $_GET['id']){
header("Location: index.php");
exit();
}

Update works on localhost but not when live [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
I've created an update page, where users can update their cards. It's working fine on localhost, but I just uploaded it to 000webhostapp and my database doesn't update. I don't get any errors, or anything, it just doesn't update it. I'm using Xampp for the localhost.
My update code:
<?php
session_start();
define('DB_SERVER', 'localhost');
define('DB_USERNAME', '1');
define('DB_PASSWORD', '2');
define('DB_NAME', '3');
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] === false){
header("Location: login.php");
} else {
$mysqli = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
mysqli_set_charset($mysqli, "utf8");
if($mysqli === false){
die("failed to connect. " . mysqli_connect_error());
}
$id = $_GET['id'];
if (isset($_POST['sub'])) {
$name = $_POST['name'];
$phone = $_POST['phone'];
$phone2 = $_POST['phone2'];
$email = $_POST['email'];
$zipcode = $_POST['zipcode'];
$address = $_POST['address'];
$company = $_POST['company'];
$job = $_POST['job'];
$description = $_POST['description'];
$userid = $_SESSION['id'];
if (
strlen($name) < 31 &&
strlen($job) < 51 &&
strlen($zipcode) < 5 &&
strlen($email) < 51 &&
strlen($phone) < 21 &&
strlen($phone2) < 21 &&
strlen($address) < 51 &&
strlen($company) < 51 &&
strlen($description) < 501) {
$stmt = $mysqli -> prepare('UPDATE cards SET name=?, phone=?, phone2=?, email=?, zipcode=?, address=?, company=?, job=?, description=?, visibility=?, confirmed=? WHERE id = ?');
$stmt->bind_param('ssssissssiii', $name, $phone, $phone2, $email, $zipcode, $address, $company, $job, $description, $visibility, $confirmed, $id);
$success = $stmt -> execute();
if ($success) {
echo "Sikeres módosítás!";
}
} else {
echo $mysqli -> error;
}
}
$getstmt = $mysqli->prepare("SELECT * FROM cards WHERE id= ?");
if ($getstmt and
$getstmt->bind_param('i', $id) and
$getstmt->execute() and
$result = $getstmt->get_result() and
$row = $result->fetch_assoc()
) {
if($row['userid'] == $_SESSION['id']){
$name = $row['name'];
$phone = $row['phone'];
$phone2 = $row['phone2'];
$email = $row['email'];
$zipcode = $row['zipcode'];
$address = $row['address'];
$company = $row['company'];
$job = $row['job'];
$description = $row['description'];
}else{
header("Location: index.php");
}
?>
It is so frustrating because I have absolutely no idea why it doesn't work there if it's working on localhost...
The problem was that in my mysli->prepare, I wanted to use the 'visbility' and the 'confirmed' columns, but I don't change them here. Thanks #Dharman for helping me with exceptions. It helped a lot.

How to log specific user executed queries

I am wanting to keep a table log history of executed MySQLI queries and log the specific user who executed a query and date & time the query was executed - on any (all) of my PHP pages.
What is the best way and simplest way to achieve this?
PHP
session_start();
if(!isset($_SESSION["username"])){
header("Location: login.php");
exit(); }
$connection = mysqli_connect("****", "****", "****", "****");
if (!$connection) {
die("Database connection failed: " . mysqli_connect_error());
}
if(isset($_POST['update'])) {
$accountNo = $_GET['ID'];
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$dob = $_POST['dob'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$town = $_POST['town'];
$postcode = $_POST['postcode'];
Recommendation from a SO user:
However, there are errors with this suggestion ...many.
$query = "UPDATE usertable set firstname = '".$firstname."', surname='".$surname."', dob='".$dob."', email='".$email."', phone='".$phone."', address='".$address."', town='".$town."', postcode='".$postcode."' where accountNo='".$accountNo."'";
$log_action = mysqli_query($connection,$query);
$result = mysqli_query($connection,$query);
if($result) {
define("LOG_FILE", "https://www.*******.com/logfile.txt");
function log_action($action, $data) {
$time = date('Y-m-d h:i:s');
$user = isset($_SESSION['username']) ? $_SESSION['username'] : '';
$message = "$time\tuser=$user\taction=$action\tdata=$data\n";
file_put_contents(LOG_FILE, $message, FILE_APPEND);
}
Write a wrapper library that logs all the mysqli calls that you want to record, e.g.
function my_mysqli_query($link, $query, $resultmode = MYSQLI_STORE_RESULT) {
log_action('mysqli_query', $query);
return mysqli_query($link, $query, $resultmode);
}
function my_mysqli_prepare($link, $query) {
log_action('mysqli_prepare', $query);
return mysqli_prepare($link, $query);
}
...
define("LOG_FILE", "/path/to/logfile.txt");
function log_action($action, $data) {
$time = date('Y-m-d h:i:s');
$user = isset($_SESSION['username']) ? $_SESSION['username'] : '';
message = "$time\tuser=$user\taction=$action\tdata=$data\n";
file_put_contents(LOG_FILE, $message, FILE_APPEND);
}
I've written it to log to a file. You could log to a database table instead, it's just more code in log_action().
Then do a global replace in all your other scripts, replacing mysqli_query with my_mysqli_query, mysqli_prepare with my_mysqli_prepare, and so on. So your code would look like:
if(isset($_POST['update'])) {
$accountNo = $_GET['ID'];
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$dob = $_POST['dob'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$town = $_POST['town'];
$postcode = $_POST['postcode'];
$query = "UPDATE usertable set firstname = '".$firstname."', surname='".$surname."', dob='".$dob."', email='".$email."', phone='".$phone."', address='".$address."', town='".$town."', postcode='".$postcode."' where accountNo='".$accountNo."'";
$result = my_mysqli_query($connection,$query);
if ($result) {
echo "Update successful";
}
}

Pass value when form submitted to If function on another file

I have two different files.
Checkoutstep4.php
Checkoutstep5.php
When the first form is submitted, I want to take the value of 'country' which has been submitted and use it in an IF function:
This is what I have so far using session variable...
however I get an error saying undefined index and I am not sure why.
checkoutDeliveryInfo (file that runs when the delivery details form is submitted).
<?php
session_start();
require_once 'DatabaseConnection.php';
$_SESSION['customerid'];
if (isset($_POST['submit'])) {
$stmt = $pdo->prepare("INSERT INTO DeliveryDetails (customerid,firstname,lastname, addressline1, addressline2, city, county, country, postalcode)
VALUES ({$_SESSION['customerid']}, :firstname, :lastname, :addressline1, :addressline2, :city, :county, :country, :postalcode)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':addressline1', $addressline1);
$stmt->bindParam(':addressline2', $addressline2);
$stmt->bindParam(':city', $city);
$stmt->bindParam(':county', $county);
$stmt->bindParam(':country', $country);
$stmt->bindParam(':postalcode', $postalcode);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$addressline1 = $_POST['addressline1'];
$addressline2 = $_POST['addressline2'];
$city = $_POST['city'];
$county = $_POST['county'];
$country = $_POST['country'];
$postalcode = $_POST['postalcode'];
$stmt->execute();
$_SESSION['country'] = $country;
header('location:../View/php_shopping_cart/CheckoutStep5.php');
}
IF function in the Checkoutstep5.php file where the session variable is being used:
<?php
include '../../Model/ShoppingCart.php';
$shoppingCart = new ShoppingCart;
// redirect to home if cart is empty
if ($shoppingCart->total_items() <= 0) {
header("Location: ../index.php");
}
?>
<div class="shippingcost"><strong>Shipping Cost <?php
if ($_SESSION['country'] != 'GIB') {
$shippingcost = '10.00';
} else {
$shippingcost = 'FREE';
}
echo $shippingcost;
?></strong>
</div>
Any help is appreciated.
Update: Error Message:
Notice: Undefined index: country in /home/k1509759/www/barbarycoast/View/php_shopping_cart/CheckoutStep5.php on line 246
I've managed to do it by extracting all variables from the session and then using the individual one i wanted.
extract($_SESSION);
if ($country == 'GIB') {
$shippingcost = 'FREE';
} else if ($country == 'GBR') {
$shippingcost = '£10.00';
} else if ($country == 'ESP') {
$shippingcost = '£10.00';
}

says there are errors mysqli

this is so that I come from Denmark and use google translate because I'm bad at English so hope that it can be in level with, however, this is how my MySQLI code to go right down to the last words, and says there are errors . I've tried to write it right password and email in, but it can not be bothered to work at all in some way it keeps making mistakes, how can it be?
<?php
session_start();
include("include/database/db.php");
if($stmt = $mysqli->prepare("SELECT id, djnavn, hemmelig, rank FROM `brugere` WHERE `email` = ? AND `password` = ?"))
{
$stmt->bind_param('ss', $email, $password);
$email = $_POST['email'];
$password = sha1($_POST['password']);
$stmt->execute();
$stmt->bind_result($id, $djnavn, $hemmelig, $rank);
$stmt->fetch();
$count_res = $stmt->num_rows;
$stmt->close();
if($count_res > 0) {
$_SESSION["logged_in"] = true;
$_SESSION["user_id"] = $id;
$_SESSION["djnavn"] = $djnavn;
$_SESSION["hemmelig"] = $hemmelig;
$_SESSION["rank"] = $rank;
if($rank == 0)
{
echo "Your can not log in!";
}
if($rank == 1)
{
echo "Ok, members you can log in now!";
}
if($rank == 2)
{
echo "Ok, Admin you can log in now!";
}
}
else {
echo 'fail her: ' . $mysqli->error;
}
}
?>
Can you help me on it!!
First of all it's notification and it occurs because you don't define $email and $password before you use them.
$email = $_POST['email'];
$password = sha1($_POST['password']);
cut and paste them befor you bind params:
$stmt->bind_param('ss', $email, $password);

Categories