r/PHPhelp Sep 28 '20

Please mark your posts as "solved"

78 Upvotes

Reminder: if your post has ben answered, please open the post and marking it as solved (go to Flair -> Solved -> Apply).

It's the "tag"-looking icon here.

Thank you.


r/PHPhelp 4h ago

Opensource PHP/Laravel LMS system feedback

2 Upvotes

Hi everyone,

Over the past few months, we've been building TadreebLMS, an open-source Learning Management System focused on enterprise and corporate training.

We've recently completed a major restructuring of the project

The project is built with:

  • PHP / Laravel
  • MySQL
  • Bootstrap / JavaScript
  • Docker

GitHub:
https://github.com/Tadreeb-LMS/tadreeblms

Issues:
https://github.com/Tadreeb-LMS/tadreeblms/issues

We have a huge roadmap like SCRUM Integration, UI upgrade as per FIGMA, Gap Analysis Module Integration, Integrations with HR Systems etc...

Please anyone experience or architect in PHP can give recommendation on best practices, gaps in the system etc..


r/PHPhelp 21h ago

Can you recommend free hosting for vanilla PHP database driven website in 2026?

0 Upvotes

I am building a simple vanilla PHP blog/portfolio website to post occasional blog posts and showcase some projects. I don't expect much traffic or the site requiring much server resources. Is there any free hosting providers for this type of websites in 2026? I know there's infinityfree.com, awardspace.com and some others but some folks mention that those free hosts can disappear overnight with your website data and never be back again lol.


r/PHPhelp 6d ago

Is there a Laravel media library that supports shared media?

1 Upvotes

I'm looking for something similar to Spatie Media Library, but where a single media item can be attached to multiple models.

For example, the same image could be linked to multiple products, blog posts, or categories without duplicating records/files.

Does a package like this exist, or did you end up rolling your own?


r/PHPhelp 7d ago

seeking advice for a image text extraction

3 Upvotes

Hi i am a junior laravel developer, right now i am asked to implement a service that extract data from a business card then create a record with it, at first i thought that frontend (web - mobile) should do the extraction part then hit a request with the data so that i do my checkings on it then create a record with it, but now when i started searching for the best way to do it claude tells me that the extraction part should be from the backend, i do not really know what is the best here, also if i will do it from the backend will the service for it be free? or the best way for it is from the frontend?


r/PHPhelp 8d ago

How to achieve silent thermal printing to a local USB printer from a hosted Laravel + Inertia + React POS?

4 Upvotes

I am building a Point of Sale (POS) system using Laravel, Inertia.js, and React. The application is hosted on a production server (HTTPS).

My goal is to achieve silent printing (direct printing without showing the browser’s print preview dialog) to a local USB thermal receipt printer (specifically an Xprinter) connected to the client machine (running Windows).

I have tried multiple approaches, but each has run into a major roadblock when moving from local development to production.

What I have tried so far:

  1. PHP ESC/POS Library (mike42/escpos-php)

How it worked: Excellent on localhost.

The Roadblock: Once deployed to production, this fails because PHP runs server-side. The hosted server has no access to the client’s local network or local USB ports to talk to the printer.

  1. Web Bluetooth API

How it worked: Worked fine during local testing.

The Roadblock: In production, even though the site is fully secured over HTTPS, navigator.bluetooth returns undefined or is unsupported on the client browsers (specifically tested in Brave/Chrome).

  1. WebUSB API + Zadig

How it worked: Allowed the browser to claim the device and send raw ESC/POS commands.

The Roadblock: Windows natively claims the USB printer driver. To bypass this, I had to use Zadig to force-replace the printer’s default driver with a generic WinUSB driver. This is not a viable or user-friendly solution for production deployments where non-technical staff need to set up printers.

  1. Standard Browser Printing (window.print())

How it worked: Works everywhere.

The Roadblock: It is highly unreliable for a fast-paced POS because it natively requires user interaction (clicking "Print" on the dialog). I need true silent printing where clicking "Pay" in my React app instantly fires the receipt.

