Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
We built our own, but it implements alot of the same ideas as Laravel, from what i’ve been told

Adbot
ADBOT LOVES YOU

LP0 ON FIRE
Jan 25, 2006

beep boop
e: Can't believe I forgot to do anything with the $rgb values in the $color var! I just updated it, and playing around, but still can't seem to adjust the color. At least it shows a black shirt.

My version of php doesn't have imagefilter, and I wanted to remake the IMG_FILTER_COLORIZE, which I thought would be easy enough. I have an image of a black shirt with a white background. I expected that only the black shirt would change to the color set in imagecolorallocate. Instead, it changes the entire image to that solid color. In this case the white background could be transparent, but it does not look to be on the source image. Does that matter? Anyone know where I'm going wrong here?

code:

<?

$im = imagecreatefrompng('sourceImages/testShirt.png');

$rgb  = "";

for($x = 0; $x < imagesx($im); ++$x)
{
	for($y = 0; $y < imagesy($im); ++$y)
	{
		$index = imagecolorat($im, $x, $y);
		$rgb = imagecolorsforindex($im,$index); 
		$color = imagecolorallocate($im, $rgb['red'] + 50, $rgb['green'] + 200, $rgb['blue'] + 50);

		imagesetpixel($im, $x, $y, $color);
	}
}

print_r($rgb);

imagealphablending( $im, false );
imagesavealpha( $im, true );

$imgname = "result.png";
imagepng($im,$imgname);

?>

<img src="result.png">

<?

imagedestroy($im);

?>

LP0 ON FIRE fucked around with this message at 20:38 on Jan 19, 2018

LP0 ON FIRE
Jan 25, 2006

beep boop
I just updated the code, because it had no sense with what I was trying to do. I wasn't using the $rgb color key values or passing $im to imagecolorsforindex. Still, I don't have the desired effect I'm talking about. Still alters the color white.

Acidian
Nov 24, 2006

Anyone know a good site for PHP excercises for beginners. I am trying to learn the language, but I am using a book + w3schools + a learn programming app, but none of them have any exercises. I can't learn from just reading and testing some premade examples. I am at a part where I need to start learning classes, but I feel like I have forgotten half the chapter about loops, switch and if statements.

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!

Acidian posted:

Anyone know a good site for PHP excercises for beginners. I am trying to learn the language, but I am using a book + w3schools + a learn programming app, but none of them have any exercises. I can't learn from just reading and testing some premade examples. I am at a part where I need to start learning classes, but I feel like I have forgotten half the chapter about loops, switch and if statements.

I think Laracasts is great for beginners, also Laravel is a great framework so you can't go wrong.
Jeffrey has some great videos and examples for PHP beginners too. Some are free, check it out.
https://laracasts.com/

Beyond that, I am self taught so don't have any other advice on guides or learning. I wanted to build something specific and learned how to do specific tasks along the way.
Everyone has a different learning style, I'm a hands-on learner and don't do well reading books. Watching videos at Laracasts and digging into the code from the git repo is a good way to see how things work and then adapt that to what you're trying to do.

Acidian
Nov 24, 2006

DarkLotus posted:

I think Laracasts is great for beginners, also Laravel is a great framework so you can't go wrong.
Jeffrey has some great videos and examples for PHP beginners too. Some are free, check it out.
https://laracasts.com/

Beyond that, I am self taught so don't have any other advice on guides or learning. I wanted to build something specific and learned how to do specific tasks along the way.
Everyone has a different learning style, I'm a hands-on learner and don't do well reading books. Watching videos at Laracasts and digging into the code from the git repo is a good way to see how things work and then adapt that to what you're trying to do.

That's kinda the way I want to go too, I just want to get my head around the basics. Problem solving is definitely the best way to learn (and hence why I want some exercises to do).

To do what I want, I need to learn both PHP and SQL. I want to download and parse (and format) informaton from xml files or flat .txt files that I download form both an xml api and an ftp, then put that information into an SQL database. Then I need to create my own interface to a website running the php/sql server, so I need to know some html (which I know), css (I know a little) and javascript (not at all). So it's a long process.

I wasn't planning on using a framework to start, as I will be doing it all internally, and the server wont be accessible for anyone outside to start with. Though to be honest I don't completely know what a framework is, other than being able to create websites without reinventing the wheel in code everytime.

I chose php over a normal programing language because I will be working in php in the future on other projects (like making modules for Magento 2.0 (which is a framework?) if I ever get that far), also in far future work I might be in a situation where I am not allowed to install and use local applicatons in python, but applications running serverside in browser are fine (doing bioinformatics research in a hospital), and anyway I am already working a bit in HTML and CSS in my current work.

Murrah
Mar 22, 2015

