Detect if user manually refreshes a php-based web page [closed]

I have an php-based web page which auto-refreshes, and, I need to detect whether the user has manually refreshed the page. This is because I am using audio embedded within an iframe to sound alerts and for that to work reliably with Chrome, web page interaction by the user is required (to enable the audio to sound). The interaction is initially satisfied by the user pressing a form button to enables audio alerts (in Chrome). However, if the user manually refreshes the web page later, the audio is disabled (unless the user subsequently clicks the web page again). Am working on finding a solution.

Am still experimenting and looking for solutions…..

VSCode Live Server Extension Not Working on a Single Page

I am using the Live Server extension by Ritwick Dey, and it is working fine, except for one webpage of my website (the most important one). What happens is that the page loops for several seconds and then loads, or sometimes I also get a Server Error 500. What could cause this issue? Everything on the page works as expected.

Upon inspecting the page, the only error I see is:

Unchecked runtime.lastError: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received

However, I don’t know how to fix this or what it means.

Here’s a GIF that shows the issue: GIF Link

I tried resolving some JavaScript errors on the page, but it didn’t fix the problem.

app/Config/Database.php file is not writable [closed]

Trying to setup a free hrms tool(PHPHR version 13), everything works fine till I try to connect it with the datbase. it throws ‘app/Config/Database.php file is not writable!’
The database.php file is encrypted and is not generating any logs as well.
I have tried changing the owner of file and do chmod 777 still the same error.

I am not familar with PHP and also the code is encrypted with ioncube loader so cannot figure out what is the issue.

I am using
PHP v-8.2,
apache2 latest,
ioncube loader latest,
mysql – latest;

Automatic conversion of false value to array deprecation

I use OpenCart version 3.0.7 and PHP 8.1

I get this error:

Unknown: Automatic conversion of false to array is deprecated in
/home/public/musabgbar/storage/modification/catalog/controller/startup/startup.php
on line 133

After refreshing the page the error disappeared. That happens every time I close the browser and reopen it.
Do know how to modify the code?

        if (!$detect && !is_array($languages)) { 
                // Try using language folder to detect the language
                foreach ($browser_languages as $browser_language) {
                    if (array_key_exists(strtolower($browser_language), $languages)) {
                        $detect = strtolower($browser_language);                        
                        break;
                    }
                }
            }

php composer use function and call in required files doesn’t work

I’m trying to declare the JWT classes in a separate file to use them in functions, but it’s not working, and I really don’t understand why.

If I put the use declarations from use.php into jwt.php, it works fine, but I want to be able to put them elsewhere or at least understand why it doesn’t work.

I have the error message :

PHP Fatal error: Uncaught Error: Class “JWT” not found in
/var/www/config/includes/functions/jwt.php:4

I have created a minimal sandbox reproducing the structure of my project. Thank you for your help!

Here is the sandbox : https://phpsandbox.io/e/x/tromp?layout=EditorPreview&defaultPath=%2F&theme=dark&showExplorer=no&openedFiles=

Original Record Isn’t Reloading After Update [duplicate]

I have a customers page with an edit button. I can click the edit button, it loads the customers_edit.php page and I can edit the customer. When I click save, it grabs the customerID as the updateID and attempts to reload the customer_edit page with the updateID in the address bar but it gives me a “is currently unable to handle this request. HTTP ERROR 500” page. The address in the address bar is correct and if I simply click in the bar and hit enter, it loads the desired customer page. When I manually load the edit page, the edits have saved. What might I be missing here to get the page to re-load after updates on it’s own?

Here is the code:

<?php
require_once '../../../db_php/dbconnectiontickets.php';


$CustomerID=(isset($_GET['updateid'])  ? $_GET['updateid'] : '');
//require_once '../fireytech-project/db_php/dbconnectiontickets.php';
    session_start();

    if(!isset($_SESSION['user'])){
        header('location:../login.php');
    }




$sql = "SELECT * From Customers

           WHERE CustomerID ='$CustomerID'
"
;


$result = $conn->query($sql);
//echo "<pre>";print_r($result);die;
if ($result->num_rows > 0) {

    $row = $result->fetch_all(MYSQLI_ASSOC);
}


/*Update ccustomers table*/
$userName=explode('@',$_SESSION['user']['firstname']);
$userName=$userName[0];


