r/PHPhelp • • Jul 20 '20

Seeking advice on developing functionality for a web app

7 Upvotes

I’m still a novice, but I need to develop a web app for school children to use for home learning. (It doesn’t have to be a complete application, but just have some good functionality.) So far I have a homepage, a login for the pupils, a separate login for the teacher, and a logged-in page for each. I’d really appreciate some advice please, about the following ideas, if they’re doable with PHP and MySQL, and if you have any suggestions on the best way I could go about this? I’ve got lots of ideas but feel overwhelmed and unsure about where to even begin. Thank you so much!

I’m thinking of having a multiple choice quiz for the pupils and for their results to be stored in a MySQL database. I’d like for the logged in pupil to be able to view their own results, and for the logged in teacher to be able to view all pupils’ results.

I also thought it would be good if I could somehow generate a ‘class average’ based on all pupils’ results for the teacher. And would it be possible for it to show what pupils have and have not completed the quiz?


r/PHPhelp • • Jun 23 '20

Storing money in a database (and other decimal values)

7 Upvotes

I've read quite a few oldish articles about properly storing money in a database. A lot of them say to use VARCHAR (due to rounding issues with floats), so £10.00 would be represented as 1000. This is also how I've been taught.

Is this still the common way of doing it? How about decimal type?

With the biggest argument being rounding issues, how about storing other float values (such as weight, height, width, etc). Should these be considered as VARCHARs?


r/PHPhelp • • Jun 09 '20

hey, PHP begineer here, im wondering, why is "if (preg_match('/^([0-9]|[0-9] [0-9])$/',$variable))" written like this? its supposted to check if the variable is a number, but i dont understand this syntax, why is there /,^,|,3x[0-9],$,/...?

7 Upvotes

r/PHPhelp • • May 16 '20

I have a weird issue in my VM when trying to connect to a mysql DB.

7 Upvotes

Hey guys. I'm working on an opensource CMS project and I ran into something strange. I work from a VM(Ubuntu 20.04) and every time I try to connect to the mysql server on my google cloud, I get this error: php_network_getaddresses failed.

(connection is made with mysqli (object oriented))

I think there's something wrong with the VM but I'm not really sure. I'm open to every suggestion.


r/PHPhelp • • May 13 '20

Can I write PHP that gets executed on the server automatically?

7 Upvotes

Hi,

for instance let's I wanna check regularly if there are customers in my database who have open invoices. How can I write a script that automatically gets executed without needing a user to request a php file from the server? Is that even possibly with PHP? If not how would you approach this otherwise?


r/PHPhelp • • May 10 '20

What is the best way to sanitize user input like name, phone?

7 Upvotes

A freelancer I hired to build the backend for a simple service booking website hasn't done any user input sanitation. All input is sent via jQuery AJAX to script running INSERT queries straight to the database.

I emailed him about it but he says he is away and it will be a while before he can get to it.

I am a web designer only so I can just read simple PHP code, but enough to understand when such a huge error is made.

Is there something I can do right now to add some form of sanitation to these inputs? Maybe a function? Googling it tells me a number of options and I'm not which ones to use. Most of my input are in text format like name, phone and ids.

Input is used like this

$name = $_POST["name"];
$phone = $_POST["phone"];
$id = $_POST["id"];

// SQL queries using $name, $phone and $id straightaway without any sanitization.

I am wondering if PHP has a inbuilt function that make these variables safe to go in database query.


r/PHPhelp • • Apr 13 '20

What is the best method for (IP) banning users on your site?

7 Upvotes

I am writing all PHP code myself. And I am wondering whether it's the most efficient way to have a SQL SELECT loop on every page that checks if the current IP is in the 'banned_ips' table?

If I forget 1 page, the banned IP will still get in. + There is an extra SQL statement on every page. What is the best method of doing this?


r/PHPhelp • • Mar 28 '20

Frameworks for transitioning bespoke applications

7 Upvotes

I spend a lot of time working with bespoke applications that were written years ago, before frameworks were a thing. This means I have to write validation, HTML for form fields etc. multiple times, instead of being able to say 'here's my model, give me a form with the fields and validation configured'.

I'd like to gradually transition each application to a framework so I can reduce some of this repeated work, and also take advantage of things like automatic CSRF protection. However, I've noticed that most PHP frameworks seem to assume that you will use them exclusively and do everything the way they want. This is fine for new projects, or small applications which can be ported in one step, but not so much for larger applications where a gradual transition is needed.

