r/PHPhelp • • Dec 27 '19

Improve PHP skills

8 Upvotes

Hello, I started learning programming two years ago with Java and last year I accidentally got offered a PHP job by a friend - help him with 2 projects, one made with Symfony 3.4 and the other one was some old custom framework (legacy code). So briefly I jumped from Java to Symfony Framework directly and found myself a Junior Web Developer job this October with PHP and Symfony mostly. However, my experience with plain PHP is not really good - I struggled when I had to work on a project from 2014 a few weeks ago. What would you recommend me to improve my PHP skills in general? I feel really comfortable with Symfony but when it comes to reinventing the wheel, I struggle.


r/PHPhelp • • Dec 17 '19

35,000 Records, num_rows() is slow at counting rows?

8 Upvotes

Hello

Im looking to count all results in the database using num_rows() for my pagination. However its causing the page to hang for half a second or two.

Is there a better way to do this?

I've tried "SELECT `topic_id` AS of "SELECT *" but this has very little benefit. I was tempted to store the value in database of the total topics BUT this would not work when the user searches for topics later on.

Solved by: mikedelfino - Adding Indexes to columns speeds it up.


r/PHPhelp • • Nov 26 '19

Should I learn design patterns?

8 Upvotes

I've been learning/using php with frameworks like codeigniter, and wordpress, else just procedurally. I understand the syntax of OOP; classes, properties, access modifiers, and inheritance, but not really the any OOP design patterns (unless inheritance is counted).

Last week I got an interview for a trainee-ship and had to write a small amount of php (specifically) without a framework. First was to create a form that allows users to register their email address in MySQL. The other was to read an RSS feed and prepare JSON data to be fetched by JS on the front-end.

I kind of feel I needed to do this in OOP, but wasn't really sure if I needed to use a certain design pattern. I ended up just doing it procedurally, but was wondering how the professionals would have implemented this.

So if you had this assignment, how would you have implemented it? The procedural way, simple OOP - like a class and an instance, or OOP with some design pattern?

Is it a really bad thing that I don't have a grasp of basic design patterns yet?

Thanks.


r/PHPhelp • • Oct 29 '19

does any one have a link for creating an login system using php sql at a beginners level? I know html - css , basic database handlng in MySQL, basic php ...variables arrays etc ; and also c++ knowledge on if statements,logic etc.

8 Upvotes

r/PHPhelp • • Oct 14 '19

Are there password hashing incompatibilities between PHP 7.2 and MySQL 5.7

8 Upvotes

OK, hear me out. I thought I knew what I was doing with all this COMPUTER stuff, but what the heck is going on here?

The Setup:

  • One application server, Ubuntu 18.04 LTS (PHP 7.2, mysql-client)

  • One database server, Ubuntu 18.04 LTS (mysql-server 5.7)

I need to connect to the database from a PHP application running on the application server. Everything's set up. Notably, both PHP and MySQL are installed from the stock packages available in Ubuntu current LTS, which means they are PHP 7.2, and MySQL5.7

For the sake of example, let's say that the IP address of the application server is 20.20.20.20, and the database server is 40.40.40.40

Here's what happens:

  • SSH into application server

  • issue mysql -u argonflowers -p -h 40.40.40.40

  • am prompted for password, enter it

  • am presented with a mysql prompt. I've successfully accessed the remote database. I can query everything I need to in the databse, it's confirmed working, etc. I kill this SSH session.

But:

  • SSH into application server

  • run a PHP script that I will copy below for the sake of keeping this list organized, run with command php -f db-test.php

  • returns with error: PHP Warning: mysqli_connect(): (HY000/1045): Access denied for user 'argonflowers'@'20.20.20.20' (using password: YES) in /home/argonflowers/db-test.php on line 10

  • K. What the heck. I can figure this out. Let's look at the MySQL server logs. They read:

2019-10-14T02:17:42.923737Z	   27 Connect	[email protected] on  using SSL/TLS
2019-10-14T02:17:42.924714Z	   27 Query	select @@version_comment limit 1
2019-10-14T02:17:44.503559Z	   27 Quit	
2019-10-14T02:17:51.359508Z	   28 Connect	[email protected] on  using TCP/IP
2019-10-14T02:17:51.359681Z	   28 Connect	Access denied for user 'argonflowers'@'20.20.20.20' (using password: YES)