if(!empty($_POST)){
   

    //DateEdited
    $Notes=$conn->real_escape_string($row[0]['Notes']);
    $NotesBilling=$conn->real_escape_string($row[0]['NotesBilling']);
    $company=$conn->real_escape_string($row[0]['Company']);
//    $billedAs=$row[0]['BilledAs'];
    $customerSource=$row[0]['CustomerSource'];
//    $customerType=$row[0]['CustomerType'];
    $customerStatus=$row[0]['CustomerStatus'];
    $donotcontact=$row[0]['donotcontact'];
    $dcpgreeting=$row[0]['dcpgreeting'];
    $dcpemailgroup=$row[0]['dcpemailgroup'];
    $shareddrive=$row[0]['shareddrive'];

    if($_POST['Notes'] !=''){
        $Notes=date('m/d/Y h:m'). ' '.$userName .'rn'.$conn->real_escape_string($_POST['Notes']).'rn'.$conn->real_escape_string($row[0]['Notes']);
        //$Notes=$conn->real_escape_string($Notes);
    }
    if($_POST['NotesBilling'] !=''){
        $NotesBilling=date('m/d/Y h:m'). ' '.$userName .'rn'.$conn->real_escape_string($_POST['NotesBilling']).'rn'.$conn->real_escape_string($row[0]['NotesBilling']);
        //$NotesBilling=$conn->real_escape_string($);
    }

        $company=$conn->real_escape_string($_POST['Company']);

//    if($_POST['BilledAs'] !=''){
//        $billedAs=$conn->real_escape_string($_POST['BilledAs']);

//    }


    if($_POST['CustomerSource'] !=''){
        $customerSource=$conn->real_escape_string($_POST['CustomerSource']);

    }

//    if($_POST['CustomerType'] !=''){
//        $customerType=$conn->real_escape_string($_POST['CustomerType']);

//    }

    if($_POST['CustomerStatus'] !=''){
        $customerStatus=$conn->real_escape_string($_POST['CustomerStatus']);

    }

    if($_POST['donotcontact'] !=''){
        $donotcontact=$conn->real_escape_string($_POST['donotcontact']);

    }  

    if($_POST['dcpgreeting'] !=''){
        $dcpgreeting=$conn->real_escape_string($_POST['dcpgreeting']);

    } 

    if($_POST['dcpemailgroup'] !=''){
        $dcpemailgroup=$conn->real_escape_string($_POST['dcpemailgroup']);

    } 

    if($_POST['shareddrive'] !=''){
        $shareddrive=$conn->real_escape_string($_POST['shareddrive']);

    }               

   // echo "<pre>";print_r($Notes);die;
    $currentDate=date('Y-m-d');

    //$updateSql="UPDATE Customers SET Notes=mysqli_real_escape_string($Notes),NotesBilling=mysqli_real_escape_string($NotesBilling) WHERE CustomerID ='$CustomerID' ";
    $updateSql="UPDATE Customers SET Notes='$Notes',NotesBilling='$NotesBilling',Company='$company',CustomerSource='$customerSource',CustomerStatus='$customerStatus',DateEdited='$currentDate',donotcontact='$donotcontact',dcpgreeting='$dcpgreeting',dcpemailgroup='$dcpemailgroup',shareddrive='$shareddrive' 
                 WHERE CustomerID ='$CustomerID' ";
    $conn->query($updateSql);      

     echo "<meta http-equiv='refresh' content='0'>";
    if ($conn->error) {
        printf("Error message: %sn", $conn->error);die;
    }
    }
  

//echo "<pre>";var_dump($saved);die;
?>

How to make header and footer fixed in Laravel DOMPDF when the content spans multiple pages?

I’m using the dompdf/dompdf package in my Laravel 9.52 application to convert HTML content into a PDF. My problem is that when the content of the PDF spans more than one page, I want the header and footer to stay fixed on every page.

Currently, the header and footer appear only on the first page, and they do not repeat or stay fixed on subsequent pages when the content overflows. How can I make the header and footer repeat on every page or stay fixed when the PDF spans multiple pages?

Here’s a simplified version of my code for generating the PDF:

use DompdfDompdf;
use DompdfOptions;