Are there any up to date frameworks out there which cater for this scenario? It feels like a need that many developers have, but isn't being met.


r/PHPhelp • • Feb 22 '20

In need of dire help and resources to learn - PHP, Laravel, Docker, Forge, AWS

7 Upvotes

At work, our PHP developer has left and we are not in the process of hiring another one. At the moment, funding is just okay, so we can't hire someone for another 2-4 months.

I'm actually a front-end developer(iOS/ReactJS, and a little node and python) and am not comfortable doing any of this, but would like to dive in and learn through any resources possible (even paid). The PHP dev left me a bunch login credentials for Forge, Envoyer, and AWS. I have no idea how to proceed from here. The dev shop before our current dev made a decent readme but I can't seem to connect the dots. I am so, so lost and just need some sort of a direction.

This is some copy + paste from the readme with issues I am stuck with below. Really... any direction is appreciated. I feel so stuck.

Running Locally

  1. Ensure you have the AWS CLI tools installed (via pipor brew)

  2. Open a terminal and navigate to this directory (API project root)

  3. Run docker-compose up -d

  4. Once the containers are running, you can provision the database by running ./bin/runme

  5. You're all set!

NOTE - If you wish to run the API on a port other than 80, just update the webserver port mapping from "80:80"to "8080:80"(or whatever port you want to be exposed).

 I run  'docker-compose up -d' , and I get an error message stating, ' (partial url)-east-1.amazonaws.com/v2/php/manifests/7.1-fpm-alpine: no basic auth credentials', soI attempted to use the command 'aws configure' and input 

AWS Access Key ID [******************D]:AWS Secret Access Key [*******************Z]:Default region name [east]:Default output format [None]:but not sure how to proceed from there... I can logon to AWS with the credentials just fine, but I tried logging to AWS with the credentials to the URL and I am not allowed in.

Connecting to the Database

  1. Database connection credentials can be found in the .envfile under the DB_*keys. The default port is 13306(when running Docker).

The Readme.MD states, "Database connection credentials can be found in the .env file under the DB_* keys. The default port is 13306 (when running Docker)."But when I go to API root directory and use the command 'open .env',  I don't see any section that is labeled 'DB_* keys''. I'm also confused as to why I was given a password to the .env file when I can just open it through terminal. My first thought, I am totally misunderstanding how this works and I am in approaching it incorrectly...

API

To set up a new installation of this API, your system must be set up to run PHP and MySQL.

You must also have Composer and the Apiary CLI Client installed. Note that installing the Apiary CLI Client may require you to install the ruby-devOS package first.

To set up the Laravel system, run the following commands at the root level of this project directory.

$ composer install $ bin/setup

Then set up the .env file according to your environment. You can generate Apiary keys at: https://login.apiary.io/tokens

When your database information is set up, run the following command to set up migrations:

$ php artisan migrate

Once migrations are complete, your system is ready to go.

For more information about about the installation, please refer to Laravel's guide.

So, I failed miserably at running locally and connecting to the database, but I was able to successfully run the commands, 'composer install' and 'bin/setup'but on the command, 'php artisan migrate', I get this error :  SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_schema.tables where table_schema = companyapp and table_name = migrations)      

I understand that there is some sort of connection in the .env file, because there is a line with 'DB_DATABASE=companyapp'The command, 'php artisan migrate --env=production', looked like it might work, but on the premise that I have no idea what the hell I am doing, I'm hoping I can get input from you guys before running anything big.

In the midst of trying to just get things to run, I've downloaded MySQLWorkBench and Docker Desktop. 

I'm going to take a step back and just learn how these two work better.

On the bright side, I am hoping to use this hurdle as a way to understand Docker and AWS better. I'm hoping this shitty struggle and chaos with PHP Laravel turns me into a better dev. I'm not trying to make any new features but I do want to be able to do simple things like, delete a test user, debug 400's..that's about it.

Again, any advice or some sort of direction is greatly appreciated. I am not looking to solve this overnight, but instead, to learn a lot from this situation. Worse comes to worse, do you guys think it'd be appropriate to have my founder pay hours for the dev agency beforehand ? The previous dev seems like he has no interest to help, but he's also quite busy. Should I pester him more?


r/PHPhelp • • Jan 30 '20

Encoding issue, trying to replace strings but getting a way different result