In case you hadn't seen it just as a side note, Repl.it is a great website/resource that allows you launch a REPL in many languages including PHP if you want to try something out quickly

McGlockenshire
Dec 16, 2005

GOLLOCKS!
... or just use the built in REPL by invoking php -a in a terminal.


Acidian posted:

I am trying to learn the language, but I am using a book + w3schools + a learn programming app, but none of them have any exercises.
Avoid w3schools for anything related to PHP. It took a massive public shaming campaign for them to even begin to clean up just some the horrible advice that's accumulated there over the years. They are not to be trusted. Further, any general tutorial about PHP made more than five years ago should be ignored as well, as should any that don't have publishing dates at all. The PHP language and ecosystem have transformed dramatically in the past few years, especially with regard to popular frameworks.

You are right to learn the language itself, and all the built in stuff, before looking at frameworks. Something I might recommend to you is reviewing the No Framework Tutorial, which walks you through the individual architectural bits that frameworks provide and demonstrates both standalone and framework libraries you can use. Another resource once you already know the basics of the language would be PHP: The Right Way. Both of these sites assume that you're a veteran coder and that PHP is not your first language. They can be quite overwhelming to take in.

For exercises, you might consider looking for general programming exercise sites, which will at least get you familiar with the syntax. Unfortunately the name of the one I played with for a while now escapes me, but many of them that I've looked at allow you to use PHP.

e: After a re-read, are you actually completely new to programming? Without intending to insult you in any way, head on over to code.org and play with their tools for schoolchildren. It's seriously a great introduction into the process of writing code, even if all you think you're doing is connecting puzzle pieces together. Please don't learn about objects & object oriented stuff ("classes") until loops and control structures aren't awkward for you.

McGlockenshire fucked around with this message at 18:37 on Mar 11, 2018

spiritual bypass
Feb 19, 2008

Grimey Drawer
Be prepared to call in paid help with Magento. It's notoriously troublesome to program. Even just hosting it can be difficult due to its performance characteristics.

Acidian
Nov 24, 2006

McGlockenshire posted:

... or just use the built in REPL by invoking php -a in a terminal.

Avoid w3schools for anything related to PHP. It took a massive public shaming campaign for them to even begin to clean up just some the horrible advice that's accumulated there over the years. They are not to be trusted. Further, any general tutorial about PHP made more than five years ago should be ignored as well, as should any that don't have publishing dates at all. The PHP language and ecosystem have transformed dramatically in the past few years, especially with regard to popular frameworks.

You are right to learn the language itself, and all the built in stuff, before looking at frameworks. Something I might recommend to you is reviewing the No Framework Tutorial, which walks you through the individual architectural bits that frameworks provide and demonstrates both standalone and framework libraries you can use. Another resource once you already know the basics of the language would be PHP: The Right Way. Both of these sites assume that you're a veteran coder and that PHP is not your first language. They can be quite overwhelming to take in.

For exercises, you might consider looking for general programming exercise sites, which will at least get you familiar with the syntax. Unfortunately the name of the one I played with for a while now escapes me, but many of them that I've looked at allow you to use PHP.

e: After a re-read, are you actually completely new to programming? Without intending to insult you in any way, head on over to code.org and play with their tools for schoolchildren. It's seriously a great introduction into the process of writing code, even if all you think you're doing is connecting puzzle pieces together. Please don't learn about objects & object oriented stuff ("classes") until loops and control structures aren't awkward for you.

I took a course in java, had some python in my bioinformatics course, and I also took a course in webdesign back when html strict was a thing. However, it's been a few years so I would consider myself as pretty new to programming. I will have to design some more exercises for myself to be more familiar with the different loops, before I move on to classes. I have worked with objects before, so it will probably get back to me. I am also aware of the rapid changes in the field (it's the same with my primary field), so I stick to material that's written for PHP 5. Thanks for the heads up about w3schools, I was only using it as a second repetition of what I am reading in my book, but I think it's better to just reread the chapter I was on. I will definitely check out those links once I am more comfortable with the basics (and I will probably start learing SQL before I move on to frameworks as well).

Thank you.

rt4 posted:

Be prepared to call in paid help with Magento. It's notoriously troublesome to program. Even just hosting it can be difficult due to its performance characteristics.

No worries, we already have paid help, and they will take care of the hosting. Magento 2.0 is supposedly alot better and different than 1.0, depending on what you have heard, but I just want to know how it works since I will be working in the environment.


Murrah posted:

In case you hadn't seen it just as a side note, Repl.it is a great website/resource that allows you launch a REPL in many languages including PHP if you want to try something out quickly