public function generatePdf()
{
    $dompdf = new Dompdf();
    $options = new Options();
    $options->set('isHtml5ParserEnabled', true);
    $options->set('isPhpEnabled', true);
    $dompdf->setOptions($options);

    $html = view('pdf.template', compact('data'))->render();
    $dompdf->loadHtml($html);
    $dompdf->render();
    $dompdf->stream('document.pdf');
}

i did try this :
=>Used position: fixed for the header and footer.
=>Tried adding padding/margins to prevent content from overlapping with the header and footer.

How to Convert an HTML Template into a WordPress Theme

I have a directory containing files for my website, including PHP and HTML files. I want to convert this into a WordPress website and upload my existing HTML template to use it as a WordPress theme.

What steps should I follow to turn my HTML template into a WordPress theme? Are there specific files or structure I need to create for WordPress compatibility? Any help or resources would be greatly appreciated!

Thank you!

Multi-Level Trouble-Shooting a PHP Script?

I have this PHP script:

<?PHP
// 0. Start The Session, If Not Already Started:
if(session_status() == PHP_SESSION_NONE)
{
session_start([ 
"lifetime" => 3600, 
"path" => "/", 
"domain" => $_SERVER["HTTP_HOST"], 
"secure" => isset($_SERVER["HTTPS"]), 
"httponly" => true, 
"samesite" => "Strict", 
]);
session_regenerate_id(true);
}

// 1. Configuration Settings:
define("ENABLE_REDIRECTION", 1);
define("ERROR_LOG_PATH", __DIR__ . "/Error_Log.txt");
define("DEFAULT_CHARSET", "UTF-8");
define("KAPIJA", "/");

// 2. Enable G. N. U. Zip Compression, If Supported by The Client:
if(isset($_SERVER["HTTP_ACCEPT_ENCODING"]))
{
if(strpos($_SERVER["HTTP_ACCEPT_ENCODING"], "br") !== false)
{
ob_start("ob_start_brotli");
}
elseif(strpos($_SERVER["HTTP_ACCEPT_ENCODING"], "gzip") !== false)
{
ob_start("ob_gzhandler");
}
else
{
ob_start();
}
}

// 3. Check for Session Hijacking:
if(!isset($_SESSION["IPaddress"]) || !isset($_SESSION["userAgent"]))
{
$_SESSION["IPaddress"] = $_SERVER["REMOTE_ADDR"];
$_SESSION["userAgent"] = $_SERVER["HTTP_USER_AGENT"];
}
elseif($_SESSION["IPaddress"] !== $_SERVER["REMOTE_ADDR"] || $_SESSION["userAgent"] !== $_SERVER["HTTP_USER_AGENT"])
{
session_unset(); // Clear session data
session_destroy(); // Destroy the session
session_start(); // Start a new session
session_regenerate_id(true); // Regenerate session ID
$_SESSION["IPaddress"] = $_SERVER["REMOTE_ADDR"];
$_SESSION["userAgent"] = $_SERVER["HTTP_USER_AGENT"];
}

// 4. Set A Session Timeout and Periodically Regenerate Session ID:
if(!isset($_SESSION["CREATED"]))
{
$_SESSION["CREATED"] = time();
}
elseif(time() - $_SESSION["CREATED"] > 1860)
{
session_regenerate_id(true);
$_SESSION["CREATED"] = time();
}

// 5. Security Headers:
header("Content-Type: text/css; charset=UTF-8");
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://trusted.cdn.com https://www.googletagmanager.com https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https://trusted.cdn.com; img-src 'self' data:; font-src 'self' data:; object-src 'none'; frame-ancestors 'none';");
header("X-Content-Type-Options: nosniff");
header("X-Frame-Options: DENY");
header("X-XSS-Protection: 1; mode=block");
header("Strict-Transport-Security: max-age=86400; includeSubDomains; preload");

// 6. Enable Error Logging for Debugging (Disable Display Errors for Production):
ini_set("display_errors", 0);
ini_set("display_startup_errors", 0);
ini_set("log_errors", 1);
ini_set("error_log", ERROR_LOG_PATH);
error_reporting(E_ALL);

// 7. Redirect to Home Page If Accessing Izvor.PHP:
if($_SERVER["REQUEST_URI"] === "/Izvor.PHP")
{
header("Location: " . KAPIJA, true, 301); exit();
}

// 8. Ensure UTF-8 encoding
mb_internal_encoding("UTF-8");
ini_set("default_charset", DEFAULT_CHARSET);
header("Content-Type: text/html; charset=" . DEFAULT_CHARSET);