7 Upvotes
<?php
function Utf8_ansi($valor) {

    $utf8_ansi2 = array(
    "\u00c0" =>"À",
    "\u00c1" =>"Á",
    "\u00c2" =>"Â",
    "\u00c3" =>"Ã",
    "\u00c4" =>"Ä",
    "\u00c5" =>"Å",
    "\u00c6" =>"Æ",
    "\u00c7" =>"Ç",
    "\u00c8" =>"È",
    "\u00c9" =>"É",

return strtr($valor, $utf8_ansi2);      

}

$test='\u00e9", ';

echo Utf8_ansi($test);   

?>

My output is és",

Any ideas?


r/PHPhelp • • May 31 '19

What are the differences between using object (`stdClass`) and associative array?

7 Upvotes

After reading this: https://www.webmaster-source.com/2009/08/20/php-stdclass-storing-data-object-instead-array/.

I was wondering what are the differences between using object (stdClass) and associative array? Are there any performance benefit of each others? When should I use array and when should create stdClass instead?


r/PHPhelp • • May 26 '19

An API for IBAN conversion?

7 Upvotes

Is there a free API that anyone knows of to allow conversion of bank sort codes and account numbers into IBANs?

IBAN have a paid one, but pricing is expensive.


r/PHPhelp • • Apr 23 '19

Php cmd command with console

7 Upvotes

Hi, i want to launch a .bat file. I want to launch it with console. I tried:

system("my_script.bat");

But console doesn't open and the output is printed in my php page.

I also tried:

exec("my_script.bat");

But console still don't open

SOLUTION:

system("start my_script.bat");

r/PHPhelp • • Apr 09 '19

Do I need to wait for an ajax request to finish before refreshing the page?

7 Upvotes

Normally I understand that it's really helpful to get a response from my ajax call, but I have one instance where the call triggers a script that can take minutes to process and I would honestly rather not even have my user on the page that made the original call while that is happening.

Will the ajax call see that the original user is not there and just eventually kill the script? I realize I could do some trial and error, but this seems like the sort of thing I'd love an answer from someone smarter than me on rather than introducing a bug after my own non-scientific testing.


r/PHPhelp • • Feb 26 '19

SSL certificate applied, logo link now broken - https replaced with [site_url_secure]

7 Upvotes

Apologies if this is below even noob level questioning but I have worked out enough from a couple of hours' web searching to realise that this probably has something to do with php but I know nothing about it. Basically, I've been asked to bring an old site up to speed with a SSL certificate. It was applied but with a mixed content notification. I fixed three image errors which were pointed at http files. However, every time I try to fix the logo and save the site, the link shows as broken. Inspecting the element shows it has replaced the https part with src="site_url_secure/..."


r/PHPhelp • • Nov 05 '18

PHP for other stuff than web development

7 Upvotes

So I started working for a software company a month which is great, only they PHP for almost everything.

So my question is, if there is any book or online tutorials that teaches PHP but for other stuff than web development?


r/PHPhelp • • May 27 '18

I'm in a weird spot with php - how can I get better?

7 Upvotes

Over the years I've had a desire to learn PHP. I've bought books, like PHP for dummies, I've played with code, I've done online courses like code academy and solo learn. I'm at a point now where if you were to show me a php file I can read it and tell you what it is doing (or..will do I guess). I can also make some modifications to it. If you ask me to then rewrite it, well, that's a no. It's an odd situation and I'm very frustrated by it.

I find that I understand PHP, the syntax, all of that, but I can't really figure out how to write my own...from scratch. I'd really like to be able to, but I don't know what to do to get to that next step. Following books and online courses are so easy it's boring and I don't learn anything. Those cover simple things like operators, syntax, functions, loops etc. I understand all of that, but I need to make something on my own.

Ideally I'd like to rebuild one of my websites with Laravel or CakePHP, but I don't feel like I am at a point where I can do that. What should be next step be?


r/PHPhelp • • May 09 '18

Please help us make /r/PHPHelp better!

7 Upvotes

Please help us make /r/PHPHelp better!

The mods of /r/PHPHelp would like to know who you are and what you hope to get out of this subreddit, so we can work to make /r/PHPHelp a better place!

If the poll questions don't cover you, please leave a comment.


Vote ButtonPoll OptionsCurrent Vote Count
VoteI am a student, and intend to make PHP my career.4 Votes
VoteI am a student, looking for homework help. No plans to make PHP a career.1 Votes
VoteI don't work in tech, but I am learning now to eventually change careers.3 Votes
VoteI work with PHP, and am here for help with the occasional problem.11 Votes
VoteI work with PHP, and am here primarily to help other people.29 Votes

Instructions:

  • Click Vote to Register Your Vote.


Note: Vote Count in this post is updated manually


Make Your Own Poll Here redditpoll.com.


See live vote count here

EDIT: Seems redditpoll has been down for 24 hours, so i'm taking the post off sticky. Thank you to everyone for your feedback! We'll be using it to make /r/PHPHelp a better place!


r/PHPhelp • • Feb 01 '18

Am I doing OOP the wrong way ?

7 Upvotes

Ok, so I've been coding for a few years now, but I have a bias. I code mostly alone, delivering packaged scripts to customers, whether in vanilla PHP/MySQL (+some kind of a front but not always) or as a Prestashop/OpenCart/WordPress plugin.

I recently coded a scraping script : getting listings + ads every day, geo matching them and mailing them to the relevant targets, and I used the opportunity to upgrade my "not a framework more a set of functions organized in objects, like a HTTP object and a Text Object and a bare controller", and while browsing some tutorials and references, I once again asked myself if i was doing OOP The Right Way (spoiler : I'm not, but I'm willing to improve).

Brief view of the index.php code to have an actual example :

$Main = new MainSortOfAController(); // on construct : parse query, set up $Main->db = new DB() and $Main->http = new HTTP()
$Listings = new SourceListingsClass(); // class SourceListingClass (specific to the source of data) extends ListingClass
$Ads = new SourceAdsClass(); // idem
// sample action
$Listings->fetch_listings();

The Listings Class has methods like fetch_listings(), parse_listings(), etc.

Classes usually stores non writable data in $this->data (with setData($id,$value) - conditional on $this->data[$id] being not set before, and getData()) and stores loop data (rewritten at each iteration) in $this->current (with setCurrent() and getCurrent, etc.)

In other words, I might be using objects as (very fat) controllers everytime and not as proper objects. I don't have any Listing class, or Ad class, but Ads class that fetch, parse and store data in loops.

I am interested in feedback, since I need to improve the maintainability and readability of my code, and am interested in changing the way I code, and maybe follow a mini framework project.

Performance is actually pretty good, all SQL statements are prepared in the DB class, HTML is in the /templates/ directory (ie be gentle with me)

Sidenote : plenty of websites/tutorials/books to explain the "how ?", very few if any to explain the "why ?". Design choices, script architecture, etc.


r/PHPhelp • • Jan 18 '18

PHP average response time up from 113ms to 2500-7000ms.

7 Upvotes

Site works. Slow, though. Avg. response time (via loader.io) is suddenly up from the normal 100-113ms (with 2.500 test clients per minute) to the current 2500-6300ms (with 50-1200 test clients per minute, and aborted tests after a few seconds due to 50% failure threshold reached at that point, if I go above 50 clients/minute). No detected change in PHP settings, as they were kept during the last php repository upgrade. So, naturally, I'm puzzled (and baffled).

Anyway, I'm getting hammered constantly with these two errors/warnings over the last 24 hours:

nginx error.log

2018/01/18 10:25:28 [error] 668#668: *107499 connect() to unix:/run/php/php7.2-fpm.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: 162.158.79.73, server: www.example-site.dk, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.2-fpm.sock:", host: "www.example-site.dk"

In conjunction with PHP warnings:

php error.log

[18-Jan-2018 10:25:15] WARNING: [pool www] server reached pm.max_children setting (5), consider raising it

Changing the pm.max_children (to 25, for instance - I run 8 cores and 3GB of RAM), doesn't help a bit. Tests still fail quickly or run at ~7.000ms avg. response time. No new php scripts installed, either. But I guess an existing one could have become slow to execute and bogs down the system?

Anyway, when running non-PHP tests (with a simple index.html), nginx delivers the expected average response times of 100-120ms for 2500 test clients/minute.

So, PHP I'm looking at you.

root@example-site#> nginx -v

nginx version: nginx/1.13.8

root@example-site#> service nginx status

● nginx.service - nginx - high performance web server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2018-01-12 22:24:25 CET; 5 days ago
     Docs: http://nginx.org/en/docs/
 Main PID: 660 (nginx)
   CGroup: /system.slice/nginx.service
           ├─660 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.con
           ├─661 nginx: worker process
           ├─662 nginx: worker process
           ├─663 nginx: worker process
           ├─664 nginx: worker process
           ├─665 nginx: worker process
           ├─666 nginx: worker process
           ├─667 nginx: worker process
           └─668 nginx: worker process
Jan 12 22:24:24 example-site systemd[1]: Starting nginx - high performance web server...
Jan 12 22:24:25 example.site systemd[1]: Started nginx - high performance web server.

root@example-site#> php -v

PHP 7.2.1-1+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Jan  5 2018 13:54:13) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.2.1-1+ubuntu16.04.1+deb.sury.org+1, Copyright (c) 1999-2017, by Zend Technologies

