r/PHPhelp • • Jan 16 '22

Need help with basic php unit testing

9 Upvotes

Hi all,

Let's start of with the fact that I have very minimal experience in backend (PHP) development but I do enjoy learing about back-end as a front-end developer :). So I am currently at the stage where I want to learn some testing with php unit tests.

The problem Im having with this is that I do not know what exactly I should test inside my project.

I currently have a login, which includes the register part of the user. inside my class User, I created my public function as such:

<?php

public function register($data) {

$this->db->query('INSERT INTO users (username, email, account, password) VALUES(:username, :email, :account, :password)');

//Bind values

$this->db->bind(':username', $data['username']);

$this->db->bind(':email', $data['email']);

$this->db->bind(':account', $data['account']);

$this->db->bind(':password', $data['password']);

//Execute function

if ($this->db->execute()) {

return true;

} else {

return false;

}

}

?>

What should I test with php unit test and how should I go about this? Like does someone have an example of how to best test the functionality? I just want to do basic testing but id like to do it the right way.

Hope I explained it well.

Thanks for reading all :)


r/PHPhelp • • Nov 07 '21

We are students, a few incorrect MySQL settings broke our whole website and database, now we are locked out, any way to fix? Please help save our project.

9 Upvotes

Edit: We are back up and running. Thank you all so very much for your help! We would not have figured it out without you!

XAMPP WordPress website goes down after working fine for over a week, cannot log into myPhpAdmin because MAX_CONNECTIONS_PER_HOUR exceeded, wait hours, not fixed, wait a day, not fixed.

Try every method under the sun to somehow log into MySQL to change the setting (which was also blocking us because MAX_CONNECTIONS_PER_HOUR), somehow get in, even though phpMyAdmin is still blocking us for the same reason (we were able to use both simultaneously before).

We try to change settings after doing our reasearch, try a few different methods, some of them work but do not actually change the MAX_CONNECTIONS_PER_HOUR per hour setting because it says "Query OK, 0 lines affected" (which I assume means we changed nothing). We must be in the same database, because it is the only one we have, and has a unique username and password.

After a few attempts of trying to change the settings we get blocked again, this time for exceeding MAX_QUERIES_PER_HOUR, this made it so we could SORT OF log into myPhpAdmin, but it is totally screwed up, just shows an "Exceeded MAX_QUERIES_PER_HOUR" error and you can no longer see the database.

We try to FLUSH USER_RESOURCES (or FLUSH_USER_RESOURCES) but cannot do that because it is treated like a query, providing the same error. Again we wait hours, then a day, and now the MySQL/phpMyAdmin is stuck on the MAX_QUERIES_PER_HOUR error. You would think after an hour we could resume work, but no, no amount of time is fixing these errors.

Our website and database was not backed up yet, we do not have snapshot because this is for a college class (this is pretty much our whole grade and is due in 4 days). We were supposed to start backing things up right when this happened, of course.

It seems if we could somehow flush the controls like such as:

MAX_CONNECTIONS_PER_HOUR

MAX_QUERIES_PER_HOUR

MAX_UPDATES_PER_HOUR

MAX_USER_CONNECTIONS

Time is not doing it like it should, is there a manual way to do it? If we can restore our access, we could then change those settings to all = 0 so that there is no more limits, and then we would be good to go, but we cannot restore access, we cannot change those settings.

Does anyone know of any way we can restore access? Is there some file somewhere with these settings that we can change and then restart everything? How do we do that? Is there any trick that will get us back into operational status? We spent a lot of time on this. Please help save me and my groupmates grades and website/database.

What are we missing! Google has been no help.


r/PHPhelp • • Oct 26 '21

My PHP code has a race condition - is this even possible?

9 Upvotes

Was debugging an error all morning, when I echo'd things out I found I have a race condition. I did not believe this was possible in php. it was solved by adding a sleep(5). Here is code snip:

if($t >= 9*60+39) {
      if($this->getPosition() !== 0) {
          $this->output("time is up, closing");
          $this->cancelOpenOrders();
          sleep(5);   // not originally here, added to solve race cond
          $this->flatten();
      }
    }

So, what is happening here is that the program is trying to flatten my position, but it can't if there are open orders, so it has to cancel any open orders first. When it doesn't do that, I get the error