// 9. Set Locale for Serbian (Both Latin and Cyrillic):
setlocale(LC_ALL, "sr_RS.UTF-8"); // Serbian Cyrillic
setlocale(LC_ALL, "[email protected]"); // Serbian Latin
setlocale(LC_ALL, "en_GB.UTF-8"); // British English

// 10. Comprehensive Function to Process URLs:
function process_comprehensive_url($url)
{
// 10. 1. Decode the URL to Get The Actual Characters:
$decoded_url = rawurldecode($url);
// 10. 2. Sanitize The URL:
$sanitized_url = htmlspecialchars($decoded_url, ENT_QUOTES, "UTF-8");
// 10. 3. Specific Handling for Ampersands:
$final_url = str_replace("&amp;", "&", $sanitized_url);
return $final_url; // Return The Processed URL
}

// 13. Secure Input Validation Function:
function secure_input($data)
{
return htmlspecialchars($data, ENT_QUOTES, "UTF-8");
}

// 14. Function to Internally Handle and Map Keys to Unique Identifiers:
function get_hashed_key($key)
{
static $key_map = [];
if($key === "")
{
$unique_key = md5(uniqid("", true));
$key_map[$unique_key] = $key;
return $unique_key;
}
return $key;
}

// 15. Function to Retrieve The Original Key:
function get_original_key($unique_key)
{
global $key_map;
return $key_map[$unique_key] ?? $unique_key;
}

// 16. URL-to-File-Path Mapping With and Without Leading Slashes and With Potential Empty Keys, Handled Internally, Including UTF-8 Names:
$url_map = [ 
get_hashed_key(process_comprehensive_url("")) => process_comprehensive_url(""), 
];

// 17. Downloading Map:
// Adding downloads on click:
$download_map = [
get_hashed_key(process_comprehensive_url("")) => "",
];

/* <?PHP
If(Session_Status() == PHP_SESSION_NONE)
{
Session_Start();
}
Echo(IsSet($_SESSION["metaTags"])? $_SESSION["metaTags"]: "");
?> */
// Functions to add META tags:
function addCommonMetaTags()
{
echo("<META HTTP-Equiv="Content-Type" Content="Text/HTML; CharSet=UTF-8">n");
}
function addSpecificMetaTags($page)
{
switch($page)
{
case("/"):
default:
echo("<META Name="Page-Name" Content="">n");
break;
}
}
function addMetaTags($page)
{
addCommonMetaTags();
// addSpecificMetaTags($page);
}

// Determine the page type based on the request URI
$request_uri = process_comprehensive_url($_SERVER['REQUEST_URI']);

// Normalize the request URI
$pageType = $request_uri;

// Start output buffering to capture and insert META tags
ob_start();
addCommonMetaTags();
addSpecificMetaTags($pageType);
$metaTags = ob_get_clean();

// Store the META tags in a session or a global variable for later use
$_SESSION["metaTags"] = $metaTags;

// 18. URLs and Their Pages:
$routes = [
get_hashed_key(process_comprehensive_url("/")) => __DIR__ . "/", 
];

// 19. Redirections:
$urls_to_be_redirected = [
get_hashed_key(process_comprehensive_url("/")) => process_comprehensive_url("/2025"), 
];

// 20. Define Error Pages:
$error_pages = [
"404" => __DIR__ . "/Errors/404.html", 
// Add more error pages if needed
];

// 21. Process The Request URI and Clean Path:
$request_uri = process_comprehensive_url($_SERVER["REQUEST_URI"]);
$clean_path = process_comprehensive_url(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));
$clean_path = ltrim($clean_path, "/");

// 22. Normalize Clean Path to Ensure It Matches Our Internally Handled Keys:
$normalized_clean_path = get_hashed_key($clean_path);

// 23. Debugging: Log The Processed Paths:
error_log("Processed request_uri: " . $request_uri);
error_log("Processed clean_path: " . $clean_path);

// 24. Handle FavIcon Requests:
if($clean_path === "Trougao" || $clean_path === "favicon.ico")
{
$favicon_path = __DIR__ . "/" . $url_map["Trougao"];
error_log("Serving favicon from path: " . $favicon_path);
if(file_exists($favicon_path))
{
serve_document($favicon_path, "image/png");
}
else
{
error_log("File not found: " . $favicon_path);
echo("File not found.");
}
exit();
}

