r/PHPhelp • • Sep 01 '24

php 8.4 property hooks... is this a bug?

7 Upvotes

So I'm doing some testing with php 8.4's new property hooks and reflection....
https://wiki.php.net/rfc/property-hooks

https://3v4l.org/RgWO8/rfc#vgit.master :

<?php

class PropertyHooks
{
    public ?string $backedGetOnly {
        get => $this->backedGetOnly;
    }

    public ?string $backedSetOnly {
        set (?string $value) {
            $this->backedSetOnly = $value;
        }
    }

    public ?string $backedGetAndSet {
        set (?string $value) {
            $this->backedGetAndSet = $value;
        }

        get => $this->backedGetAndSet;
    }
}

$propertyHooks = new PropertyHooks();

$reflectionProperty = new ReflectionProperty($propertyHooks, 'backedGetOnly');

$reflectionProperty->isInitialized($propertyHooks); // returns true - I would expect false
                                      // backSetOnly reports  false
                                      // backedGetAndSet reports true - I would also expect false

if ($reflectionProperty->isInitialized($propertyHooks)) {
    $reflectionProperty->getRawValue($propertyHooks); // Uncaught exception 'Error' with message Typed property PropertyHooks::$backedGetOnly must not be accessed before initialization
}

isInitialized() seems to be based on whether or not there's a get hook instead of the backing-value


r/PHPhelp • • Aug 26 '24

Moving away from Laravel Forge to manual server management

7 Upvotes

Hey guys, recently I setup my server using Laravel forge. I had previously set up an nginx server on Ubuntu a couple of times and wanted to save the time of setting up a server, thus chose to use Forge. However, I am not finding any use of it after the initial setup. I want to stop using Forge and do the server management by myself. Will the automatic CI CD be intact if I stop using forge? How can I make this transitions


r/PHPhelp • • Aug 01 '24

Solved What is the most common PHP code formatter?

7 Upvotes

I found three code formatters for PHP.

I was able to setup Prettier with the PHP plugin but the setup is not ideal since I have to install prettier and the prettier PHP plugin from NPM into the project every single time which is not the case when using Prettier VSCode extension with HTML, JS and CSS. I do like how Prettier has its own configuration .prettierrc files and it allows you to set a standard format for a project you are collaborating with others, however I believe formatting should be done in the IDE such as using a VSCode extension and this is the case with the Prettier extension for HTML, JS and CSS but not for PHP since it requires NPM packages.

The other two do not look popular. Am I missing something? I would like to have a standard format or be able to have an opinionated format setup like Prettier for JS but for PHP.


r/PHPhelp • • May 27 '24

Help! Hacker makes index files in folders - How Do I Stop This?

7 Upvotes

Hi everyone,

I'm in a bit of a bind and could really use some advice. I have a self coded php website hosted on cPanel, and recently, I've been dealing with a persistent hacker. This person keeps adding malicious code to my index file and creating random index files in random folders throughout my website.

I've attached the code of the PHP index file that the hacker creates [https://ibb.co/tCL07fJ]

I've tried deleting all the files they created, but the hacker somehow keeps coming back and creating new ones. It feels like a never-ending battle.

What steps can I take to secure my cPanel and stop this hacker from injecting their code again? Any help or suggestions would be greatly appreciated!

Thanks in advance.


r/PHPhelp • • May 06 '24

Do you ever create flowcharts for your code?

7 Upvotes

I was creating a function that had several conditional checks and it was kinda breaking my brain to follow the steps in my head.

I remembered that years ago I saw a video where someone talks about using flowcharts for code so I created and it helped me see everything very clearly.

Do programmers in general do this? Like, when multiple engineers have to work on the same system? Or only when they're having trouble like I was?


r/PHPhelp • • Mar 26 '24

Solved I want to learn how to write tests, should I start with PHPUnit or Pest?

7 Upvotes

Sorry if it's a stupid question, but I've never written a test before. And it gives me these options while I'm creating a new Laravel project. Which one should I go with?