{
  "error" : "This order may result in an oversold/overbought position in your account.  Please check your position quantity and/or open orders."
}

This is because you can't buy to cover when you already have a stop loss order in place. I actually think they should just kill the stop loss and accept the new order, but that's not how it works.

When I echo'd it out, it goes like this

2021-10-26 10:16:00: time is up, closing
going to child orders
Skipping child
2021-10-26 10:16:00: 0 orders cancelled
2021-10-26 10:16:00: Flattening position - buying 100
going to child orders
Skipping child
{
  "error" : "This order may result in an oversold/overbought position in your account.  Please check your position quantity and/or open orders."
}
there was an error

So you can see that the flatten function runs WHILE the cancel function is still looping through the orders trying to cancel them one by one. This should not be possible. Putting in the sleep function solved it.

The code is using CURL to send and receive requests, but even still, this should not matter. PHP should run sequentially. Was there an update or something I don't know about? Here is my composesr require:

      "slim/slim": "^3.12",
      "illuminate/database": "^5.8",
      "robmorgan/phinx": "^0.10.6",
      "symfony/console": "^4.2",
      "illuminate/events": "^5.8",
      "phpmailer/phpmailer": "^6.0",
      "league/flysystem": "^1.0",
      "symfony/var-dumper": "^4.2",
      "monolog/monolog": "^1.24",
      "jenssegers/blade": "^1.1",
      "illuminate/pagination": "^5.8",
      "symfony/dotenv": "^4.2",
      "symfony/polyfill-php80": "1.19",
      "mongodb/mongodb": "^1.8",
      "amphp/websocket-client": "^1.0",
      "caymanbrothers/stockshare-sdk": "^1.0",
      "mnshankar/linear-regression": "^1.0"

Most of those arent being used for this script. Really only Slim, console, and dotenv should be getting used for this. Is it possible that including amphp is doing this? Or is there something else I am missing?


r/PHPhelp • • Oct 16 '21

Solved when you would u use a static function?

9 Upvotes

im coming from python and very new to php

consider this:

    class normalUser
    {
        const rank = NORMAL;
        private $rank = NORMAL;

        static function static_function()
        {
            return self::rank;
        }

        function just_function()
        {
            return $this->rank;
        }
    }

this is my understanding:

	$new_user = new normalUser;
	echo $new_user->just_function();		#call class method in object context
	echo normalUser::static_function();		#without initializing an object of class

this is weird. i guess static methods can be used to grab a class's constant property without instantiating the class or something? i guess a slight performance optimization?

static methods can only access its class's constant properties so if thats not what the implemented static method does that means the method has nothing to do with the class really, in which case i would be better off writing a function that does the same thing outside the class scope?

what r sum practical examples where this kind of weird technique is used?


r/PHPhelp • • Aug 25 '21

How do I find out what I don't know?

9 Upvotes

All of my php knowledge has been self taught over the years and I've just kind of stumbled upon information randomly and other times I learn out of some specific need, which leads me to outdated SO answers that I tweak to fit my needs to what I believe to be more updated and better code.

However...

I've noticed over the past few months here that there's random things I either didn't know I didn't know, or I have learned to be outdated and should be burned with fire. Example 1, I have no idea what this variable leading with a period $.var thing is. Example 2, apparently setting a variable conditionally is a no-no? $a = ( $b > $c ) ? $x : $y;

Where do I go to find my I unknown unknowns?


r/PHPhelp • • May 20 '21

Learn PHP

9 Upvotes

I want to learn advanced PHP, give some suggestions about books, topics, and other necessary things...


r/PHPhelp • • Apr 28 '21

Is there a way to test a function with static variables? (PHPUnit)

9 Upvotes

Ιs there a way to test a function containing static variables using PHPUnit?

For example,

class MyClass {
  public function my_method() {
    static $already_invoked = false;
    
    if ($already_invoked) {
      return;
    }

    echo 'Hello world';

    $already_invoked = true;
  }
}

my_method() will print Hello world exactly one time, no matter how many times it's called.

$instance = new MyClass();
$instance->my_method();
$instance->my_method();

outputs:

Hello world

Having just one test