What? This doesn't make any sense to me. This seems like a "you are sending me the wrong password" error, but the PHP script contains the same password as I enter when prompted by mysql-client. Yes, SSL is enabled, but it's not being enforced for all incoming connections. I've dug around a lot to find out if there are any known gotcha's in how password hashing happens between PHP 7.2 and MySQL 5.7, but there seemingly aren't. Also, these are the packages that are default to this distro, so I'm extra surprised it's this much of a struggle. Please tell me I'm a fool and I've missed something obvious! No, that's not the current password (all of this data is fake).

Here's the PHP script:

<?php
# Fill our vars and run on cli
# $ php -f db-connect-test.php

$dbname = 'inventory';
$dbuser = 'argonflowers';
$dbpass = 'otkgjazmcutrls';
$dbhost = "40.40.40.40";

$link = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
mysqli_select_db($link, $dbname) or die("Could not open the db '$dbname'");

$test_query = "SHOW TABLES FROM $dbname";
$result = mysqli_query($link, $test_query);

$tblCnt = 0;
while($tbl = mysqli_fetch_array($result)) {
  $tblCnt++;
  #echo $tbl[0]."<br />\n";
}

if (!$tblCnt) {
  echo "There are no tables<br />\n";
} else {
  echo "There are $tblCnt tables<br />\n";
} 
?>

EDIT: The saga has ended! A friend and I finally identified that what was happening was that mysql-server was enforcing SSL connections even though we explicitly told it not to do that. We tested this by attempting to connect from the command line on the application server with mysql -u argonflowers -p -h 40.40.40.40 --ssl-mode=disabled, and seeing that it failed.

For us, the solution was disabling SSL, which is viable for us because these servers are connecting over a private network with no other resources on it. For others, the solution may look like this.


r/PHPhelp • • Sep 23 '19

How do you prevent XSS and Code Injection using PHP?

8 Upvotes

r/PHPhelp • • Jun 17 '19

Development in PHP without a framework / Mixing procedural and OO design in PHP

8 Upvotes

So as a fairly new person to web design using PHP, and still fairly new to it in general, I've decided to get my hands dirty and begin without any framework to really get a comprehensive understanding of what's really going on. The only other times I've dove into web development was in the Spark Framework for Java 8, where everything was pretty heavily abstracted. Its been a bit of a slog, but I feel like I'm slowly starting to understand the gist of things, and once I wrote a router everything began to flow a lot better.

So with my newness established, my real question is, the deeper I get into this, the more I feel like I'm going to have to essentially write an entire framework to properly adhere to Object Oriented Principles. It really seems inefficient (or at very least time consuming) to try to match web dev to pure OO, and I'm really tempted to leave a few choice areas practically procedural to make the entire project flow better. Its become a real nightmare particularly as I get further into separating my php from my html, ob_start() and ob_get_clean() have been the workhorses here, but I find them really clumsy to use.

Now I know I could just give up and switch to simply using a framework and a template engine, but I've found this whole process really educational, and I'd like to see it to the end. I've found it difficult to find resources and info to improve my design, most questions I search end up referring to using a framework. I'd really appreciate any thoughts and advice going forward!


r/PHPhelp • • Feb 09 '19

Nesting “if” statements to do validation checks - is there a better way?

8 Upvotes

I am doing validation checks on a file that is getting uploaded to my server, and I would like the error that it spits out to be verbose, keeping me from using a generic catch-all. Is there any practical way of doing this other than nested “if” statements?

For example: checking the name, the file type, file size, and if the upload itself was successful.


r/PHPhelp • • Feb 09 '19

Does 'session_start();' cascade into other php files or do I have to declare it every time?

8 Upvotes

I am working on a project with no framework. Bare bones php 7.

Using sessions quite a bit.

Do I have to 'session_start();' at the top of every PHP page I want to use sessions in, or can I just declare it once at top of the index or controller file and the 'session_start(); will cascade into other files.


r/PHPhelp • • Dec 16 '18

Password security with PHP and MySQL

8 Upvotes

I have an employee portal for my company's web site. I'm curious if the following is adequate password security considering the site does not contain any confidential information beyond the work schedule. Also, if someone were to gain access to the site they would not have access to any internal business system as the portal resides on a completely different and unrelated server.

When an employee record is completed, or a password updated, I use the crypt function to hash the password. For the 'salt' I generate a random string of 5-10 alpha numeric characters (length is randomly selected) . After hashing the password the salt is stored in the database along with the hashed password.