r/PHPhelp • • Dec 20 '23

Senior php devs If you are to take a interview of fresher for php developer role and you have to give him a challenge project that takes 1-1.5 hour. What task will you give him.

7 Upvotes

I know giving 1.5 hour task is stupid but its common in my area all jobs i think of applying has long tedious interview speically in php


r/PHPhelp • • Dec 01 '23

Solved bots are using my form (Laravel)

7 Upvotes

Hi everyone, I have a laravel website that has a contact form where you put your conctact info, the data is sent to my client's mail and then they contact you....

these days a lot of mails have coming in with super random data obviusly is one person doing it, I dont know if it is just a person doing it by hand or using bots

how can i prevent this ??

i've sanving the ip from the sender but it is almost always different


r/PHPhelp • • Nov 22 '23

Why are global functions bad?

7 Upvotes

Hi,

I've noticed that Symfony, Laravel, and other frameworks seem to avoid global functions. Sure, they still use them...but very rarely.

To me, the following looks like a good and logical function that could be shared across different classes:

<?php

declare(strict_types=1);

namespace FooVendor\FooPackage;

if (! function_exists(__NAMESPACE__ . '\\isStringable') {
    function isStringable($value): bool
    {
        return (
            is_scalar($value)
            || (is_object($value) && method_exists($value, '__toString'))
        );
    }
}

The above example isn't using any global variables or polluting other namespaces. So, why do frameworks avoid mixing OOP with functional programming?


r/PHPhelp • • Jun 11 '23

STRIPE API Checkout and Invoice

7 Upvotes

SOLVED

Hi everyone

I have a problem with Stripe and PHP. I have created custom fields to ask customers for their "SIRET" and "address" during the checkout process. They are displayed during the checkout, but how can I add them to the invoice generated by Stripe? Best regards!"

Ps : I already have this information on my web app, i don't really need for customer to enter it again at the CheckOutBox.

Big Thanks.


r/PHPhelp • • May 23 '23

Does setlocale() affect POST or REQUEST data?

7 Upvotes

My understanding was that it controlled the generation of locale specific content e.g., date formats, etc.

It was suggested to me that the problem I'm seeing related to utf-8 request data decoding COULD be related to locale, i.e., that locale can affect how utf-8 is decoded into codepoints.

Is this possible?

On a bit of a tangent: On php7.4 (+ Apache 2.4), I'm seeing something odd:

The default 'LANG' in envvars is 'C'. This is reflected in the return of setlocale(LC_CTYPE,0);

When I change it to "en_US.UTF-8", restart apache and php-fpm, a call to setlocale(LC_CTYPE,0) will reflect the change. BUT..., at some point, on successive requests, the setlocale() call will flip back to returning 'C'. It ain't me doing it..., and it doesn't appear to be any of the modules I'm using either.

FWIW..., threads are not enabled.


r/PHPhelp • • May 07 '23

I wanted to ask should a model be allowed to return a collection querying another table?

7 Upvotes

I wanted to ask should a model be allowed to return a collection querying another table?

Example. (Typing from phone not sure how to insert code snippet)

I have a user model with a user_type column. Then I want to retrieve a list of the contents of another model based on the user_type column. So if user_type is type_a query the other model's table to give a list with type_a permission else go with the type_b permission list.

Where should I put this logic? On the other model as a scope that asks for a user then checks the user's user_type there or in the user model since I want that list in the 1st place for that specific user anyway?


r/PHPhelp • • Apr 07 '23

Solved Can you point me to which topics should I study to handle api with JSON

7 Upvotes

r/PHPhelp • • Mar 29 '23

Datetime "last month" or "-1 month" do not always give a date within the previous month

7 Upvotes

Hello all

We are nearing the end of the month and today we got a nice date related surprise as we had before : a test fails today where it did pass yesterday.

If you use today the expression "last month", "previous month" or even "-1 month" with Datetime, it gives a date on the 1st March, not in February. This is the same with Carbon's subMonth() method.

If I use "-2 month" it does gives me a date on the 29th January.

To get a date in the previous month, we have to write for instance "first/last day of last month".

I do imagine this is not a bug in PHP, but what is the logic behind that ?

I felt that the page about the relative datetime formats (https://www.php.net/manual/en/datetime.formats.relative.php) do not help.

---

Actually as I write this, the logic I think is that the system just change the month, which gives a date of 2023-02-29, which is a day that doesn't exists, so it correct to the next equivalent proper date.

It also means that such behavior happens basically every 31th ...

This is a very un-intuitive behavior !


r/PHPhelp • • Mar 17 '23

How should I consume my own API?

7 Upvotes

Hello everybody,

sorry if it's a dumb question. Let's say I have a BookMapper class that gets all the books from a database and let's also say that I have to expose this data as well on a HTTP REST API that "prepares" the data for other developers. (for eg. React)

If I want to get Books data myself via PHP, is it considered a good practice to consume my own API or should I use "again" the BookMapper?

If it's a good practice, should I do a CURL request to my own server or create a static method like:

$Books = API::callMyOwnAPI('api/Books/', $parameters);

? How should I use all the objects (Database, BooksMapper etc...) inside this static method?

Thank you


r/PHPhelp • • Mar 12 '23

Solved What the namespace is going on!?

7 Upvotes

Hi, I made a router as a learning exercise and noticed there is something I don't really understand. namespaces!

Currently in my router project, I don't use them and everything works fine. But if I add them, then the classes error when trying to instantiate them.

Here is my router project with the namespaces and use keywords commented out. This is what I thought I needed to run for things to be correctly namespaced.

https://github.com/enfrte/Forbidden-PHP-Router

Could someone take a quick look and tell me what the problem could be? Entry point is index.php

Thanks.


r/PHPhelp • • Feb 27 '23

Display CPT UI content in elementor

7 Upvotes

Hello,

Is it possible to display custom post types in a elementor page section ? I think you can with a shortcode by adding the code in a function but I need some help with that. Can you give me an example that works or a tutorial.

Thank you for your help.


r/PHPhelp • • Feb 19 '23

log in page encryption.. shouldn't that be done client side?

7 Upvotes

I'm following a tutorial on making a log in system with php.

when adding all the users information into the database (mysql), I noticed it's only right before the data is put into the table does the password get encrypted.. so to my understanding the data was sent via plain text (ish, was using post method at the very least) to my server.. shouldn't the encryption be done at the client side? or does post + https take care of that?

I suppose this isn't really a php question... sorry.


r/PHPhelp • • Jan 30 '23

Solved Returning ordered results using Prepared SQL statements

7 Upvotes

I'm trying to sort a table by re-populating it with the same results ordered by whichever column the user clicks on, can anyone explain why this works:

$colVal = $_POST['colVal'];

$direction = $_POST['direction']; $sortField = ['p.lastName','p.firstName', 'p.email', 'd.name', 'l.name'];

$stmnt = 'SELECT p.lastName, p.firstName, p.jobTitle, p.email, p.id, d.name as department, l.name as location FROM personnel p LEFT JOIN department d ON (d.id = p.departmentID) LEFT JOIN location l ON (l.id = d.locationID) ORDER BY ' . $sortField[$colVal] . ' '.$direction;

But this only ever returns the results ordered by p.id?

$query = $conn->prepare("SELECT p.lastName, p.firstName, p.jobTitle, p.email, p.id, d.name as department, l.name as location FROM personnel p JOIN department d ON (d.id = p.departmentID) LEFT JOIN location l ON (l.id = d.locationID) ORDER BY ?, ?");

$query->bind_param("ss", $sortField[$colVal], $direction); $query->execute();

$result = $query->get_result();


r/PHPhelp • • Jan 20 '23

Any performance difference from upgrading from PHP 7.4 to PHP 8.2

7 Upvotes

Hi all, currently I have PHP 7.4.33 installed on my VPS server, and the server itself are very slow but had 1GB of RAM,

I'm kinda worried about the performance of my WP website on it, so I need performance improvement if possible on it.


r/PHPhelp • • Oct 28 '22

Best way to create a pdfs (Recommend a library)

7 Upvotes

I need to create pdfs using existing documents I have . I want to place values from the database fields in my pdf documents. Can you tell me the easiest, best library to do this with.


r/PHPhelp • • Oct 23 '22

Solved Reading an XML file in a PHP file

7 Upvotes

Hi, I'm very new to this and I'm looking for some help on displaying my XML data in a php file.

echo "<p> Cost of Rental per day: " .$product->rentalCost.          "</p>";
echo "<p> Lenght of Rental: " .$product->lenghtOfRental. "</p>";
echo "<p> Search Tags: " .$product->searchTags. "</p>";
echo "<p> Product Condition: " .$product->productCondition. "</p>";
echo "<p> Operation of product: " .$product->operation. "</p>"; 

Im using these statement to handle the child elements of my XML file which is working great, but I need to access a child of a child element(?) so I need to print everything inside the 'extras' element.

<products>
    <product code="Simpsons">
            <name></name>
            <description></description>
            <rentalCost></rentalCost>
            <lenghtOfRental></lenghtOfRental>
            <searchTags></searchTags>
            <parentalRating></parentalRating>
            <productCondition></productCondition>
            <operation></operation>
            <extras>
                <nameManufacturer />
                <additionalCost></additionalCost>
                <lateFees></lateFees>
            </extras>
            <reviews></reviews>
            <picFile></picFile>
            <relatedURL></relatedURL>
    </product>

Any help is greatly appreciated.


r/PHPhelp • • Oct 02 '22

Am I understanding DIP/IOC/DI correctly? Thanks

7 Upvotes

Using horribly simplified pseudo-code, is this the different between traditional control and inverted control?

Edit: Is this also an example of "composition over inheritance"? Thanks

Traditional Control

class HighLayer
{
    $mid = new MidLayer();
}

class MidLayer
{
    // The MidLayer decides which LowLayer to use
    $low = new LowLayer();
    $low->doSomething();
}

class LowLayer
{
    // Do something method
}

Inverted Control

class HighLayer
{
    // The HighLayer decides which LowLayer the MidLayer should use
    $mid = new MidLayer(new LowLayer1());
}

class MidLayer
{
    construct(LowInterface $low){$this.low = $low;}
    $this.low->doSomething();
}

interface LowLayer
{
    // Do something abstract method
}

class LowLayer1 implements LowInterface
{
    // Do something method
}

class LowLayer2 implements LowInterface
{
    // Do something method
}

Thanks!


r/PHPhelp • • Sep 18 '22

I'm struggling to understand SQL injection and how to protect against it.

7 Upvotes

I understand that all user input should not be trusted and it is recommended to use parameterized queries to defend against sql injection. But should parameterized queries be used if there is no user input such as in a drop down form?

For example:

HTML

<form class="hotel" action="#" method="get"> 
<label for="location" class="city-label">Location:</label> 
<select class="filters" name="location" id="location"> 
<option value="London">London</option> 
<option value="Paris">Paris</option> 
<option value="Berlin">Berlin</option> 
<option value="New York">New York</option> 
</select> 
<input type="submit" value="Filter" class="filter"> 
</form>

PHP

switch($location) {     
case $location == "London":       
$queryselect = "SELECT * FROM accommodation WHERE location = 'London' ORDER BY name";       break;     
case $location == "Paris":       
$queryselect = "SELECT * FROM accommodation WHERE location = 'Paris' ORDER BY name";       break;    
case $location == "Berlin":       
$queryselect = "SELECT * FROM accommodation WHERE location = 'Berlin' ORDER BY name";       break;

Can someone ELI5 if/how this would be vulnerable to SQL injection as this is different to the sql injection examples that i have seen.