root@example-site#> service php7.2-fpm status

● php7.2-fpm.service - The PHP 7.2 FastCGI Process Manager
   Loaded: loaded (/lib/systemd/system/php7.2-fpm.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2018-01-18 10:32:04 CET; 21min ago
     Docs: man:php-fpm7.2(8)
 Main PID: 20095 (php-fpm7.2)
   Status: "Processes active: 0, idle: 3, Requests: 78, slow: 0, Traffic: 0req/sec"
   CGroup: /system.slice/php7.2-fpm.service
           ├─20095 php-fpm: master process (/etc/php/7.2/fpm/php-fpm.conf)
           ├─20096 php-fpm: pool www
           ├─20097 php-fpm: pool www
           └─20100 php-fpm: pool www

www.conf (extract)

[www]
user = www-data
group = www-data
listen = /run/php/php7.2-fpm.sock

php.ini (extract)

cgi.fix_pathinfo=0

/etc/nginx/sites-available/#> vi example-site

server {
        listen 443 ssl http2 default_server; # managed by Certbot
        server_name www.example-site.dk;
        root /var/www/example-site.dk;
        index index.php index.html index.htm;
        location / {
                #try_files $uri $uri/ =404;
                try_files $uri $uri/ /index.php$is_args$args;
        }
        ssl_certificate /etc/letsencrypt/live/example-site.dk/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/example-site.dk/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
        ssl_client_certificate /etc/nginx/certs/cloudflare.crt;
        ssl_verify_client on;
        if ($scheme != "https") {
        return 301 https://$host$request_uri;
        } # managed by Certbot
        location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_intercept_errors on;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        }
        location = /favicon.ico { log_not_found off; access_log off; }
        location = /robots.txt { log_not_found off; access_log off; allow all; }
        location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ {
        expires max;
        log_not_found off;
        }
        location ~* /wp-includes/.*.php$ {
        deny all;
        access_log off;
        log_not_found off;
        }
        location ~ /\.ht {
        deny all;
        }
    }