<?php
class MyMethodTest extends \PHPUnit\Framework\TestCase {
    public function test_should_print_hello_world_exactly_one_time() {
        $instance = new MyClass();
        $instance->my_method();
        $instance->my_method();

        $this->expectOutputString('Hello world');
    }
}

passes:

MyMethod
 ✔ Should print hello world exactly one time

However, adding another test

<?php
class MyMethodTest extends \PHPUnit\Framework\TestCase {
    public function test_should_print_hello_world() {
        (new MyClass())->my_method();

        $this->expectOutputString('Hello world');
    }

    public function test_should_print_hello_world_exactly_one_time() {
        $instance = new MyClass();
        $instance->my_method();
        $instance->my_method();

        $this->expectOutputString('Hello world');
    }
}

causes the previously passing test to fail, because of the static variable:

MyMethod
 ✔ Should print hello world
 ✘ Should print hello world exactly one time
   │
   │ Failed asserting that two strings are equal.
   │ --- Expected
   │ +++ Actual
   │ @@ @@
   │ -'Hello world'
   │ +''
   │

Now, I know I could use a static property instead:

class MyClass {
    private static bool $already_invoked = false;

    public function my_method() {
        if (self::$already_invoked) {
            return;
        }

        echo 'Hello world';

        self::$already_invoked = true;
    }
}

That way, I could use a reflection property to reset its value immediately after each test, like this:

class MyMethodTest extends \PHPUnit\Framework\TestCase {
    // ...

    public function tearDown() {
        $ref = new ReflectionProperty('MyClass', 'already_invoked');
        $ref->setAccessible(true);
        $ref->setValue(null, false);
    }
}

And then, both tests pass:

MyMethod
 ✔ Should print hello world
 ✔ Should print hello world exactly one time

In my case, though, I'm dealing with legacy code and I'd like to write some unit tests before refactoring it.

I've also tried to run each test in isolation (although that's not ideal since it'd probably end up being considerably slower) using the @runInSeparateProcess method annotation, but that seems to be failing because the process isolation feature requires serialization:

PHP Fatal error:  Uncaught Exception: Serialization of 'ReflectionClass' is not allowed in phar:///usr/local/bin/phpunit/phpunit/Util/GlobalState.php:151

Is there a way to test a function containing static variables?


r/PHPhelp • • Feb 11 '21

Can someone code review my PHP project?

9 Upvotes

Introduction

I've been lucky enough to get my first job as a junior PHP developer. I am concerned I'm not good enough because I am only 16. I would like to brush up on my coding and get as much constructive criticism as I can.

What is it?

This is a SQL query builder, built for MySQL that provides a fluent, chaining API to build a query, and allows you to output the raw SQL. How can I improve the quality of it, as well as any features you can think of that I can try to practice.

API:

https://gist.github.com/WholePatient9125/bb51995a4e9d7fef8fab9184f663698b

Gist class (QueryBuilder): https://gist.github.com/WholePatient9125/cd8b275882836d49e30e1df55ffdebb7

Many, many thanks in advance to everyone who helps.

I know the support for multiple where clauses is weak, and maybe I forgot to add some options and be more flexible, but this was to the best of my basic SQL knowledge, I'm open to challenges.


r/PHPhelp • • Jan 18 '21

what kind of projects are better with php than with other web programming languages?

9 Upvotes

r/PHPhelp • • Dec 08 '20

Solved Which coding conventions do you follow, if any?

9 Upvotes

I recently had a debate with a colleague about coding conventions in PHP code. My PHP skills are rusty and I really don't know the best practices. Do you work in an organization that has multiple people maintaining a PHP code base? If so, I'd be grateful for insights.

  • Do you follow a coding convention? If yes, which one? Is https://www.php-fig.org/psr/psr-12/ a thing?

  • Do you specify things like indentation style? To which extent?

  • Do you allow curly braces, "alternative" control structures or both?

  • Is it OK in your organization to use many different coding styles? If yes, how do you decide which file uses which style? Can styles be mixed in a single file?

  • Do you use an automatic formatting tool? Which one?

I'm trying to find out a general sentiment. Do you see coding standards as a hindrance to work or as a way to help the team to work? Is there a point after which a standard is too strict?

Thanks in advance.