// 25. Handle Download Requests:
if(array_key_exists($normalized_clean_path, $download_map))
{
$file_path = __DIR__ . "/" . $download_map[$normalized_clean_path];
error_log("Serving file for download: " . $file_path);
if(file_exists($file_path))
{
serve_document($file_path, "application/octet-stream", true);
}
else
{
error_log("File not found: " . $file_path);
echo("File not found.");
}
exit();
}

// 26. Handling The Root Path Case:
if($clean_path === "")
{
$clean_path = "/";
}

// 28. Function to Get The MIME Type of A File:
function get_mime_type($file)
{
$mime_types = [ 
"txt" => "text/plain", 
"html" => "text/html", 
"htm" => "text/html", 
"css" => "text/css", 
"csv" => "text/csv", 
"woff" => "font/woff", 
"woff2" => "font/woff2", 
"ttf" => "font/ttf", 
"otf" => "font/otf", 
"js" => "application/javascript", 
"json" => "application/json", 
"pdf" => "application/pdf", 
"xml" => "application/xml", 
"zip" => "application/zip", 
"rar" => "application/x-rar-compressed", 
"jpg" => "image/jpeg", 
"jpeg" => "image/jpeg", 
"png" => "image/png", 
"gif" => "image/gif", 
"ico" => "image/x-icon", 
"svg" => "image/svg+xml", 
"webp" => "image/webp", 
"mp4" => "video/mp4", 
"mp3" => "audio/mpeg", 
];
$extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
return $mime_types[$extension] ?? "application/octet-stream";
}

// 29. Serve The Document with Proper MIME Type:
function serve_document($document, $mime_type, $is_download = false)
{
if(file_exists($document))
{
header("Content-Type: " . $mime_type);
header("Content-Length: " . filesize($document));
header("Last-Modified: " . gmdate("D, d M Y H:i:s", filemtime($document)) . " GMT");
if($is_download)
{
header("Content-Disposition: attachment; filename='" . basename($document) . "'");
}
readfile($document); exit();
}
else
{
error_log("File not found: " . $document);
echo("File not found."); exit();
}
}

// 29. Rate Limiting to Prevent Abuse:
$rate_limit_key = $_SERVER["REMOTE_ADDR"] . ":" . $clean_path;
if(!rate_limit_check($rate_limit_key, 3010, 3600))
{
header("HTTP/1.1 429 Too Many Requests");
echo("Too many requests. Please try again later."); exit;
}
function rate_limit_check($key, $limit = 3010, $window = 3600)
{
$current_time = time();
if(!isset($_SESSION["rate_limit"][$key]))
{
$_SESSION["rate_limit"][$key] = ["count" => 0, "start" => $current_time];
}
$data = &$_SESSION["rate_limit"][$key];
if($current_time - $data["start"] > $window)
{
$data = ["count" => 0, "start" => $current_time];
}
$data["count"]++;
return $data["count"] <= $limit;
}

// 30. Check If Redirection Is Enabled and Handle Accordingly:
if(ENABLE_REDIRECTION && array_key_exists($request_uri, $urls_to_be_redirected))
{
$redirect_to = $urls_to_be_redirected[$request_uri];
if(array_key_exists($redirect_to, $routes))
{
$file_path = get_full_path($routes[$redirect_to]);
if(file_exists($file_path))
{
header("Location: $redirect_to"); exit();
}
else
{
log_error("File does not exist: $file_path");
handle_error(404, $error_pages);
}
}
else
{
log_error("Route does not exist: $redirect_to");
handle_error(404, $error_pages);
}
}
elseif(array_key_exists($request_uri, $routes))
{
$file_path = get_full_path($routes[$request_uri]);
if(file_exists($file_path))
{
require $file_path;
}
else
{
log_error("File does not exist: $file_path");
handle_error(404, $error_pages);
}
}
elseif(array_key_exists($clean_path, $url_map))
{
serve_document(__DIR__ . "/" . $url_map[$clean_path], get_mime_type($url_map[$clean_path]));
}
else
{
log_error("Route does not exist: $request_uri");
handle_error(404, $error_pages);
}

// 31. Error-Handling Function:
function handle_error($error_code, $error_pages)
{
http_response_code($error_code);
$error_message = "$error_code Error - Page not found";
log_error($error_message);
if(is_array($error_pages) && array_key_exists((string)$error_code, $error_pages) && file_exists($error_pages[(string)$error_code]))
{
include $error_pages[(string)$error_code];
}
else
{
echo("$error_message");
}
exit();
}

// 32. Function to Get The Full Path:
function get_full_path($path)
{
return (strpos($path, "/") === 0 || strpos($path, ":") === 1)? $path: __DIR__ . "/" . $path;
}

// 33. Logging Function:
function log_error($message)
{
error_log($message, 3, ERROR_LOG_PATH);
}
?>

Which has all the functions I currently need. It loads files as expected.
But when I enter responsive mode in Firefox, with this script, it stops loading some SubCSS (@import URL) files. When I entered console, it tells me that

header("X-Content-Type-Options: nosniff");

prevents CSS from being properly loaded in Firefox’s responsive mode.
I tried to fix it with the help of Copilot (Artificial Intelligence), but it keeps getting bad things far more worse. Can you please check it and improve it?
Copilot “changed” some code in it and, after that, the PHP script downloaded files without extension in stead of loading and displaying it properly in browser…
Can you please help me to improve my script to work fully well, both with responsive and non-responsive modes?

How to Resolve a 403 Forbidden Error When Scraping a Website Using PHP Simple HTML DOM Parser?

I am trying to scrape data from a website using the PHP Simple HTML DOM Parser. However, every time I attempt to fetch the HTML content of the page, I encounter a 403 Forbidden error.

To troubleshoot, I tried setting custom headers, including a User-Agent, using Guzzle PHP to mimic a browser request. Despite this, the issue persists, and I am unable to retrieve the webpage content.

// using simple dom parser
require '../simple_html_dom.php';

$html = file_get_html('https://www.mywebsite.com');
$title = $html->find('title', 0);
$image = $html->find('img', 0);

echo $title->plaintext."<br>n";
echo $image->src;
// using guzzle
require '../../vendor/autoload.php';

use GuzzleHttpClient;

$url = "https://www.mywebsite.com";
$client = new Client();

try {
    $response = $client->request('GET', $url, [
        'headers' => [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Accept-Language' => 'en-US,en;q=0.9',
            'Accept-Encoding' => 'gzip, deflate, br',
            'accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Referer' => 'https://www.mywebsite.com',
        ]
    ]);

    if ($response->getStatusCode() === 200) {
        $html = $response->getBody()->getContents();
        echo "Fetched HTML (first 500 characters):n" . substr($html, 0, 500) . "nn";

        // Continue with DOM parsing...
    } else {
        echo "Failed to fetch the URL. HTTP Status Code: " . $response->getStatusCode() . "n";
    }
} catch (Exception $e) {
    echo "An error occurred: " . $e->getMessage() . "n";
}

I suspect the server might have additional mechanisms, such as IP blocking, anti-bot protection, or cookies, that are causing the 403 error.

  • Are there other headers or configurations I should include to bypass
    the 403 Forbidden error?
  • Is there an alternative approach or library that might work better
    for scraping websites with such restrictions?

Any guidance on resolving this issue would be greatly appreciated!

HTML “required” Attribute does not work for spam bots

I have a form, which users should be able to submit only if they upload/attach a document. For that I use the following line:

<input type="file" id="file" name="attachment" accept=".pdf, .doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" required>

This code works for real users: on my webpage, I cannot submit the form without an attachment.

However, I receive many spam submissions without an attachment. How does that even happen? How can I avoid this?

I checked many times, but could not find a solution.

Edit:
I use a php form (Post) to enable submissions. Is there a php code that makes it possible?

Why does my redirected page ignore css styling and images

My .htaccess file that redirects users to a maintenance page but the page is displayed without any of my css styling

My .htaccess file looks like this.

RewriteEngine On
# Redirect to maintenance page unless query parameter supplied
RewriteCond %{QUERY_STRING} !^allowLogin=true$
RewriteCond %{REQUEST_URI} !/maintenance.php$
RewriteRule (.*) https://www.example.com/maintenance.php [R,L]

When the maintenance page is displayed via the .htaccess redirect, it looks like the image below. Notice the empty image and the lack of background color.
With .htaccess redirect

Without the .htaccess file, the page looks like the image below. Notice that the image is now correctly displayed and there is a colored background.
Without .htaccess redirect

The image is loaded by reference to the file containing it.
<img src="assets/img/current-logo.png" width="250px"></a>

The css background command is in a file loaded in the <head> tag
<link rel="stylesheet" href="assets/css/styles.css">

Here is a screenshot of the network tab in my Chrome browser debug tools showing all the calls and responses for the index and maintenance pages. They look OK to me but I’m not familiar enough with that tool to know if there are any problematic issues in it.

Chrome debug network screenshot here

For comparison, the Chrome network axreensghot I remove the .htaccess file is here

I am also seeing errors in the Chrome Console as shown here These errors are in third party tools and do not occur when I remove the .htaccess file.

I should also say this problem is not limited to the maintenance.php file. When I point my browser to any other file in my domain file and include the allowLogin query parameter,they are displayed with the same problems, missing background color and empty images.

Any help much appreciated

Issues with WordPress Admin Dashboard (Mobile View and Functionality)

I’m working on a project for a client who has some specific requests related to the WordPress admin dashboard. The client accesses the WordPress dashboard via a browser (not the app) and it’s RTL. Here’s a detailed list of the issues and attempted solutions so far:

1. Disable Responsive Design for the WordPress Admin Dashboard

The client wants to disable the responsive design for the dashboard only (not the site itself), so it appears the same on mobile as it does on desktop.

My Attempts:

Quick Solution: Used the “Request Desktop Site” feature available in browsers. However, this isn’t practical as editors have to enable it repeatedly.

Slow Solution: Downloaded the dashboard.css file, removed all the media queries, and loaded it with this code:

add_action('admin_enqueue_scripts', function () {
    // Deregister original styles
    wp_deregister_style('dashboard');
    wp_deregister_style('dashboard-rtl');

    // Enqueue custom styles
    wp_enqueue_style('dashboard', get_stylesheet_directory_uri() . '/custom/custom-dashboard.css', [], null);
    wp_enqueue_style('dashboard-min', get_stylesheet_directory_uri() . '/custom/custom-dashboard.min.css', [], null);
    wp_enqueue_style('dashboard-rtl', get_stylesheet_directory_uri() . '/custom/custom-dashboard-rtl.css', [], null);
    wp_enqueue_style('dashboard-rtl-min', get_stylesheet_directory_uri() . '/custom/custom-dashboard-rtl.min.css', [], null);
});

Unfortunately, this didn’t work as intended.

2. Redirect Dashboard to the “All Posts” Page

The client wants the dashboard to automatically redirect to the “All Posts” page (edit.php) after logging in or after pressing the Publish or Update button when editing a post.

Attempts so far:
I’ve tried various hooks like login_redirect and others, but I couldn’t get it to work for the Publish/Update action.

3. Text Cutting Issue

When I attempt to cut text (on mobile), it actually copies the text instead of cutting it. Additionally, it removes the last letter of the selected text during the process.

Troubleshooting steps taken:

Disabled all custom code in functions.php.
Deactivated all plugins.
Issue persists even in this clean state.

4. Unable to Type in the Title Field

When using “Request Desktop Site” in the mobile browser, I can paste text into the Title Field, but I cannot type directly in it.

I would appreciate any guidance or solutions for these issues.
Thank you so much

Can’t receive push notif in capacitorjs using FCM

I creating app using CapacitorJS and Svelte with php Backend, my problem is I fail to implement push notification while app is backgrounded (or killed)

here my Android manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:theme="@style/AppTheme.NoActionBarLaunch"
            android:launchMode="singleTask"
            android:exported="true">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="FCM_PLUGIN_ACTIVITY" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

        </activity>

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"></meta-data>
        </provider>

        <service
            android:name=".MyFirebaseMessagingService"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <receiver
            android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="${applicationId}" />
            </intent-filter>
        </receiver>

    </application>

    <!-- Permissions -->

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />



</manifest>

here my custom java class extending firebaseCloudMessaging