How do I find the culprit?


r/PHPhelp • • Nov 13 '17

csv to php with html table

7 Upvotes

I have a csv file with product data in it. I have this code written that returns only the columns I need.

I would like to have it so I could restrict the products shown by "type"($data[8]) but I'm struggling with where to put the correct statement.

<?php $handle = fopen("products.csv", "r"); ?> 
<table> 
    <thead> 
        <th> 
            SKU 
        </th> 
        <th> 
            Type
        </th> 
        <th> 
            Name
        </th> 
        <th> 
            Variation 1
        </th> 
    </thead> 
    <tbody> 

<?php 
fgetcsv($handle);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE): ?> 
    <tr> 
        <td><?= $data[2] ?></td> 
        <td><?= $data[8] ?></td> 
		<td><?= $data[6] ?></td> 
		<td><?= $data[10] ?></td>         
    </tr> 
<?php endwhile; ?> 

    </tbody> 
</table>                        

r/PHPhelp • • Oct 22 '17

Question: What would be a good book for web development in general or just PHP?

7 Upvotes

I have been using PHP for several months and am looking for intermediate and not just beginning books. Thx!


r/PHPhelp • • Oct 19 '17

How mysql_real_escape_string() works?

7 Upvotes

I'm trying to understand how mysql_real_escape_string() works. I've been trying for some time to grasp it thoroughly.

I really appreciate your help. Thanks


r/PHPhelp • • Oct 05 '17

Coming back to PHP dev, kind of... I have a client with an OLD OLD OLD custom php app thats running on 5.3.x right now and I'm trying to get it moved over to 7x. Are there any tools that can take my target php version, and scan the php files and tell me what is deprecated/incompatible?

7 Upvotes