0

I keep getting a 403 error when I call a php script that posts to a mysql database. the other thing is if i call the script directly in the browser the browser downloads a blank file instead of showing it. if the database is unable to connect it shows an error in the blank file that's downloaded, so i'm assuming it's able to connect to the db properly so i'm very confused. I'm using a delphi program to call the php script and the delphi program is getting the 403 error.

here's my php file:

<?php
                header("Content-type: application/x-www-form-urlencoded; charset=utf-8");
                header('X-Frame-Options: DENY');
                header("X-Content-Type-Options: nosniff");
                header("X-XSS-Protection: 1; mode=block");
                header("Expect-CT: max-age=86400, enforce");
                header("Feature-Policy: geolocation 'none'");
                header("Access-Control-Allow-Origin: *");
                // the above must be the first items in this file (well, before any output)

          $dive_no = $_POST["diveCode"];
          $name = $_POST["Name"];
          $team = $_POST["Team"];
          // connect to database
                require_once("./db_connect.php");
                if ($DbLink) {
                        // make sure the database knows to use utf-8
                        $sql = "SET NAMES 'utf8';";
                        $result = mysqli_query($DbLink, $sql);

                        // Write next dive
                        $sql = "UPDATE `admin` SET `diveCode` = '" .$dive_no
                                . "', `Name` = '" . $name
                                . "', `Team` = '" . $team
                                . "' WHERE `userid` = 1;";
                        $result = mysqli_query($DbLink, $sql);

                        $sql = "UPDATE `judge` SET `score` = NULL;";
                        $result = mysqli_query($DbLink, $sql);

                        mysqli_close($DbLink);
                }

here's my apache.conf:

# This is the main Apache server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.4/ for detailed information about
# the directives and /usr/share/doc/apache2/README.Debian about Debian specific
# hints.
#
#
# Summary of how the Apache 2 configuration works in Debian:
# The Apache 2 web server configuration in Debian is quite different to
# upstream's suggested way to configure the web server. This is because Debian's
# default Apache2 installation attempts to make adding and removing modules,
# virtual hosts, and extra configuration directives as flexible as possible, in
# order to make automating the changes and administering the server as easy as
# possible.

# It is split into several files forming the configuration hierarchy outlined
# below, all located in the /etc/apache2/ directory:
#
#   /etc/apache2/
#   |-- apache2.conf
#   |   `--  ports.conf
#   |-- mods-enabled
#   |   |-- *.load
#   |   `-- *.conf
#   |-- conf-enabled
#   |   `-- *.conf
#   `-- sites-enabled
#       `-- *.conf
#
#
# * apache2.conf is the main configuration file (this file). It puts the pieces
#   together by including all remaining configuration files when starting up the
#   web server.
#
# * ports.conf is always included from the main configuration file. It is
#   supposed to determine listening ports for incoming connections which can be
#   customized anytime.
#
# * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/
#   directories contain particular configuration snippets which manage modules,
#   global configuration fragments, or virtual host configurations,
#   respectively.
#
#   They are activated by symlinking available configuration files from their
#   respective *-available/ counterparts. These should be managed by using our
#   helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See
#   their respective man pages for detailed information.
#
# * The binary is called apache2. Due to the use of environment variables, in
#   the default configuration, apache2 needs to be started/stopped with
#   /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not
#   work with the default configuration.