r/PHPhelp • • Nov 26 '20

Good resource for learning best practices on architecture/scalability?

9 Upvotes

My PHP skills have gotten really good over the past couple years (IMO), but I sometimes find myself building methods and classes that don't scale as well as I'd like, though I'm getting better at it.

I've usually don't have a dev above me to teach me best practices, and I'm guessing there's a good resource for learning.

Anyone recommend something that would help?


r/PHPhelp • • Oct 09 '20

Getting extremely frustrated with debugging situation

9 Upvotes

I keep having to post questions here because I keep getting stuck on my homework. The way our professor wants us to do our work, we're supposed to write our HTML + PHP in Notepad++, upload it to the class server, test it, re-write it, re-upload it, test it again, and so on, until it works. The problem is that there's no error messages more helpful than HTTP error 500, even with the error reporting code y'all gave me the other day. I still only get HTTP error 500 messages. Is there some other IDE that I can use that will spot syntax issues and other stuff before I upload it? I'm really sick of getting stuck and having to ask for help. Thanks.

PS. I know I sound upset, but I'm not mad at you guys, I'm mad at the situation.


r/PHPhelp • • Sep 08 '20

How can I get this string replace to work on a copied and pasted apostrophe?

9 Upvotes

Hello-

I am trying to replace this, in a string: ’

$quote = str_replace("’", "'", $row["quote"]);

The above is what I tried but it does not work. My initial problem is that I copied and pasted quotes from Google Docs in my database. When these quotes are displayed on page, the apostrophe is displayed as a black triangle with a question mark, showing that the character in question cannot be interpreted right. I tried doing a replace in the database table, but that does not work, so now I am trying to replace the apostrophe before the browser attempts to display it. Thus this function above.

SOLUTION:

//detect encoding coming from DB

$enc = mb_detect_encoding($row["quote"]);

// change encoding to UTF-8

$quote = iconv($enc, "UTF-8", $row["quote"]);


r/PHPhelp • • Jul 02 '20

Is there a better way to do things than index.php?id=99?

9 Upvotes

I’ve got a large group of categories, each of which links to a page with a GET statement like ?id=99. Is there a better way to do this? Does it open your site up to injection attacks?


r/PHPhelp • • Jun 15 '20

Careers Question: Has anyone switched from .NET to PHP and then back to .NET?

9 Upvotes

If this question doesn't belong here, please let me know and I'll remove it.

I'm in a bit of a minor crossroads moment in my professional career. I started out as a .NET developer for 2.5 years and then fell into a PHP/.NET position at my current job (2 years and counting). I'm looking to switch jobs soon and I've always assumed that I would switch back to .NET, until I saw a job position (tentative current opening) in PHP that's making me second guess.

I'm in the middle of a "do I stay in programming or switch careers all together" moment, but I'm not ready to throw in the towel yet. I wanted to ask if anyone has had the switch like in the title OR has switched long-term to PHP? If the latter, what's the industry been like for you? How has it changed in the last several years (or in the duration you were a PHP dev)? How's the job growth in this part of the market? I know what to expect with .NET but I'm clueless about PHP.

PHP hasn't been terrible to work in and I've always been interested in venturing out of closed systems like .NET, but I'm not sure that my experience is colored by my current job (it's pretty bad) or if it will continue to in the next PHP job. Hell, I'm not even sure if my PHP experience is even good enough for another PHP job.

Edit: Located in East Coast, USA.


r/PHPhelp • • May 26 '20

Is there any website like CodePen but for PHP?

9 Upvotes

Hi

I really like CodePen but I can't write in PHP in it. Is there any website similar to it but allows PHP?

Thanks


r/PHPhelp • • May 19 '20

Here is a tutorial to get your started using PHP in the cloud with Digital Ocean or AWS.

9 Upvotes

I know a lot of developers are still using traditional hosting (shared hosting, dedicated, etc..) But there are some real good offerings from Digital Ocean and AWS to take you application to the cloud using tools like droplets or EC2. Here a small tutorial I typed up to get you stared developing PHP in cloud. https://phpnibbles.com/how-to-configure-your-digital-ocean-droplet-or-aws-ec2-instance-for-php-development/


r/PHPhelp • • May 16 '20