My Tech Stack:

Backend: Laravel 10/11

Frontend: React (via Inertia.js)

Client OS: Windows

Hardware: USB Thermal Receipt Printer (Xprinter)

Browser: Brave / Chrome

The Question:

What is the industry-standard, reliable architecture to handle silent thermal printing from a cloud-hosted React frontend to a local USB printer?

Are there lightweight local bridge utilities (like a local WebSocket server) that are commonly paired with Laravel/React for this, or is there a way to make WebUSB/Web-Bluetooth work reliably in production without forcing clients to manually overwrite their Windows USB drivers?


r/PHPhelp 8d ago

Solved Need help with CakePHP lifecycle hooks

1 Upvotes

I have an entity called "Account". And I m trying to create and add an account verification token to a newly created account in beforeSave lifecycle hook. My problem is that "beforeSave" wants to get EventInterface and EntityInterface:

Cake\ORM\Table::beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options): void

So then I set a breakpoint inside of "beforeSave", I have an error that "The first argument should be of EventInterface, but Event is given" and "The second argument should be of EntityInterface, but Entity is given".

I have CakePHP 5.2, PHP 8.2 and I have "strict types" declaration in AccountsTable.php (that's a location of beforeSave hook).

I tried to remove "strict types" and this didnt help. I tried to add:

use Cake\Event\EntityInterface;

use Cake\Event\EventInterface;

This also didnt help.

What's the right way to make the thing work?


r/PHPhelp 10d ago

Copy Paste Problem on windows

7 Upvotes

Sorry I dunno if this is the right place to post this, I have no clue and php, SQL all that stuff but I'm having this problem with copying and pasting. If I try to copy and paste something I keep getting this code.

<br />

<b>Fatal error</b>: Uncaught mysqli_sql_exception: Too many connections in /www/wwwroot/clip-stash.beer/config.php:6

Stack trace:

#0 /www/wwwroot/clip-stash.beer/config.php(6): mysqli-&gt;__construct()

#1 /www/wwwroot/clip-stash.beer/api/index.php(6): require('...')

#2 {main}

thrown in <b>/www/wwwroot/clip-stash.beer/config.php</b> on line <b>6</b><br />

I have absolutely no idea what it means. I tried googling but its just leading me to stuff about SQL servers and stuff which I have absolutely no clue about. Am I being hacked or something? Hopefully someone can help as I can't copy and paste anything atm. Again sorry if this is the wrong place.


r/PHPhelp 10d ago

Using APCu instead of sessions and for rate limiting

2 Upvotes

In trying to find a way to rate limit bots server side (more complicated than I could manage with Cloudflare), I discovered APCu. Specifically:

# in Apache
RewriteCond %{QUERY_STRING} foo=([0-9]{3,}) [NC]
RewriteRule ^ - [E=HIGH_FOO:1]
RequestHeader set X-High-Foo "1" env=HIGH_FOO

# in PHP
if (isset($_SERVER['HTTP_X_HIGH_FOO'])) {
  $ip    = $_SERVER['REMOTE_ADDR'];
  $key   = 'rl_sv_' . $ip;
  $count = apcu_exists($key) ? apcu_fetch($key) : 0;

  if ($count >= 10) {                 // e.g. 10 req/min threshold
    http_response_code(429);
    header('Retry-After: 10');
    exit('Rate limit exceeded');
  }

  apcu_inc($key, 1, $success, 60);    // 60s TTL
}

Two questions:

  1. Will this work as expected to rate limit to 10 requests per 60s when foo is greater than 100?
  2. What's the downside?

If it matters, I'm using EasyApache on WHM/cPanel and have both PHP 5.6 and 7.4 installed. Version 5.6 is to accommodate a hosting client that refuses to update anything, and I haven't updated the other sites to 8.x yet because it'll require a bit of coding work and there's just not enough time in the day.

Follow up: if it works fine with no downside, is there a reason to not store variables here instead of relying on sessions or MySQL?


r/PHPhelp 10d ago

Best identifier for clients

2 Upvotes

Hey everyone,

My site was hit with a 'card verifier attack'. Basically my processor uses a token that is vidable to the visitor to verify cards. I suspect the attack just got that number, and wrote his own script.

I am switching my CC processing to a system that uses One Time Use tokens for processing. Thay way, it can't be done that way again.

The idea is everytime someone loads a shopping cart, they get a token that can only be used once.

I'd like to harden even more by tracking how often the same user request a token. If they go over a certain amount, it will stop giving them tokens.

What is the best way to track if a request is from the same user. I was thinking IP, but my understanding is that's really easy to spoof. Not to mention, if the attacker uses a VPN, I might block an IP that a legit user might use.

Any ideas?


r/PHPhelp 11d ago

Multi tenant application, I need help with choosing the best approach

0 Upvotes

Hello,

TLDR; I am making a somewhat of a shop where each shop has its own subdomain, and I am now wondering whether the login for tenant (who manages the shop, no one else will be able to login) should live on its own shop domain or a different/centralized domain... Laravel sprout is used for multi tenancy.

I am starting to build a multi tenant application (first time dealing with the multi tenant app), and I need help from you. Sorry if it is not the right place, but here I am using laravel sprout for multi tenancy.

The current struggle I have is: where do I put the authentication for my tenants?
I am making somewhat of a shop, where the normal user will be able to browse items, make an order then get a link, send it to the shop owner and the owner can open it and it will lead him straight to managing the order (this is the reason why I need the authentication per subdomain)

What are PROS and cons of this approach? The con is that the tenant if he has multiple shops he will need to switch subdomains in order to manage everything... Also the guest and the auth will be shared per subdomain while if I keep the tenant login separate, the tenants can manage their shop from the other subdomain e.g. manage.subdomain.something.

P.S. Sorry, if this is not the right place for this subject


r/PHPhelp 12d ago

Encoding error with curl and LoadHTML()

3 Upvotes

Hi all,

I'm very new to php, but I'm learning as time goes along. I'm currently making a webcrawler in php for my a level computer science project. I have it working, getting all the links off of a page, trying to run the page, and then if it doesn't throw and error whilst requesting the content of the next page, it loops around, I am currently just looking to see what links work and what links won't work and if there's anything I can do to make them work so I can get more websites into my index.

My main issue currently is at about 15000 websites in (which takes like an hour and a half to get to which is very time consuming) I get a content encoding error.

Is there anyway to fix this so I don't get an error every time?

Thanks in advance

Here is my code for those that would like it for help (it's just an amalgamation of other people's code along with some logic based stuff on my end, I turned off warnings because id get about 600 errors come through from just trying to load wikipedia and it was majorly slowing down my already slow code):

<?php

error_reporting(E_ALL ^ E_WARNING);

$currenttime = time();

// define the target URL

$StartUrl = 'https://en.wikipedia.org/wiki/Main_Page';

/**

* Get a web file ( HTML, XHTML, XML, image, etc. ) from a URL. Return an

* array containing the HTTP server response header fields and content.

*/

function get_web_page( $url ) {

$user_agent = 'Computer Science project Web Crawler';

$options = array(

CURLOPT_CUSTOMREQUEST =>"GET", //set request type post or get

CURLOPT_POST =>false, //set to GET

CURLOPT_USERAGENT => $user_agent, //set user agent

CURLOPT_COOKIEFILE =>"cookie.txt", //set cookie file

CURLOPT_COOKIEJAR =>"cookie.txt", //set cookie jar

CURLOPT_RETURNTRANSFER => true, // return web page

CURLOPT_HEADER => false, // don't return headers

CURLOPT_FOLLOWLOCATION => true, // follow redirects

CURLOPT_ENCODING => "", // handle all encodings

CURLOPT_AUTOREFERER => true, // set referer on redirect

CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect

CURLOPT_TIMEOUT => 120, // timeout on response

CURLOPT_MAXREDIRS => 10, // stop after 10 redirects

//this is very poor technique but it makes the code work

CURLOPT_SSL_VERIFYPEER => false, // disables their verifying certificate

//CURLOPT_SSL_VERIFYHOST => false, // disables my verifying certificates

);

$ch = curl_init( $url );

curl_setopt_array( $ch, $options );

$content = curl_exec( $ch );

$err = curl_errno( $ch );

$errmsg = curl_error( $ch );

$header = curl_getinfo( $ch );

curl_close( $ch );

$header['errno'] = $err;

$header['errmsg'] = $errmsg;

$header['content'] = $content;

return $header;

};

//$array = get_web_page($StartUrl);

//echo $array['errno'].'<br>';

//echo $array['errmsg'].'<br>';

//echo $array['content'];

$stackdepth = 1;

$maxstackdepth = 3;

$cfs = 1;

$pagecount = 0;

$arraylength = 1;

$worked = 0;

$workings= array();

$fails = array();

$banned = array();

$file = "webcrawllinklist.txt";

$txt = fopen($file, "w") or die("Unable to open file!");

$linksArray = array();

array_push($linksArray,$StartUrl);

array_push($banned,$StartUrl);

while ($arraylength !=0){

$array = get_web_page($linksArray[0]);

$pagecount ++;

echo $pagecount."<br>";

//echo $array['errno'].'<br>';

//echo $array['errmsg'].'<br>';

if($array['errno'] == 0){

$worked ++;

array_push($workings, $linksArray[0]);

$Page = new domDocument;

$Page -> loadHTML("<html>".$array['content']."</html>");

$Page->preserveWhiteSpace = false;

$links = $Page->getElementsByTagName('a');

$links = iterator_to_array($links);

for($i = 0; $i < count($links);$i++) {

$link = $links[$i];

$link = $link->getAttribute('href' );

//echo $link."<br>";

$if = strpos( $link, "//" );

$start = $if == false? false: $if+2;

//echo $start."<br>";

if ( $start ) {

$link = substr( $link, $start, strlen( $link )-( $start ) );

}

;

//echo $link."<br>";

if ($stackdepth != $maxstackdepth){

if (!in_array($link,$banned)){

array_push( $linksArray, $link);

array_push($banned,$link);

$arraylength ++;

};

};

};

} else{

array_push($fails,$linksArray[0]);

};

array_splice($linksArray,0,1);

$arraylength --;

$cfs--;

if ($cfs == 0){

$stackdepth++;

$cfs += $arraylength;

};

};

$output = "Works:\n";

for ($i=0;$i<count($workings);$i++){

$output = $output.$workings[$i]."\n" ;

};

$output = $output."\n Failed: \n";

for ($i=0;$i<count($fails);$i++){

$output = $output.$fails[$i]."\n" ;

};

echo $pagecount."= num of pages <br>";

echo $worked."= num that worked <br>";

$newtime= time();

$timeelapsed = $newtime - $currenttime;

$output = $output."\n time taken: ".$timeelasped;

echo $timeelapsed."= time taken <br> <br><br><br><br><br>";

fwrite($txt, $output);

fclose($txt);

header('Content-Description: File Transfer');

header('Content-Disposition: attachment; filename='.basename($file));

header('Expires: 0');

header('Cache-Control: must-revalidate');

header('Pragma: public');

header('Content-Length: ' . filesize($file));

header("Content-Type: text/plain");

readfile($file);

?>

The error on Firefox specifically says "content encoding error

The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression."

I'm using MAMP on an emulated windows 11 (I'm running Linux but I couldn't get any other local hosting apps to work so I'm using one my computer science teacher showed me on an emulated windows 11 because my school laptop doesn't let CURL work)


r/PHPhelp 12d ago

grocy - wie PHP Limit erhöhen auf Synology / Docker Installation

0 Upvotes

Hi ich benötige Hilfe, wie man das PHP Limit für Grocy erhöht (und bin Laie was PHP betrifft) Groy ist auf meiner Synology DS 918+ unter Docker installiert und funktioniert im Prinzip (alle Funktionen sind über das Handy problemlos benutzbar). Einige Views funktionieren jedoch nicht wenn ich sie über den Web.browser meines Windows11 PCs aufrufen möchte. (Die Fehlermeldung lautet:

:2026/03/16 12:27:09 [error] 279#279: *41901 FastCGI sent in stderr: "PHP message: PHP Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 26169344 bytes) in /config/data/viewcache/1c639f3ceb27870716fc6191833ec04b.php on line 10

siehe nachstehend meinen ersten Hilferuf, zu dem ich leider keine Tips bekommen habe https://www.reddit.com/r/grocy/comments/1rv74qh/grocy_some_views_like_purchase_not_working_for_me/)

Ich war in Kontakt mit Berrnd dem Entwickler von grocy, aber er konnte mir leider bzgl. PHP auf Synology Docker nicht helfen, hat mir aber dankenswerterweise den Hinweis gegeben, dass die Fehlermeldung auf ein zu geringes PHP Limit für Grocy hinweist.

Wie ändere ich bitte das PHP Limit für Grocy? Ich möchte ungern >700 Produkte bei einer Neuinstallation anlegen in der Hoffnung, dass es dann dauerhaft funktioniert.

PS Im Ordner docker/grocy/php finde ich eine "php-local.ini" Datei, die mir aber leer zu sein scheint (Inhalt: "; Edit this file to override php.ini directives"). Falls hier ein höheres Limit gesetzt werden muss, wäre ich dankbar für den konkreten Befehl dazu,

VIELEN DANK vorab!!!!


r/PHPhelp 13d ago

Imagick, GIF frames, and compositing

1 Upvotes

Hello, I can't seem to find the step(s) that I'm missing. I am pulling a NWS radar image every 10 minutes and changing the colors to not blind me on a dashboard in the morning.

In changing the white land background to gray it's also affecting the header and footer, so I copy them out first and then composite them back in after a flood fill. The problem is I'm getting only the first frame of the footer, so instead of a changing clock per image, I'm getting only the start time. The individual image frames are changing, just not the footer.

I tried looking into masking the image before flood filling but I couldn't figure that one out.

Please let me know if you have any suggestions, thank you!

<?php
require "lib.php"; //For my curlGet() which adds an agent header

$fuzz = 0.01 * Imagick::getQuantum();
$site = "AKQ";

file_put_contents("radar.gif", curlGet("https://radar.weather.gov/ridge/standard/K{$site}_loop.gif"));
$im = (new imagick("radar.gif"))->coalesceImages();

foreach ($im as $frame)
{
    $upper = clone $frame;
    $upper->cropImage(600, 24, 0, 0); //WHXY
    $lower = clone $frame;
    $lower->cropImage(600, 24, 0, 526); //WHXY

    $frame->opaquePaintImage("white", "rgb(75,75,75)", $fuzz, false);
    $frame->opaquePaintImage("rgb(194,234,240)", "rgb(0,0,100)", $fuzz, false);

    $frame->compositeImage($upper, Imagick::COMPOSITE_OVER, 0, 0);
    $frame->compositeImage($lower, Imagick::COMPOSITE_OVER, 0, 526);
}

$im->deconstructImages();
$im->writeImages("html/radar{$site}.gif", true);

r/PHPhelp 13d ago

Session values are not being retained across pages

3 Upvotes

Hi all,

I recently migrated several of my web applications from CentOS 8 to Rocky Linux 8.1. After the migration, I’m facing an issue with session handling in most of the applications.

Session values are not being retained across pages (i.e., values set in one page are not available in subsequent requests). However, one of the applications on the same server is working perfectly fine with sessions, which makes this a bit confusing.

OS: Rocky Linux 8.1 (migrated from CentOS 8)

Since one app works and others don’t, I suspect some config/environment inconsistency, but I’m unable to pinpoint it.

Has anyone faced a similar issue after migrating to Rocky Linux? Any suggestions on what else I should check?

Thanks in advance.


r/PHPhelp 14d ago

How do I integrate a CRM with an existing PHP website when I only have cPanel access?

Thumbnail
1 Upvotes

r/PHPhelp 14d ago

Developing in Laravel: Is it worth sticking with VS Code or do you use other IDEs? (Issues with Blade & Autocomplete)

0 Upvotes

Hi everyone,

I'm working on my first Laravel project, and as much as I love the framework, I'm having a lot of trouble properly configuring my development environment using Visual Studio Code. I constantly feel like I'm fighting the editor rather than focusing on writing code, to the point where I'm starting to wonder if I should just switch tools.

Here are the main issues I'm facing that are slowing me down quite a bit:

1. Lack of HTML support in .blade.php files

Writing UIs is quite frustrating right now. As soon as I name a file .blade.php, VS Code seems to forget how to handle standard HTML:

  • Typing < doesn't suggest tags (like div, span, form, etc.).
  • I get no autocomplete for HTML attributes (e.g., class, href, type).
  • Tags don't auto-close when I type >.

Basically, I lose all the native support and suggestions (including Emmet) that I usually get when working in a standard .html file.

2. Unrecognized Eloquent methods and PHP "false errors"

When working in Controllers, my PHP analyzer (I use Intelephense) fails to correctly interpret Laravel's structure, either hiding suggestions or throwing non-existent errors. Two classic examples:

Missing suggestions: If I try to use common methods like findOrFail, the editor doesn't help at all.

PHP

// The editor only suggests "find", "findOr", and "findIndex", 
// but NOT findOrFail, forcing me to memorize it.
$post = Post::findOrFail($id);

False parameter errors: The editor underlines the update() method with a red squiggly line, claiming it accepts no arguments, even though the code works perfectly and updates the database.

PHP

$validated = $request->validate([
    'title' => 'required|min:2|max:12',
    'body' => 'required'
]);

// The line below is highlighted as an error by the editor:
// "Too many arguments. Expected 0. Found 1"
$post->update($validated); 

3. Installing extensions didn't fix it

To try and mitigate the situation, I installed several highly recommended Laravel extensions, but surprisingly, nothing changed. The issues described above persist exactly as if I hadn't installed anything at all, giving me no real help. Here is the list of my currently active extensions:

  • Auto rename tag (Jun Han)
  • Laravel (Laravel)
  • PHP Intelephense (Intelephense)
  • Code Runner
  • Code Spell Checker
  • ESLint
  • Jest

In light of all this, I'd like to ask an open question to those of you who work professionally or daily with Laravel: do you all use VS Code, or have you moved on to more fully-featured IDEs? If you use other IDEs, do you think switching to a different tool is worth it to handle Laravel's "magic" natively and out-of-the-box? Or, if you are loyal to VS Code, could you tell me how you configured your environment to fix these headaches? I would be incredibly grateful for any tips on your ideal setup!

Thanks in advance to anyone willing to share their experience.


r/PHPhelp 15d ago

Spent 8+ hours chasing a login bug... it wasn't what I expected.

0 Upvotes

Today was one of those days that reminds you why software engineering is equal parts debugging and detective work.

My Laravel application suddenly stopped letting users log in. The login page loaded perfectly, but after submitting credentials it just redirected back to /login.

At first, I blamed everything except the application:

Moved the project to a fresh VPS.

Reconfigured Nginx.

Installed SSL again.

Checked DNS.

Restored the database.

Verified the user existed.

Confirmed Auth::attempt() returned true.

Verified cookies and sessions.

Checked maintenance mode.

Audited middleware.

Every time I eliminated one possibility, another theory took its place.

The interesting part is that the exact same codebase works perfectly on my local machine, but the staging environment refuses to stay authenticated after login. That means the problem is probably environmental or somewhere in the request lifecycle rather than in the login credentials themselves.

Today's biggest reminder:

Don't assume the first symptom is the real problem.

A login issue isn't always an authentication issue.

Sometimes it's a session problem.

Sometimes it's middleware.

Sometimes it's routing.

Sometimes it's a configuration difference you don't even know exists yet.

I'm not done yet, but I've narrowed the search down dramatically. That's progress.

What's the most frustrating bug you've ever spent hours chasing, only to discover the cause was completely different from what you expected?


r/PHPhelp 16d ago

Laravel Project

0 Upvotes

I have a small Laravel project but I’m new to this framework and I’m finding hard to work with,

What the application is just a Hostel( Accommodation) website for my school that I have to do before the month ends,
I already have my requirement documentation and how the current the paper process works.

Is there anyone who would like to help?


r/PHPhelp 18d ago

Directory structure for vanilla PHP blog/project CMS

4 Upvotes

Can you take a look if this directory structure is good for vanilla PHP blog/project CMS ? I was curious if I can build my own CMS for blog posts, blog archives and projects. Before I had a WordPress site with those features which I built using Underscores. Please see here directory structure


r/PHPhelp 21d ago

Scrutinizer for php 8.4

1 Upvotes

I keep noticing that readonly classes are ignored, propertyhooks are being flagged as faults etc.
Anybody figured out how to make it work or what I can replace it with?
I mostly use it for the Code Rating.
I also look at the issues, but all the issues lately seem to be related to newer php features.

Included my config just in case that's the issue

build:
    image: default-jammy
    nodes:
        analysis:
            environment:
                php:
                    version: "8.4.1"
            cache:
                disabled: false
                directories:
                    - ~/.composer/cache
            project_setup:
                override: true
            dependencies:
                override:
                    - 'composer install --no-interaction --prefer-dist --optimize-autoloader'
            tests:
                override:
                    - php-scrutinizer-run

filter:
    excluded_paths:
        - bin/*
        - config/*
        - node_modules/*
        - src/Core/templates/Maker/*
        - var/*
        - vendor/*

tools:
    php_analyzer:
        enabled: true
        config:
            parameter_reference_check: { enabled: true }
            checkstyle: { enabled: true }
            suspicious_code: { enabled: true }
            unreachable_code: { enabled: true }
            unused_code: { enabled: true }

    php_mess_detector: true
    php_sim: true
    php_pdepend:
        excluded_dirs:
            - vendor

    php_code_sniffer:
        config:
            standard: phpcs.xml.dist
        filter:
            excluded_paths:
                - 'src/Core/templates/Maker/*'
                - 'src/Modules/*/tests/*'

checks:
    php:
        unused_variables: true
        unused_properties: true
        unused_parameters: true
        variable_existence: true
        unused_methods: true
        sql_injection_vulnerabilities: true
        simplify_boolean_return: truebuild:
    image: default-jammy
    nodes:
        analysis:
            environment:
                php:
                    version: "8.4.1"
            cache:
                disabled: false
                directories:
                    - ~/.composer/cache
            project_setup:
                override: true
            dependencies:
                override:
                    - 'composer install --no-interaction --prefer-dist --optimize-autoloader'
            tests:
                override:
                    - php-scrutinizer-run

filter:
    excluded_paths:
        - bin/*
        - config/*
        - node_modules/*
        - src/Core/templates/Maker/*
        - var/*
        - vendor/*

tools:
    php_analyzer:
        enabled: true
        config:
            parameter_reference_check: { enabled: true }
            checkstyle: { enabled: true }
            suspicious_code: { enabled: true }
            unreachable_code: { enabled: true }
            unused_code: { enabled: true }

    php_mess_detector: true
    php_sim: true
    php_pdepend:
        excluded_dirs:
            - vendor

    php_code_sniffer:
        config:
            standard: phpcs.xml.dist
        filter:
            excluded_paths:
                - 'src/Core/templates/Maker/*'
                - 'src/Modules/*/tests/*'

checks:
    php:
        unused_variables: true
        unused_properties: true
        unused_parameters: true
        variable_existence: true
        unused_methods: true
        sql_injection_vulnerabilities: true
        simplify_boolean_return: true

r/PHPhelp 22d ago

weird behavior in including files

3 Upvotes

i have a weird problem in including files in php, i have a functions.php file in a folder and a Router in the index.php file, when i include thefunctions.php in the index.php, all the other pages that rely on it get broken, the variables become empty and the functions no longer work, when i dont include it in the index.php file all the other pages function normally

i include my files in all pages in this way

require_once($_SERVER["DOCUMENT_ROOT"] . "/src/logic/functions.php");

my other pages are in /src/pages/

i have tried all ways of including the file but i keep getting the same problem, i need to include the functions.php in the index file to use some of its functions.

i do have a declare(strict_types=1) in the index file if that affects it

Any help will be appreciated thanks.


r/PHPhelp 24d ago

Solved file not being deleted after its expiry time passes

2 Upvotes

Hello, im trying to make a rate limiting function that prevent users from using specific forms when they reach a certain threshold and the limit will get reset after a certain amount of time, when a user submits a request, a file with their ip will get created into a cache folder and the amount of requests is inside the file, the rate limiting works except the file doesnt get deleted after the specified amount of time passes, any help will be appreciated. Thanks!

rate_limiter.php

<?php
ignore_user_abort(true);
//Get the user IP
function getIP() {
$ip = null;
if(!empty($_SERVER["REMOTE_ADDR"])) {
$ip = $_SERVER["REMOTE_ADDR"];
} elseif(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}

return $ip;
}

function rate_limit($ip, $requests_limit, $limit_expiry) {
$start_time = null;
$reached_limit = null;
$amount_requests = 1;
$file_name = __DIR__ . "/cache/ratelimit-" . $ip;
$file_name = rtrim($file_name);
if(!file_exists($file_name)) {
global $start_time;
$start_time = time();
$fp = fopen($file_name, "w+") or die("An error occured");
fwrite($fp, $amount_requests) or die("Failed to write into file");
fclose($fp);
} elseif(file_exists($file_name)) {
$fp = fopen($file_name, "r+") or die("Failed to read file");
$new_amount_requests = file_get_contents($file_name);
if($new_amount_requests >= $requests_limit) {
global $reached_limit;
echo "<script>alert('You have been rate limited!')</script>";
$reached_limit = true;
header("Location: /", 423, true);
} elseif(!$reached_limit) {
$new_amount_requests++;
ftruncate($fp, 0);
fwrite($fp, $new_amount_requests) or die("Failed to write amount of requests");
}
}

if(file_exists($file_name) && time() - $start_time >= time() + $limit_expiry) {
unlink($file_name);
}




}

?>

index.php

<?php
ignore_user_abort(true);
require_once("rate_limiter.php");

if(isset($_POST["submit"])) {
$ip_Addr = getIP();
rate_limit($ip_Addr, 3, 60);
echo $_POST["text"];
}

?>

r/PHPhelp 26d ago

Composer installation fails with "certificate verify failed" PHP beginner

5 Upvotes

Hi everyone,

I’m a beginner in PHP and I’m currently trying to install Composer on Windows with WampServer.

I keep getting an SSL certificate verification error during the installation (certificate verify failed / Failed to enable crypto), and I’m not sure how to fix it.

I’ve already checked my php.ini file, but as a beginner I may be missing something important.

Could anyone help me understand what’s causing this issue and how to solve it? Any simple explanation would be greatly appreciated.

Thank you in advance!


r/PHPhelp 28d ago

Old Developer Went AWOL so I Inherited a Wordpress CRM on Bluehost, How Do I Fix the Code?

Thumbnail
2 Upvotes