# Global configuration
#

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE!  If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the Mutex documentation (available
# at <URL:http://httpd.apache.org/docs/2.4/mod/core.html#mutex>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
#ServerRoot "/etc/apache2"

#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
#Mutex file:${APACHE_LOCK_DIR} default

#
# The directory where shm and other runtime files will be stored.
#

DefaultRuntimeDir ${APACHE_RUN_DIR}

#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}

#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300

#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On

#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100

#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5


# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off

# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog ${APACHE_LOG_DIR}/error.log

#
# LogLevel: Control the severity of messages logged to the error_log.
# Available values: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the log level for particular modules, e.g.
# "LogLevel info ssl:warn"
#
LogLevel warn

# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf

# Include list of ports to listen on
Include ports.conf


# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
<Directory />
    Options FollowSymLinks
    AllowOverride All
    Require all granted
    Order allow,deny
    Allow from all
</Directory>

<Directory /usr/share>
    AllowOverride None
    Require all granted
</Directory>

<Directory /var/www/>
        Options FollowSymLinks
        AllowOverride All
        Require all granted
        Order allow,deny
        Allow from all
</Directory>

#<Directory /srv/>
#   Options Indexes FollowSymLinks
#   AllowOverride None
#   Require all granted
#</Directory>




# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives.  See also the AllowOverride
# directive.
#
AccessFileName .htaccess

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<FilesMatch "^\.ht">
    Require all denied
</FilesMatch>


#
# The following directives define some format nicknames for use with
# a CustomLog directive.
#
# These deviate from the Common Log Format definitions in that they use %O
# (the actual bytes sent including headers) instead of %b (the size of the
# requested file), because the latter makes it impossible to detect partial
# requests.
#
# Note that the use of %{X-Forwarded-For}i instead of %h is not recommended.
# Use mod_remoteip instead.
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

# Include of directories ignores editors' and dpkg's backup files,
# see README.Debian for details.

# Include generic snippets of statements
IncludeOptional conf-enabled/*.conf

# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

AddHandler application/x-httpd-php .php

my apache sites-enabled conf:

<VirtualHost *:4200>
    <Directory /var/www/judgepad>
        Options FollowSymLinks
        AllowOverride All
        Require all granted
        Order allow,deny
        Allow from all
    Deny from none
    </Directory>

    ServerName judge.brooker.cloud
    ServerAlias judge.brooker.cloud
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/judgepad
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

my mysqld.cnf:

    #
# The MySQL database server configuration file.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

# Here is entries for some specific programs
# The following values assume you have at least 32M ram

[mysqld]
#
# * Basic Settings
#
user        = mysql
# pid-file  = /var/run/mysqld/mysqld.pid
# socket    = /var/run/mysqld/mysqld.sock
# port      = 3306
# datadir   = /var/lib/mysql


# If MySQL is running as a replication slave, this should be
# changed. Ref https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_tmpdir
# tmpdir        = /tmp
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address        = 0.0.0.0
mysqlx-bind-address = 127.0.0.1
#
# * Fine Tuning
#
key_buffer_size     = 16M
# max_allowed_packet    = 64M
# thread_stack      = 256K

# thread_cache_size       = -1

# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover-options  = BACKUP

# max_connections        = 151

# table_open_cache       = 4000

#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
#
# Log all queries
# Be aware that this log type is a performance killer.
# general_log_file        = /var/log/mysql/query.log
# general_log             = 1
#
# Error log - should be very few entries.
#
log_error = /var/log/mysql/error.log
#
# Here you can see queries with especially long duration
# slow_query_log        = 1
# slow_query_log_file   = /var/log/mysql/mysql-slow.log
# long_query_time = 2
# log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
#       other settings you may need to change.
# server-id     = 1
# log_bin           = /var/log/mysql/mysql-bin.log
# binlog_expire_logs_seconds    = 2592000
max_binlog_size   = 100M
# binlog_do_db      = include_database_name
# binlog_ignore_db  = include_database_name

I have one .htaccess file in my webroot (handles a angular site on the same webroot):

RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]

# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

I'm not getting anything showing up in my apache error logs and I've been researching and trying things for weeks and I'm really stuck. Please help. Thanks :)

EDIT: If i use this php file directly in the browser it post updates to the db correctly:

<!DOCTYPE html>
<html>
<head>
  <title>Add Records in Database</title>
</head>
<body>

<?php
$user = "******";
$password = "********";
$database = "********";
$table = "********";
$host = "localhost";

$db = mysqli_connect($host,$user,$password,$database);

if(!$db)
{
    die("Connection failed: " . mysqli_connect_error());
}

if(isset($_POST['submit']))
{
    $diveCode = $_POST['diveCode'];
    $name = $_POST['name'];
    $team = $_POST['team'];

    $insert = mysqli_query($db,"UPDATE admin SET diveCode='".$diveCode."', Name='".$name."', Team='".$team."' WHERE userId = 1;");

    if(!$insert)
    {
        echo mysqli_error();
    }
    else
    {
        echo "Records added successfully.";
    }
}

mysqli_close($db); // Close connection
?>

<h3>Fill the Form</h3>

<form method="POST">
  DiveCode : <input type="text" name="diveCode" placeholder="Enter diveCode" Required>
  <br/>
  Name : <input type="text" name="name" placeholder="Enter name" Required>
  <br/>
  Team : <input type="text" name="team" placeholder="Enter team" Required>
  <br/>
  <input type="submit" name="submit" value="Submit">
</form>

</body>
</html>

EDIT: here's the delphi program code. The code owner told me there's some ssl files that can also given if needed. Brookertest.dpr

program Brookertest;

uses
  Vcl.Forms,
  Main in 'Main.pas' {Form1};

{$R *.res}

begin
  Application.Initialize;
  Application.MainFormOnTaskbar := True;
  Application.Title := 'Brooker Test';
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

Main.dfm

object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Next Dive Test'
  ClientHeight = 267
  ClientWidth = 467
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object lblURL: TLabel
    Left = 16
    Top = 16
    Width = 23
    Height = 13
    Caption = 'URL:'
  end
  object lblPostParameters: TLabel
    Left = 16
    Top = 80
    Width = 83
    Height = 13
    Caption = 'Post Parameters:'
  end
  object lblDiverName: TLabel
    Left = 32
    Top = 139
    Width = 71
    Height = 13
    Caption = 'Name of diver:'
  end
  object lblNextDive: TLabel
    Left = 32
    Top = 107
    Width = 50
    Height = 13
    Caption = 'Next dive:'
  end
  object lblTeamCode: TLabel
    Left = 32
    Top = 171
    Width = 59
    Height = 13
    Caption = 'Team code: '
  end
  object edtURL: TEdit
    Left = 16
    Top = 35
    Width = 417
    Height = 21
    TabOrder = 0
    Text = 'https://judge.brooker.cloud/diverecorder/nextdive.php'
    TextHint = 'eg:  https://judge.brooker.cloud/diverecorder/nextdive.php'
  end
  object edtDiverName: TEdit
    Left = 120
    Top = 136
    Width = 201
    Height = 21
    TabOrder = 2
    TextHint = 'eg  Christian Brooker'
  end
  object edtNextDive: TEdit
    Left = 120
    Top = 104
    Width = 201
    Height = 21
    TabOrder = 1
    TextHint = 'eg:  5132D'
  end
  object edtTeamCode: TEdit
    Left = 120
    Top = 168
    Width = 201
    Height = 21
    TabOrder = 3
    TextHint = 'eg:  AUS'
  end
  object btnSend: TButton
    Left = 16
    Top = 216
    Width = 105
    Height = 25
    Caption = 'Send Post'
    TabOrder = 4
    OnClick = btnSendClick
  end
  object IdHTTP1: TIdHTTP
    IOHandler = IdSSLIOHandlerSocketOpenSSL1
    HandleRedirects = True
    ProxyParams.BasicAuthentication = False
    ProxyParams.ProxyPort = 0
    Request.ContentLength = -1
    Request.ContentRangeEnd = -1
    Request.ContentRangeStart = -1
    Request.ContentRangeInstanceLength = -1
    Request.Accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
    Request.BasicAuthentication = False
    Request.UserAgent = 'Mozilla/3.0 (compatible; Indy Library)'
    Request.Ranges.Units = 'bytes'
    Request.Ranges = <>
    HTTPOptions = [hoForceEncodeParams]
    Left = 360
    Top = 96
  end
  object IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL
    MaxLineAction = maException
    Port = 0
    DefaultPort = 0
    SSLOptions.Method = sslvTLSv1_2
    SSLOptions.SSLVersions = [sslvTLSv1_2]
    SSLOptions.Mode = sslmUnassigned
    SSLOptions.VerifyMode = []
    SSLOptions.VerifyDepth = 0
    Left = 336
    Top = 192
  end
end

Main.pas

UNIT Main;

INTERFACE

USES
  Winapi.Windows,
  Winapi.Messages,
  System.SysUtils,
  System.Variants,
  System.Classes,
  Vcl.Graphics,
  Vcl.Controls,
  Vcl.Forms,
  Vcl.Dialogs,
  Vcl.StdCtrls,
  IdIOHandler,
  IdIOHandlerSocket,
  IdIOHandlerStack,
  IdSSL,
  IdSSLOpenSSL,
  IdBaseComponent,
  IdComponent,
  IdTCPConnection,
  IdTCPClient,
  IdHTTP;

TYPE
  TForm1 = CLASS(TForm)
    IdHTTP1: TIdHTTP;
    IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL;
    lblURL: TLabel;
    edtURL: TEdit;
    lblPostParameters: TLabel;
    lblDiverName: TLabel;
    edtDiverName: TEdit;
    edtNextDive: TEdit;
    lblNextDive: TLabel;
    lblTeamCode: TLabel;
    edtTeamCode: TEdit;
    btnSend: TButton;
    PROCEDURE btnSendClick(Sender: TObject);
  PRIVATE
    { Private declarations }
  PUBLIC
    { Public declarations }
  END;

VAR
  Form1: TForm1;

IMPLEMENTATION

{$R *.dfm}

{
  URL for Christian:  https://judge.brooker.cloud/diverecorder/nextdive.php
  URL for Malcolm:    https://diverecorder.co.uk/dr_scripts/nextdive.php
}

PROCEDURE TForm1.btnSendClick(Sender: TObject);
VAR
  AURL, DNo, N, T: STRING;
  OK: boolean;
  Parameters: TStringList;
BEGIN
  AURL := edtURL.Text;
  DNo := edtNextDive.Text;
  N := edtDiverName.Text;
  T := edtTeamCode.Text;

  // Do all the fields contain some data?
  OK := True;
  IF AURL.IsEmpty THEN
    OK := False;
  IF DNo.IsEmpty THEN
    OK := False;
  IF N.IsEmpty THEN
    OK := False;
  IF T.IsEmpty THEN
    OK := False;
  IF OK THEN
  BEGIN
    // set up the parameters
    Parameters := TStringList.Create;
    TRY
      Parameters.Add('diveCode=' + DNo);
      Parameters.Add('Name=' + N);
      Parameters.Add('Team=' + T);

      IdHTTP1.Post(AURL, Parameters);

    FINALLY
      Parameters.Free
    END
  END
  ELSE
    ShowMessage('Please complete all the edit boxes.')

END;

END.
  • 2
    **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Nov 17 '21 at 10:58
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. – ADyson Nov 17 '21 at 10:58
  • P.S. You probably ought to share the Delphi code as well – ADyson Nov 17 '21 at 10:59
  • thanks for the info. it looks way over my head i'm afraid because i'm very new to all this. the delphi code is not mine. it's a small app that someone else uses to connect to my database. i've contacted them to try and get the code and i'll update this post once i get it. – user1019450 Nov 17 '21 at 11:30
  • Ok so you don't even know if the delphi is even calling the right URL or connecting in the right way or anything. – ADyson Nov 17 '21 at 11:39
  • i know the delphi is calling the correct file because i can specify it in the settings of the program. – user1019450 Nov 17 '21 at 11:53
  • Hm. When you access the PHP file via the browser do you need to log in first? – ADyson Nov 17 '21 at 11:57
  • Also, have you tried testing the PHP script using a tool such as Postman? That's a good way to test the HTTP request and the server's response without needing a browser, it would be more akin to how Delphi may be calling it. – ADyson Nov 17 '21 at 11:58
  • i didn't know about postman. thanks. ill check it out. no, i don't need to login to access the php files. – user1019450 Nov 17 '21 at 12:44
  • 403 error code means forbidden, probably the delphi code is calling wrong url. There is some checkpoint, first the dephi code should post data to your php script as **http**://yourserver:4200/yourscript.php according to your httpd configuration. so you should check httpd logs if there is correct access log or not. – Bart Nov 17 '21 at 19:28
  • i added the delphi code. Bart, thanks but the delphi code is posting to the correct php file, and there's no errors in the httpd logs, which i find very strange too. – user1019450 Nov 17 '21 at 22:47
  • `$sql = "UPDATE `judge` SET `score` = NULL;";` -- You really want to clear _all_ rows? That is, don't you need a `WHERE` clause? – Rick James Nov 20 '21 at 21:06
  • yes, i want to clear all rows. there is only ever 1 row. – user1019450 Nov 21 '21 at 05:45

0 Answers0