I downloaded a wamp package from wampserver.com, it has Apache2, PHP and MySQL, just to spare me the effort to set it up. Then I use Dreamweaver from Adobe :filez: to run the code without needing to publish it (I tried Eclipse and Netbeans, but didn't like it). Did not know about repl.it, but thanks, now I have a place to test code from anywhere.

spiritual bypass
Feb 19, 2008

Grimey Drawer
I recommend skipping Apache and using the integrated PHP dev server instead. It'll help you sidestep all the Apache configuration headaches.

Ranzear
Jul 25, 2013

I strongly recommend dumping Apache entirely and forever for nginx+PHP-FPM instead.

Yes, Apache and mod_php can allegedly be a little faster... in single core environments ... with limited memory ... and avoiding simply changing default file handler limits, but it takes days of tuning to beat out an out-of-the-box -FPM stack. Then you have very nice nginx static serving too and a single point of configuration instead of htaccess vomit everywhere.

I might be venting. Apache likes to completely poo poo the bed on the really braindead API stuff we do and I greatly enjoy being able to say 'no Apache' on all our future projects.

Ranzear fucked around with this message at 04:23 on Mar 12, 2018

Acidian
Nov 24, 2006

Ranzear posted:

I strongly recommend dumping Apache entirely and forever for nginx+PHP-FPM instead.

Yes, Apache and mod_php can allegedly be a little faster... in single core environments ... with limited memory ... and avoiding simply changing default file handler limits, but it takes days of tuning to beat out an out-of-the-box -FPM stack. Then you have very nice nginx static serving too and a single point of configuration instead of htaccess vomit everywhere.

I might be venting. Apache likes to completely poo poo the bed on the really braindead API stuff we do and I greatly enjoy being able to say 'no Apache' on all our future projects.

And how would I go about setting up nginx+php-fpm+mysql? The reason I went for Wamp was so I didn't have to worry about any setup time or learning how to get the 3 platforms to work together. It's just install and done.

Anyway, for a purely "sit home and learn php by myself" purpose, I am sure Apache will hold up.

Edit: I found an Ubuntu tutorial, so I can use that when I want to start setting up a production server. https://www.howtoforge.com/installing-nginx-with-php5-fpm-and-mysql-on-ubuntu-14.04-lts-lemp

Acidian fucked around with this message at 16:15 on Mar 12, 2018

Ranzear
Jul 25, 2013

Hoof, that's an old one and smells of grognard. It sets cgi.fix_pathinfo=0 though, so it's on the right track.

If you don't know you need PHP 5.x, move up to PHP 7.2, and you should probably be on Xenial by now.

(This one is a bit better, but trash their mysql for MariaDB instead if you wanna be a cool FOSS kid, and PHP 7.2 instead of 7.0.)

That nginx config is really slapdash and rudimentary. Work from the stock configuration instead. Nginx configuration looks complex at first, but it's 'set it and forget it' most of the time. Dump the ipv6 lines. Dump the extra location blocks until you know what you need them for. If you want https, certbot can alter your configuration automatically, but a lot of tutorials are overwrought; you just install and do 'certbot' and pick nginx (or run certbot --nginx). Use your real domain and/or IP in server_name, not the wildcard underscore, so you dump all other requests. snippets/fastcgi-php.conf is likely very wrong - you'll have a fastcgi-params include in the stock config already.

I don't know why it has you change from a unix socket to localhost:9000, don't do that part.

Don't install APC, use the native -opcache package.

The mysql support section is kinda wrong. You don't need to install all of those individually. Just do php7-mysqlnd I think, which is the native driver. Install -pdo if you need it (you should need it).

So your install is more like:

code:
sudo apt-get remove apache2
sudo apt-get install nginx php7.2-cli php7.2-fpm php7.2-pdo php7.2-mysqlnd php7.2-opcache
and for MariaDB, go here, then run mysql-secure-installation.

And for gently caress's sake don't leave a php info page hosted.

Ranzear fucked around with this message at 19:00 on Mar 12, 2018

Acidian
Nov 24, 2006

Damnit, now I kinda want to set this up. I will reinstall Ubuntu on my server when I get home, and I might have some questions if I get stuck and unable to Google the answer.

Thanks for the help guys, you are great goons.

Pile Of Garbage
May 28, 2007



Speaking of installing PHP, is the PPA from Ondřej Surý considered reputable: https://launchpad.net/~ondrej/+archive/ubuntu/php? I added it quite some time ago to get the latest PHP back when Ubuntu and Debian repos were lagging behind the times and its been pretty good I guess.

Also if it's your first time working with a server that's exposed to the internet then I'd recommend reading this tutorial from Linode which gives some good basic tips for hardening: https://linode.com/docs/security/securing-your-server/

Master_Odin
Apr 15, 2010

My spear never misses its mark...

ladies

cheese-cube posted:

Speaking of installing PHP, is the PPA from Ondřej Surý considered reputable: https://launchpad.net/~ondrej/+archive/ubuntu/php? I added it quite some time ago to get the latest PHP back when Ubuntu and Debian repos were lagging behind the times and its been pretty good I guess.
Yeah, his work is the definition of a reputable PPA you don't need to worry about installing on your server.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Master_Odin posted:

Yeah, his work is the definition of a reputable PPA you don't need to worry about installing on your server.

Seconding Ondřej Surý being reliable.

Remi Collet's RPMs for the RHEL/CentOS/Fedora world are also trustable.

Ranzear
Jul 25, 2013

Remi is good. I go to Webtatic for some reason, I think they're faster with or just have better coverage of some weird modules and gives me a newer (and not Fedora branded?) nginx too on Centos7.

Acidian
Nov 24, 2006

I went with a windows installation for the time being, seeing as all my harddrives are in ntfs and I want to be able to write to them without formating. I assume that I can't write to ntfs. Don't feel like booting windows to download a movie.

Downloaded PHP Non Thread Safe version, since I saw FastCGI mentioned in the description, was this correct? I changed php.ini to cgi.fix_pathinfo=0, but what does this do? I did not understand the explanation in the ini file, but I also don't understand what cgi is. Is there anything else I might want to change (I enabled some error message reporting and I also added xdebug)?

For the nginx config file, is this ok?

code:
location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9123;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
Also, in the server {} part, I only added the top line, but what is the second line for [::]:?
code:
 listen 80 default_server;
 listen [::]:80 default_server;
I also downloaded and installed MariaDB, did not seem to require any additional configuration. My phpinfo() lists mysql as being present.

BallerBallerDillz
Jun 11, 2009

Cock, Rules, Everything, Around, Me
Scratchmo

Acidian posted:

Also, in the server {} part, I only added the top line, but what is the second line for [::]:?
code:
 listen 80 default_server;
 listen [::]:80 default_server;


I'll let php experts answer the other parts, but as for this, it's just setting it to listen on both ipv4 and ipv6. It's usually considered best practice to remove ipv6 if you're sure you won't need it as it reduces attack surface, but for a test server with basic configurations it's probably not really necessary.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Also, Linux not being able to write to NTFS hasn't been true for a decade. Assuming you're even using them in the same machine instead of accessing it over the network via Samba.

bigmandan
Sep 11, 2001

lol internet
College Slice
You could check out Laravel Homestead. It is a pretty great development environment even if you are not using Laravel.

Ranzear
Jul 25, 2013

Acidian posted:

cgi.fix_pathinfo=0 [...]

code:
location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9123;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }

What it does, ostensibly, is prevent stuff like traversal attacks (~domain.tld/../../../foo.php) and passing weird stuff like an uploaded image bar.png with php headers then accessed with ~domain.tld/bar.png/nonexistent.php getting passed to fastcgi, because that configuration would otherwise take anything and everything that ends in .php and pass it to fastcgi but then it will 'fix' the script location to where it found the first extension, leading to php running the bar.png as a php script. It just makes to so your .php files have to be found directly and accurately, like you would expect them to be.

CGI is 'common gateway interface' and in quick and dirty terms it's just a standard pipe to and from something running a script at the location passed to it. It's 'run this script/process and give me a file handler to its input and output'. FPM is a crazy beast that can basically run thousands of workers preloaded with the scripts all the time so you just hit a preexisting process and your response times are stupid low, meanwhile most scripts are in shared memory so you end up using only about 10MB of memory per worker for even the largest codebase, so not only do you get a connection handled per worker but they rip through requests even faster so your workers stay even more available.

Ranzear fucked around with this message at 22:00 on Mar 14, 2018

MrMoo
Sep 14, 2000

Annoying when you do actually want PATH_INFO though, you end up with redundant looking configuration
code:
location ~ ^(.+\.php)(.*)$ {
        fastcgi_split_path_info ^(.+\.php)(.*)$;
        try_files $fastcgi_script_name =404;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        set $path_info $fastcgi_path_info;
        fastcgi_param PATH_INFO $path_info;
        include fastcgi_params;
}

Ranzear
Jul 25, 2013