I created a tutorial php blog to help new php developers.

9 Upvotes

Let me know if there is anything you would like me to cover. https://phpnibbles.com/

Its pretty new so I only have two posts but will be doing more and more tutorials and explainer posts. I am going to cover things like setting up a proper dev environment for php in cloud using services like aws and digitalocean.


r/PHPhelp • • Apr 08 '20

I would like to make a simple chat system. Right now I have done it with PHP, MySQL and Ajax. But I don't want the chatbox to keep refreshing every second. I want it to refresh only if I sent a message or the other person has sent a message.

9 Upvotes

I have spent a decent amount of time on creating my own online platform and it's all based on PHP and MySQL. I want to integrate a chat system, so it also works with the same user Id's and Sessions as the rest of my site.

I have found socket.io but you need Node installed for it. I have little knowledge about Node. Is it installed on most webhosting servers? Can I just use a combination of socket, node and php? Is that a viable way to make a chat system? I have pretty much written all the chat logic already in PHP and Ajax. Users can send messages to other users. It's just the Ajax refreshing loop that is the problem. I don't want the chatbox to refresh every second and get the data from the database every second, because it's not good for the bandwidth.


r/PHPhelp • • Dec 19 '19

preg_replace with German umlaut

9 Upvotes

Hi, I'm looking for a preg_replace which adds a "+" in front of every word, otherwise my full text search query which I'm getting via a get request does not work.

This is what I have so far:

$products->term = isset($_GET['term']) ? preg_replace('/(\w+)/', '+$1', $_GET['term']) : die();

This works. "keyword1 keyword2" is converted to

+keyword1+keyword2

The problem is that it does not work with German umlaut like ä, ö, ü. So " keywörd1 keyörd2" gives me

+keywö+rd1 +keyö+rd2

as result.

Is there a way to fix this?

Thanks


r/PHPhelp • • Nov 25 '19

Best way to pass JWT token from backend to frontend?

9 Upvotes

Okay so I'm writing a web application (Symfony for backend, some JS framework for frontend, probably Angular). I use JWT tokens for authentication.

When it comes to normal username + password login, it's simple - frontend makes a request with username and password, backend returns token, frontend receives token. This is simple.

But the thing is, I want to allow users to log in using Google or Facebook. I have my backend all set up, but I'm not sure how should I pass the token to frontend.

Because now it's like this:

  1. user clicks a button on frontend

  2. user is redirected to some backend url, which in turn redirects him to a proper Google login url

  3. user logs in and allows my app to use his Google account

  4. user gets redirected by Google to backend url

  5. backend authenticates the user and generates JWT token

And now what's the usual way of passing this token back to frontend? The only thing that comes to my mind is redirecting the user back to frontend with token as query param, like http://example.com/?token=... but this seems insecure.


r/PHPhelp • • Oct 13 '19

INSERT INTO sql table not working.

9 Upvotes

Am I inserting rows into my table correctly? This doesn't work for some reason.

$conn->exec("INSERT INTO Questions_Table (ID, Question, Votes) VALUES ($num_rows, $submitted_question, 1)");

r/PHPhelp • • Feb 14 '19

Should I delete temporary files myself or leave it to the OS?

9 Upvotes

In my web apps, I often create temporary files via

$tmp = tempnam(sys_get_temp_dir(), '');

Is the program expected to clean up after itself when it comes to temporary folders? I'm sure it's different between OSes, so I'll point out my stuff mostly runs on Linux servers.


r/PHPhelp • • Feb 13 '19

PHP router works on a local machine but not on a Linux Server.

9 Upvotes

I finished a simple no framework php 7+ website.

It uses a MVC structure and has a router to handle GET, POST, URL change requests.

On the local machine everything works perfectly.

However on the server it looks like the server is blocking the router.

The initial view loads but on url change or post request the following is returned:

Not Found

The requested URL /url was not found on this server.

*Sorry if this is more of a server question. Figured i'd ask here first as i'm sure other's with custom php routers have had this issue before

Fedora 29

Edit:

apache

My file structure is roughly

index.php

-core

--router

-pages

--page1

--page2

--page3

I think the issue is Apache is only able to serve pages in the top level of the var/www/html folder. Best way to fix?