When the employee logs in the system grabs the salt which matches their username, and uses it to hash the entered password before matching it to the stored password.


r/PHPhelp • • Nov 10 '18

I am currently using WAMP, should I switch to Docker?

8 Upvotes

I run Windows 10. I found that WAMP would provide a good development environment for PHP and MySQL, which is what I need.

Then, I found out about Docker and how it is the new "standard" and everyone uses it.

What are the advantages of Docker vs WAMP? Should I switch?

Docker mentions 'dependencies' and such, but I am not sure what that means, because in my case I only use PHP.

In what cases would Docker be better?

EDIT: I just found out I cannot run Docker Desktop since I have Windows Home (not pro). So I will use the 'Toolbox' version. Not sure if that changes anything.


r/PHPhelp • • Oct 10 '18

Scraping the </br> tag

8 Upvotes

I am trying to scrape the HTML of a site using PHP and DOMXPath.

The site that I'm scraping uses this break tag a lot,

</br> 

for line breaks. Now the site also uses this:

<br/> 

with the back slash at the end. It seems that I'm able to scrape the one right above, with the backslash at the end, but not the one where the backslash is in front, like this:

</br>.

I'm using both the saveHTML and saveXML functions to get the HTML.

Any ideas on how I can capture the

</br> 

tag and why I currently can't? I need to separate, or "explode" the strings with that deliminator.

Thanks!

UPDATE: Solution Found!

Thank you everyone in this thread who replied and for trying to help! I need to give a Special Shout Out to

judgej2 and

94bc

down below for offering me the simple solution which worked.

Ok, so here it is:

In PHP, when you scrape a web page, you first capture all of the HTML into a string, something like this:

$page = file_get_contents("https://www.reddit.com");

Now $page is a string, albeit a giant string, containing all of the HTML for that page. So in my case, the invalid HTML I was trying to access was the </br> tag. So all I needed to do, before using any fancy DOMDocument or DOMXpath methods, was simply take that giant string, $page, and do a string replace on it to convert all of the </br> tags.

Like this:

$page = str_replace("</br>", "<br/>", $page);

Bam! Now all of those weird </br> tags are now <br/> tags. Thanks guys!


r/PHPhelp • • Jun 27 '18

Php Object Oriented Design. Need help

8 Upvotes

I have a list of operations and i need to calculate bank commission for every operation.

Operation types for now: cash in, cash out.
Person types can be: natural or legal. Not sure if there can be more types, but i thinking with in mind, that its possible.

Commission size depends on operation type and what person type made that operation:

Cash in commission for everyone, is 0.07% but not more than 4.00 Eur.
Cash out commission for legal person is 0.2% , but not less than 1.00 Eur.
Cash out commission for natural person is 0.2%, but person can cash out 1000 Eur in a week for free.

Input is csv file. With lines like this:
2015-12-31,1,natural,cash_out,1000.00,EUR
2016-01-05,2,legal,cash_in,200.00,EUR
2016-02-01,1,natural,cash_out,1000.00,EUR
(Second value is user id).

I want to do this using all good oop practices, solid principles etc. So far im doing it like this:

$calculator = new Calculator();

foreach ($data as $row) {

    $operation = OperationFactory::create($data); //Returns instance of class CashIn, class CashOut etc
    $calculator->addOperation($operation);

}

$results = $calculator->calculate();

And now it becomes very confusing to me. If tax price would only depend on operation type, i would do something like this:

class Calculator
{
    public function addOperation(Operations\Operation $operation)
    {

        $this->operations[] = $operation;

    }

    public function calculate()
    {

        foreach ($this->operations as $operation) {

            $result = $this->operation->amount * $operation->charge / 100;

            if ($result < $operation->min) {
                $result = $operation->min;
            } elseif ($result > $operation->max) {
                $result = $operation->max;
            }

            $results[] = $result;
        }

 return $result;
    }
}

I want to make this, that i could easily extend system with new operation types and new person types if neccesary. And this complicates the task for me. Escpecialy that part : "Cash out tax price for natural person is 0.2%, but person can cashout 1000 Eur in a week for free". In which place should i track all of this?

Im doing all this for learning purposes. Any help and tips appreciated.


r/PHPhelp • • Apr 19 '18

TIFU by coming out of web programming retirement.