code:
location / {
	try_files $uri $uri/ /index.php?/$request_uri;
	location ~ /\.php$ {
		include         /etc/nginx/fastcgi.conf;
		fastcgi_split_path_info ^(.+\.php)(/.+)$;
		fastcgi_param	SCRIPT_FILENAME	/var/www/scripts$fastcgi_script_name;
		fastcgi_pass    unix:/var/run/php-fpm.sock;
	}
}
This is sufficient to pass path and lets your PHP actually be wherever you want instead of the root you specify before the location block (say, /var/www/public vs /var/www/scripts), meaning your scripts can't be static served by accident. It works for CodeIgniter at least though I've made a few speculative changes (the inner location block was just '= /index.php', not sure if regex match will work there). It even supports a bare path on your domain going to index.php (CI's style and others).

Nested location blocks are the black magic of nginx.

Ranzear fucked around with this message at 22:19 on Mar 14, 2018

Acidian
Nov 24, 2006

Alright, thanks guys!

I know EDI and code editors are very subjective. I am currently using Dreamweaver, but mostly because it allows me to get the output immediately in a split screen after saving the file, rather than having to refresh my browser. At my level it doesn't really matter much, but any recommendations? Sublime and PHP Storm seems the most recommended?

duz posted:

Also, Linux not being able to write to NTFS hasn't been true for a decade. Assuming you're even using them in the same machine instead of accessing it over the network via Samba.

It's definitely not a decade since last time I used linux. I can't remember if I was running Debian or Ubuntu, but I was sure I had problems writing to my NTFS drives. That doesn't mean there wasn't a hack for it, but does Ubuntu now support it out of the box?

bigmandan
Sep 11, 2001

lol internet
College Slice

Acidian posted:

Alright, thanks guys!

I know EDI and code editors are very subjective. I am currently using Dreamweaver, but mostly because it allows me to get the output immediately in a split screen after saving the file, rather than having to refresh my browser. At my level it doesn't really matter much, but any recommendations? Sublime and PHP Storm seems the most recommended?


It's definitely not a decade since last time I used linux. I can't remember if I was running Debian or Ubuntu, but I was sure I had problems writing to my NTFS drives. That doesn't mean there wasn't a hack for it, but does Ubuntu now support it out of the box?

Both Sublime and PHP Storm are great. I use PHP Storm most of the time now as I like it's debugger interface a lot better than the xdebug plugin for Sublime. But If I'm just writing something really quick I'll use Sublime still.

itskage
Aug 26, 2003


I used to use PHPStorm, but for the past 4 months I've been writing PHP almost daily in VSCode and I love it. Its JS support is fantastic if you're doing frontend stuff at all too, so it's bonus. And I also frequently switch to C# or node for some other services we manage and I like having a consistent IDE for it.

I have a tutorial I give to new hires for setting up nginx+php on windows, with VSCode and the PHP extensions for debugging in VSCode, PHP Unit, Composer, NPM and Webpack (and now with setting up PHP CS+MD thanks to this thread). I'll have to remove some company specfic stuff from the thread, but if anyone's interested I can post it here.

PHP in VSCode does have some issues where it "jams" up when debugging and it's trying to lint with CS or MD. But usually you just hit stop and restart the debugger.

itskage fucked around with this message at 15:23 on Mar 15, 2018

Acidian
Nov 24, 2006

Been testing PHPStorm for a bit now, and I really like it. The way the autocomplete works, how it shows me the variables I am inputting in functions and also when I got the run code/debugger working.


itskage posted:

I have a tutorial I give to new hires for setting up nginx+php on windows, with VSCode and the PHP extensions for debugging in VSCode, PHP Unit, Composer, NPM and Webpack (and now with setting up PHP CS+MD thanks to this thread). I'll have to remove some company specfic stuff from the thread, but if anyone's interested I can post it here.

I might be interested? But I don't know what Composer, NPM, Webpack and CS+MD is.

Masked Pumpkin
May 10, 2008

itskage posted:

I have a tutorial I give to new hires for setting up nginx+php on windows, with VSCode and the PHP extensions for debugging in VSCode, PHP Unit, Composer, NPM and Webpack (and now with setting up PHP CS+MD thanks to this thread). I'll have to remove some company specfic stuff from the thread, but if anyone's interested I can post it here.

PHP in VSCode does have some issues where it "jams" up when debugging and it's trying to lint with CS or MD. But usually you just hit stop and restart the debugger.

I interested - hit us up 🙂

Edit: Seriously, I've been using Notepad++ for ages now - Aptana failed after not supporting PHP7, if there's a good IDE I'd like to hear about it!

Masked Pumpkin fucked around with this message at 21:50 on Mar 20, 2018

itskage
Aug 26, 2003


Ahh shoot I've been posting all night and forgot about your replies today. I should be able to post it tomorrow night.

Acidian
Nov 24, 2006

Masked Pumpkin posted:

I interested - hit us up 🙂

Edit: Seriously, I've been using Notepad++ for ages now - Aptana failed after not supporting PHP7, if there's a good IDE I'd like to hear about it!

As a complete newbie on the subject, I can only say that my extensive googling and other threads on this forum seems to indicate that PHPStorm (costs money/free trial) and NetBeans (free) to be the best IDE. The most recommended code editor I have seen is Sublime Text by a good margin, but I have also seen Visual Studio Code recommended by more than just Itskage, and also you are not the only one still using Notepad++. I have been using Sublime Text when I want to install something fast and light weight to code in when I am at a workstations at work, especially when I only want to work in HTML and CSS.

Ranzear
Jul 25, 2013

It's the little stuff like Ctrl+D or shift-RMB selecting that makes Sublime absolutely top tier as a pure editor. It was one of the easiest 'shut up and take my money' decisions for me.

It did take until Sublime 3 for a good php linter to just work out of the box. Getting the package manager into Sublime is still a copy-paste annoyance(?), but then the availability of good stuff just skyrockets.

I know there are packages for class hierarchy and whatnot too.

itskage
Aug 26, 2003


This has become less of a "copy the guide from these mark down files" and more of a "Retype the jist of stuff into a forums post". Sorry but there's more company specific stuff in them than I remembered, and it was quite long and I was fighting with the lack of md formatting, so I cut it down a lot, and now it is like a text dump, but hopefully it's useful to someone.

To be clear this is for windows.

Install NGINX
  1. Download the NGINX/Windows binaries http://nginx.org/en/download.html
  2. Make a folder for nginx and unzip there E.g.: C:\nginx\
  3. Run nginx.exe to start. You can verify installation by going to http://localhost/ and you should get the nginx welcome page.

Some notes:
If you have something else listening on 80 (XAMPP IIS Express) then you need to stop it or configure NGINX to listen on another port.
To stop NGINX after running it this way you have to taskkill it.

Install PHP
  1. Download the PHP binaries for windows. http://php.net/downloads.php
  2. Extract them to a folder. E.g.: C:\php\
  3. Start PHP and listen on 9000 `c:\PHP\php-cgi.exe -b 127.0.0.1:9000

Test PHP
In nginx's folder /conf/nginx.conf un-comment the php location, and alter the SCRIPT_FILENAME per below.
code:
     # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

     location ~ \.php$ {
       root           html;
       fastcgi_pass   127.0.0.1:9000;
       fastcgi_index  index.php;
       fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
       include        fastcgi_params;
     }
- This is telling NGINX that any requests ending in .php should be forwarded to PHP and for PHP to execute the file at $document_root + relative path to the file.
- Add a test phpfile to the nginx root E.g.: nginx/html/phpinfo.php with
code:
<?php phpinfo();
- Restart the nginx process to load the changes.
- Now you should see php info when you navigate to http://localhost/phpinfo.php

Tweaking configs
Now I have a bunch of poo poo about tweaking nginx.conf, sites-available/yourside.conf and php.ini for our CMS and whatnot, that I won't touch here. NGINX is like apache with sites-availabe and sites-enabled and with that above snippet getting phpinfo working you should be able to figure it out, otherwise just ask.

Some stuff I will mention:
- Setup your SSL and hostnames if you are developing with https (which I don't know why you wouldn't in tyool 2018)
- Change your the root for your site in NGINX unless you plan to workout of C:\nginx\html or wherever you installed it.
- in php.ini be sure to uncomment any extensions you need (and ensure you have the .dlls for them in php\ext\) so like if you need curl just uncomment extension=php_curl.dll in the ini.
- Xdebug will be needed to debug in VSCode (does any IDE not need this?): dump your phpinfo() output into https://xdebug.org/wizard.php and it should result in you downloading a dll that you put in php\ext\ and then referencing in php.ini (zend_extension = php_xdebug-2.5.4-7.0-vc14-x86_64.dll)
- Confgure Xdebug in PHP ini. You can google a bunch of the options but minium I do this for local development:
code:
[debug]
; Always xdebug
xdebug.remote_autostart=1 
; Enable...
xdebug.remote_enable=1
; Debug at the start of every request
xdebug.remote_mode=req
; What host to send debugging info to (your local)
xdebug.remote_host=127.0.0.1
; Port to connect to VSCode on... be sure this is not your PHP port!
xdebug.remote_port=9001
; Auto start can be disabled and this can be enabled if you want to use a browser extension to enable/disable debugging, (from any machine even) but since it's local I don't see the point.
xdebug.remote_connect_back=0
Working files
Next I have directions about git cloning our projects down. It should be the same. Clone yours to where you set your NGINX site's root, (I'll just use C:\nginx\html\ for this). Once done or if starting from scratch you can open a workspace in vscode there. (ctrl+k ctrl+o). VSCode also has bulit in terminal (ctrl+`) so you can just run git commands there, or use the built in commands (F1 to open the command pallet, type git clone, follow prompts).