package com.appapp.omi;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.capacitorjs.plugins.pushnotifications.PushNotificationsPlugin;
import com.getcapacitor.BridgeActivity;
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginHandle;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import com.getcapacitor.Bridge;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginManager;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "PushNotificationService";
    private static final String CHANNEL_ID = "default_channel";

   

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        String title = "Default Title";
        String body = "Default Body";

        JSObject dataObj = new JSObject();

        if (remoteMessage.getNotification() != null) {
            title = remoteMessage.getNotification().getTitle();
            body = remoteMessage.getNotification().getBody();
        } else if (remoteMessage.getData().size() > 0) {
            // Handle custom data payload
            title = remoteMessage.getData().get("title");
            body = remoteMessage.getData().get("body");

        }

        if (MainActivity.bridge != null) {
            PluginHandle pushPluginHandle = MainActivity.bridge.getPlugin("PushNotifications");
            if (pushPluginHandle != null) {
                PushNotificationsPlugin pushPlugin = (PushNotificationsPlugin) pushPluginHandle.getInstance();
                pushPlugin.fireNotification(remoteMessage);
            }
//            MainActivity.bridge.triggerJSEvent("pushNotificationReceived", jsonString);
            // MainActivity.bridge.triggerWindowJSEvent("pushNotificationReceived", data.toString());
        } else {
            Log.e("MyFirebaseService", "Bridge not initialized");
        }
        // Show notification
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle(title)
            .setContentText(body)
            .setSmallIcon(R.mipmap.ic_launcher) // Replace with your app's notification icon
            .setPriority(NotificationCompat.PRIORITY_HIGH);

    
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        notificationManager.notify(0, builder.build());
    }
    
}

here my implementation pushnotif in capacitorjs

export async function registerPushNotifications() {
  try {

    PushNotifications.requestPermissions().then((status) => {
      console.log({status})
      if (status.receive === 'granted') {
        PushNotifications.addListener(
          "pushNotificationReceived",
          (notification) => {
            console.log()
            // console.log({notification: JSON.parse(notification)});
            addGNotif(notification);
          },
        );

        // Listener for errors
        PushNotifications.addListener("registrationError", (error) => {
          console.error("Push registration error:", error);
        });

        PushNotifications.addListener('pushNotificationActionPerformed', (action) => {
          console.log(action)
          alert("clicked")
        });

        FCM.getToken()
          .then((r) => {
            saveToken(r.token);
          })
          .catch((err) => console.log(err));
      }
    })



  } catch (error) {
    console.error('Push notification setup failed:', error);
  }
}

here my backend php


use KreaitFirebaseFactory;
use KreaitFirebaseMessagingCloudMessage;


function appapp_sendPushNotification($registrationTokens, $title, $body, $data = []) {
    // Initialize Firebase
    $factory = (new Factory)
        ->withServiceAccount(ABSPATH.DIRECTORY_SEPARATOR.'wp-content'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.'firebase-service-account.json'); // Optional if using Realtime Database

    $messaging = $factory->createMessaging();

    
    
    // Create the message
    $message = CloudMessage::new()
        ->withNotification([
            'title' => $title,
            'body' => $body,
        ])->withTarget('token', $registrationTokens)->withHighestPossiblePriority()->withAndroidConfig(array('priority' => 'high', 'notification' => [
            'title' => $title,
            'body' => $body,
        ], 'data' => $data));

    try {
        $response = $messaging->send($message);
        // $response = $messaging->sendMulticast($message, $registrationTokens);
        error_log(json_encode($response));
        return $response;
    } catch (Throwable $e) {
        error_log($e->getMessage());

        return $e->getMessage();
    }
}

my capacitor version is v.6

"@capacitor/android": "^6.1.2",
    "@capacitor/app": "^6.0.2",
    "@capacitor/cli": "^6.1.2",
    "@capacitor/core": "^6.1.2",
    "@capacitor/inappbrowser": "^1.0.2",
    "@capacitor/keyboard": "^6.0.3",
    "@capacitor/local-notifications": "^6.1.1",
    "@capacitor/preferences": "^6.0.2",
    "@capacitor/push-notifications": "^6.0.3",

my capacitor config

{
  "appId": "com.appapp.omi",
  "appName": "OMI App",
  "webDir": "dist/client",
  "allowNavigation": ["wa.me", "api.whatsapp.com", "orbitalmedika.co.id"],
  "plugins": {
    "PushNotifications": {
      "presentationOptions": ["badge", "sound", "alert"]
    },
    "Keyboard": {
      "resize": "none"
    }
  }
}

while app in foreground, notification is received but not while in background