8 Upvotes

I hope the problem lies with my host, but I probably just suck.

Today, I hang my head in shame. I am stuck. It's been about 4 years since my last website with PHP and MySQL. I have tried using MySQLi object oriented and also linear procedure. Today I am admitting defeat over what is most likely the simplest part of my project. BlueHost is shared server running PHP 7.0, and MySQL Server version: 5.6.32-78.1 - Percona Server. My DNS is via Google Domains pointing to my BlueHost server. Everything is setup as default for the servers. I have tried to simplify my code down to near bare bones and have no issues with errors. I am not getting any errors and my page is loading fine and echo displaying my $email and $ip variables with no issues. However, when I check my SQL table, there is no row present and no updates. Again, there is no errors and no positive report that the connect was completed. My code is below.

<?php if(isset($_POST['email'])) { $email = $_REQUEST['email']; $ip = $_SERVER['REMOTE_ADDR']; $servername = "127.0.0.1"; $username = "user_name"; $password = "pass_word"; $dbname = "db_name"; $conn = new mysqli($servername, $username, $password, $dbname, 3306); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "INSERT INTO 'Signup' ('dt', 'email', 'ip') VALUES (CURRENT_TIMESTAMP, $email, $ip)"; if ($conn->query($sql) === TRUE) { echo "<script type= 'text/javascript'>alert('New record created successfully');</script>"; } else { echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>"; } $conn -> close(); echo $email; echo $ip; } ?>

Please help!


r/PHPhelp • • Mar 22 '18

Is this a bad practice / not recommended?

8 Upvotes

I am just starting my journey into learning php and I am doing so by creating an online application for myself. At one point I am trying to manipulate the content on the page based on sensitive data that only the admin should have access to, not a general user. So I thought I could do it easily in php since the user does not have access to the code obviously.

My problem was that I am not yet familiar with the DOM methods and practices for php, but I have a lot of experience with this sort of thing using javascript.

I was concerned about the user looking at the JS file provided and seeing the sensitive data, so I decided to do this:

<?php if ($admin_logged_in) { echo "<script src='admin_functions.js'></script>"; } ?>

As you can see, the sensitive data is being dealt with using javascript, but it is only available if the admin is logged in, not a general user.

I feel like this is a cheap and dirty work around, and yes I do plan on learning the proper way to solve my problem. This is just a temporary solution. I just was wondering if this is a bad idea and could lead to security issues.

Thank you.


r/PHPhelp • • Mar 05 '18

Solved Potential memory leak in PDO using 7.2.2?

8 Upvotes

I've been scratching my head trying to figure out the following issue and even opened up an official bugreport (https://bugs.php.net/bug.php?id=76053).

The following piece of code running on a brand new Laravel Homestead box using MariaDB (same deal with MySQL though) has a massive memory leak and time difference when running with 7.2 over 7.1:

<?php

$dsn = 'mysql:dbname=homestead;host=127.0.0.1';
$user = 'homestead';
$password = 'secret';

$pdo = new PDO($dsn, $user, $password);
$statement = $pdo->prepare('SELECT :column FROM :table WHERE grade <= :grade');

for($i = 0; $i < 1000; $i++) {
    $statement->execute([':grade' => 100, ':column' => 'id', ':table' => 'grades']);
    if ($i % 100 === 0) {
        echo memory_get_usage() . "\n";
    }
}

The more arguments i add to the execute function, the slower it gets.

Here's the "benchmark":

vagrant@homestead:~$ time php7.2 memorytest.php
578448
632880
687280
741680
796080
850480
904880
959280
1013680
1068080

real	0m2.769s
user	0m2.676s
sys	0m0.032s

vagrant@homestead:~$ time php7.1 memorytest.php
365440
365472
365472
365472
365472
365472
365472
365472
365472
365472

real	0m0.079s
user	0m0.028s
sys	0m0.016s

On average, the execute call generates ~550bytes of garbage. I've tested it with bigger queries and it can go up to several kilobytes!

Opcache is disabled on the CLI by default, but are there any config settings I might have missed? Cheers!


r/PHPhelp • • Feb 17 '18

PHP Design Patterns Book

8 Upvotes

Hi everyone, can any of the advanced PHP programmers out there recommend a great PHP design patterns book? Something that is really widely applicable hopefully, as I want knowledge that will apply broadly. The reason I want one written in reference to PHP is because I'm a web developer and am better with PHP than anything else so it feels like a very relevant choice for learning more about design patterns in general.

I'd also want something pretty current. Published post-php7 is what I'm thinking.

Thanks very much for anything you come up with.


r/PHPhelp • • Jan 02 '18

I'm building a text editor and would like a critical eye before I develop it further.

8 Upvotes

https://gitlab.com/z0x/pnano

Hi all,

I've been programming php a while (though I'd still consider myself a novice) and this is the first thing I've built that I think could (eventually) be useful to the community at large.

My problem is I have no point of reference whether or not my code is a dumpster fire.

Does this project have potential or am I completely delusional?


r/PHPhelp • • Nov 28 '17

Can you learn PHP without PHP?

8 Upvotes

I've been asked to learn PHP. I work at a big bureaucratic org where I don't have the ability to install anything myself. I put in a request to have PHP, Apache, and MySQL installed, but it might take a while.

Is there a tutorial site that has a PHP simulator so I can study while I wait?

Is there something I can download and use to practice PHP without having admin or root privileges?

Thanks either way.


r/PHPhelp • • Oct 30 '17

Need some PHP related exercise to tighten my grip oh PHP.

8 Upvotes

I google it, but couldn't find any good exercises.

I'm currently solving these exercises, but all of them are question like 'get file name or server address, etc' things.

So, can you guys refer me a good exercises, or the above one is better?


r/PHPhelp • • Oct 09 '17

Checking for availability between dates

8 Upvotes

So basically I am to make a reservation system for a resort. I have already made a database: https://imgur.com/f9aLyFZ. I really need to know how to check if dates are available when making a reservation.

So far I did this: $sql = "SELECT * FROM room_type_tbl

    INNER JOIN room_tbl ON room_type_tbl.room_type_id=room_tbl.room_type_id

    WHERE room_type_tbl.room_capacity='$roomcap' && ('$datein'>booking_tbl.checkin_date && '$dateout'<booking_tbl.checkoutdate)
";

if ($conn->query($sql) === TRUE) {
    //echo "Table MyGuests created successfully";
} else {
  echo "Error creating table: " . $conn->error;
}

It's not working and I'm about to go mad. Please help me.


r/PHPhelp • • Sep 18 '17

Php Database - Content Encryption / Decryption

8 Upvotes

Hello Reddit!

I'm working on a website that will input data into a Database, and the data itself is rather sensitive. As a precaution I want to have some Encryption / Decryption occur, and while I have had success in some basic testing, it's not currently working when I try to pull the data from the Database itself.

Here is what I currently have working;

$plaintext      = 'Hello World';

$encrypted      = openssl_encrypt($plaintext, $cipher, $key, 0, $iv);

$decrypted      = openssl_decrypt($encrypted, $cipher, $key, 0, $iv);

echo "<pre>" . $encrypted . " - Encrypted Version </pre>";
echo "<pre>" . $decrypted . " - Decrypted Version </pre>";

This works just fine on the page itself. When trying to input it into the Database, and retrieve it and Decrypt however, it stops working.

I can see the data inside the Database is encrypted, and I can echo out the results normally, however, when I attempt to use a mysqli_fetch_array() to loop through and retrieve the data, the same functionality that works just above, no longer works..

while($row = mysqli_fetch_array($result))
{

   $title = openssl_decrypt($row['title'], $cipher, $key, 0, $iv);

    echo "<pre>" . $title . " - Decrypted Version (MySQLi) </pre>";

}

Do note that the connection to the Database for the loop is working, as I can output the raw data itself. It's just through the openssl_decrypt that it no longer works.

I'm stumped for what's the cause, I have looked through a plethora of Stack Overflow questions on this, and many other online sources, but none of them are related to my problem.

I thank you for taking the time to read, and look forward to working through this issue.

You can also track the Stack Overflow conversation here: https://stackoverflow.com/questions/46281075/php-database-content-encryption-decryption


r/PHPhelp • • Sep 14 '17

Meaning of <input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />?

8 Upvotes

I know very little about php and have to look into a form. What does the line <input type="hidden" name="form_token" value="<?php echo $form_token; ?>" /> mean?

Thanks


r/PHPhelp • • Aug 16 '17

Could someone explain me this snippet please?

8 Upvotes
static public function init(){
    null === self :: $instance and self :: $instance = new self;
return self :: $instance;
}