At this point if you have your site in the folder and all of your site's configs and any database connections or anything configured then your site should run under localhost (or if you need a hostname to serve multiple sites from one CMS like I do you can overwrite your hosts file).

Last thing is unless you want to run NGINX and PHP locally as a service (I don't) you will want something to start and stop them, so here's a bat file that kills any running nginx and php processes and then restarts them (and leaves the window open).
code:
@ECHO OFF

taskkill /f /IM nginx.exe
cd c:\nginx
start nginx

taskkill /f /IM php-cgi.exe
cd c:\php

Echo running php...
c:\php\php-cgi.exe -b 127.0.0.1:9000
You can add a task in vscode if you'd rather run that from the IDE.

Anyway that's the most rudimentary way to run NGINX and PHP locally on windows.


VS Code part:
Basic PHP support:
You still need PHP downloaded even if not running it locally because you will need to point your extensions at the .exe.
Microsoft will recommend you the: https://marketplace.visualstudio.com/items?itemName=felixfbecker.php-pack which includes the debugger and IntelliSense, but I wasn't big on the intelliSense. Fortunatley you can get them seperately, so for me I just grab the debugger. https://marketplace.visualstudio.com/items?itemName=felixfbecker.php-debug
Then instead I use Intelephense: https://marketplace.visualstudio.com/items?itemName=bmewburn.vscode-intelephense-client
Now you have to add some user/workspace settings (ctrl+,). I recommend putting these php specific things into workspace so they aren't trying to phpmd my node.js projects or dotnet core.
code:
    "php.suggest.basic": true, (disabling this will stop the double suggestions from the native VSCode's and the intelephens/IntelliSense)
    "php.validate.enable": true,
    "php.validate.run": "onSave", (I haven't tryied onType, but I'm constantly hitting ctrl+s from years of doing this so...)
    "php.validate.executablePath": "C:\\php\\php.exe", (or wherever you installed)
VS Code is pretty good and will autocomplete options and what not if you want to play with the settings.

Debugging:
This should work now, so open the debugging pane (ctrl+shift+d) then up at the top you have some profiles. Click the gear to get started and edit some:
Here's the most basic:
code:
 
     {
            "name": "Local",
            "type": "php",
            "request": "launch",
            "port": 9001,
            "pathMappings": {
                "C:/nginx/html/" : "${workspaceRoot}"
            }
        },
Listens on port 9001 for xdebug. Just set a break point in your index.php or wherever is easy to test, hit F5 to start debugging the current profile, and then open that page in a browser and it should halt on your breakpoint.

I keep four profiles: local, remote (to debug a test server), tests (to halt on exceptions when running a bunch of tests), and current file (which I think is built in and is quite useless to me since we use a CMS with a dispatcher).

Composer:
https://getcomposer.org/download/ (recommend just using the EXE)
There is a VS Code extension. You don't need it, but it adds composer commands to the command pallet, and will validate your composer.json so I recommend it: https://marketplace.visualstudio.com/items?itemName=ikappas.composer
Back to workspace settings (crtl+,):
code:
    "composer.enabled": true,
    "composer.executablePath": "C:\\ProgramData\\ComposerSetup\\bin\\composer.bat",
If you have a composer.json in your project. You should be able to run composer install now (ctrl+` composer install to do it from the command line, or F1 composer install to do it from the command pallet). If not you will need to make one (and the necessary git/vcs exclusions).

Anyway add and run composer install/update and it should install PHPMD, PHPCS, and PHPUnit with a Code coverage plugin.
code:
    "require-dev": {
        "phpmd/phpmd" : "@stable",
        "squizlabs/php_codesniffer": "3.*",
        "phpunit/phpunit": "@stable",
        "phpunit/php-code-coverage": "@stable"
    },
You can generate xml for PHPMD and PHPCS rules easily here with this:
http://edorian.github.io/php-coding-standard-generator/#phpcs
You can even paste your XML back in later if you need to make adjustments

PHPCS: https://marketplace.visualstudio.com/items?itemName=ikappas.phpcs
This is the less finicky of the two linters.
Workspace settings:
Where to find the rules to enforce, and where the cs script is. You're SUPPOSED to be able to go to vendor/bin/phpcs for this instead of the full path but that never worked for some reason.
code:
    "phpcs.standard": ".\\phpcs.xml",
    "phpcs.executablePath": "vendor/squizlabs/php_codesniffer/bin/phpcs",
PHPMD: https://marketplace.visualstudio.com/items?itemName=ecodes.vscode-phpmd
There's a couple of these. As of about August of last year that one was the best one, but PHPMD still tends to jam up sometimes on large projects/files espcially when the debugger is running.
If you notice this, just restart the debugger. You can also see at the bottom stuff like "PHP is linting document..." with a spinner and it hangs. Usually restart the debugger fixes that too.
What I think is the process to lint is getting locked behind an actual request you want to debug for some reason, and even though you finish in the GUI, VSCode debugger isn't communicating that back, and it just gets stuck. If someone knows better, by all means, please share.
code:
    "phpmd.verbose": true,
    "phpmd.rules": ".\\phpmd.xml",
If you don't use verbose then it doesn't tell you what rule the line is violating.

Once you get those setup you can see what horrors are lurking in the code base you've inherited:
The function getConfigJSONResponse() has an NPath complexity of 1773066240. The configured NPath complexity threshold is 200.
The function getConfigJSONResponse() has a Cyclomatic Complexity of 74. The configured cyclomatic complexity threshold is 10.
:allears:

PHP Unit: https://marketplace.visualstudio.com/items?itemName=emallin.phpunit
Only needed if you want to run tests in VSCode while developing.
code:
    "phpunit.execPath": ".\\vendor\\bin\\phpunit.bat",
    "phpunit.args": [
        "--configuration", ".\\Tests\\phpunit.xml",
        "--coverage-text=.\\Tests\build\\coverage.txt"
    ],
    "phpunit.preferRunClassTestOverQuickPickWindow": false, // Default false
Not going to cover the phpunit.xml and setup of tests unless someone needs it.

To run tests in VS Code hit F1 and type PHPUnit Test with nothing open or selected will run all tests in the listed configuration.
With a test file/case open and selected hit F1 and type PHPUnit Test to run all tests for that file.
To run a specific test, double clock the function to highlight it, then do the F1 type PHPUnit Test (this autocompletes after the first time) and then it will just run that single test.


Webpack:
Be sure you've installed node and npm. I'm assuming you know what this is and how it works outside of VSCode. If not, ask but don't just add it because it's here.
Then open a terminal and npm install webpack, or I recommend using a package.json for your project:
code:
{
    "name": "",
    "version": "",
    "description": "",
    "dependencies": {
        "webpack": "3.10.0"
    }
}
Then just npm install.

Now you just make a webpack.config like any other webpack project, and the cool thing is you can just make some tasks to run this for you:
Under Tasks -> Configure Tasks...
You can add these:
code:
        {
            "label": "webpak build",
            "type": "shell",
            "command": "${workspaceRoot}/node_modules/.bin/webpack",
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "args": [
                "--colors",
                "--progress"
            ]
        },
        {
            "label": "webpak watch",
            "type": "shell",
            "command": "${workspaceRoot}/node_modules/.bin/webpack",
            "args": [
                "--colors",
                "--progress",
                "--watch"
            ]
        }
First one just runs a build. But you can have that set as default so it auto builds whenever you run a build task which you can even have it do when you start the debugger.
2nd one adds --watch so it will auto update with any changes you make.

Probably would be better breaking it down into multiple posts (it's 3 different guides in our private github) but there you go.

Summary
Anyway it's a bit janky for PHP, but it works fine when you know the quirks. I think NGINX+php-fpm is better than apache-php and VS Code is the best IDE in general. So if this helps some people try it out then great.

If you're like me and jump between dotnet core and node as well as PHP (and frontend js) then it's nice just being in one IDE. It's not perfect (sometimes even for dotnet core I have to open VS2017), but I like it.

Finally one last thing is you can now write the js for your PHP site in here with ts which has fantastic vs code support.

itskage fucked around with this message at 22:47 on Mar 21, 2018

Masked Pumpkin
May 10, 2008

itskage posted:

:words: Fantastic Advice™ :words:

This is a Good Post™ - thank you! I've always been leery of running PHP locally since I've got dev and prod servers I work off of, but having PHP running locally for error checking makes sense.

Edited for brevity since the original post is right above this one and this isn't the old E/N.

Masked Pumpkin fucked around with this message at 17:19 on Mar 28, 2018

Pile Of Garbage
May 28, 2007



Someone add that to the op it's great. Btw Masked Pumpkin you don't have to quote posts in their entirety, that's why :words: exists, a fun placeholder.

Ranzear
Jul 25, 2013

Should maybe establish that that's for a development environment too, lest I see it crop up as the backend for a mobile game API.

Because that'd be par for the course.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


cheese-cube posted:

Someone add that to the op it's great. Btw Masked Pumpkin you don't have to quote posts in their entirety, that's why :words: exists, a fun placeholder.

Someone? I have a name you know :p

Edit: man, it's been awhile since I looked at that OP, its got a bit of dust on it.

Adbot
ADBOT LOVES YOU

Masked Pumpkin
May 10, 2008

cheese-cube posted:

Someone add that to the op it's great. Btw Masked Pumpkin you don't have to quote posts in their entirety, that's why :words: exists, a fun placeholder.

Good point - fixed :)

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply