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
DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!
Is there a published method for verifying Goon accounts on SA from our own web apps?
I'm interested in an automated method for verifying SA Goon signups.

Adbot
ADBOT LOVES YOU

IT BEGINS
Jan 15, 2009

I don't know how to make analogies

Mister Chief posted:

Why not just use a foreign key?

I'm not sure how I'd do this. I don't have a 1:1 relationship between any of my fields. Sometimes the invoice fields will match shipment fields, sometimes they will be random unrelated numbers.


a lovely poster posted:

This sounds like something that should be taking place in the query/orm. You shouldn't be using PHP to meld multiple tables into one dataset unless you really have to.

I see. I was hoping to avoid a huge SQL but I suppose it is much faster and definitely cleaner than a bunch of conditionals.

Mister Chief
Jun 6, 2011

Vasja posted:

I'm not sure how I'd do this. I don't have a 1:1 relationship between any of my fields. Sometimes the invoice fields will match shipment fields, sometimes they will be random unrelated numbers.

My question is why was the database schema designed that way?

a lovely poster
Aug 5, 2011

by Pipski
My guess is that it probably isn't, especially if it's an eCommerce application. Or he's just stumbled into the largest coding horror we've seen in a while (granted it's PHP, let's not count that out)

What platform are you working with Vasja?

IT BEGINS
Jan 15, 2009

I don't know how to make analogies
I'm working with a fairly large parcel shipping and analytics app, running PHP/Postgres. It's definitely a coding horror (see my posts in that thread), but this part is mostly a result of the fact that the data feeds we get are inconsistent and sometimes hand-created from paper invoices. A horrible system, yes, but that's why we exist - we convert that horrible poo poo to a single consistent set of data.

Bastard
Jul 13, 2001

We are each responsible for our own destiny.
Sounds exactly what the Data Mapper pattern is for, so if you were doing that, I'd keep doing that.

a lovely poster
Aug 5, 2011

by Pipski

Vasja posted:

I'm working with a fairly large parcel shipping and analytics app, running PHP/Postgres. It's definitely a coding horror (see my posts in that thread), but this part is mostly a result of the fact that the data feeds we get are inconsistent and sometimes hand-created from paper invoices. A horrible system, yes, but that's why we exist - we convert that horrible poo poo to a single consistent set of data.

So are you taking all the poo poo sources and compiling them into a database, or taking a bunch of different tables in the database and compiling them into a single data set? Ideally an ORM would be handling the data import from source into database. But if you really just a crazy database filled with tons of different tables that all look different, hell, I might try to set up a new database to use as a source for your consistent sets of data. Either way, pulling a ton of different arrays into PHP and using different methods on each of them to get the correct output is probably going to look pretty drat ugly no matter what you do.

Best of luck goon, keep us posted. Can I ask whether it's something from an outside vendor or built in house?

IT BEGINS
Jan 15, 2009

I don't know how to make analogies
Thanks for the help so far guys :)

a lovely poster posted:

So are you taking all the poo poo sources and compiling them into a database, or taking a bunch of different tables in the database and compiling them into a single data set? Ideally an ORM would be handling the data import from source into database. But if you really just a crazy database filled with tons of different tables that all look different, hell, I might try to set up a new database to use as a source for your consistent sets of data. Either way, pulling a ton of different arrays into PHP and using different methods on each of them to get the correct output is probably going to look pretty drat ugly no matter what you do.

Best of luck goon, keep us posted. Can I ask whether it's something from an outside vendor or built in house?

Basically, I've only got two table to worry about - a table for invoice data, and a table for shipment data. My code is supposed to create the junction table between these two (along with calculating some derived fields). However, I don't have a strict foreign key relationship - 1-3 fields on the left will match 1-2 fields on the right. I supposed I could extract just these specific fields (?) into their own table so I could join on them, but, like you said, it's likely going to be ugly.

Edit: Yeah, we've already got something that converts a bunch of really horrible data into somewhat consistent invoice and shipment data. However, it doesn't go so far as to completely normalize that data, hence this code.

IT BEGINS fucked around with this message at 05:18 on Oct 3, 2013

IT BEGINS
Jan 15, 2009

I don't know how to make analogies
So... one more, somewhat related question, though it is more abstract.

I've got a small but somewhat complex system of classes, and writing some tests for one of them is somewhat difficult. I suspect that my design is incorrect, but I'm not sure how. Here is the system in question:



php:
<?
class InvoiceLevelProrater
{
    protected Mapper $chargeMapper;
    protected Mapper $detailMapper;
    protected Mapper $shipmentMapper;
    protected Distributor $distributor;
    protected Builder $detailBuilder;

    public function __construct(...) { ... }

    public function prorate(Invoice $invoice)
    {
        $charges = $this->chargeMapper->findAll($invoice);
        $shipments = $this->shipmentMapper->findAll($invoice);
        foreach ($charges as $charge) {
            $distributedCharges = $this->distributor->distribute($charge->getCharge(), mpull($shipments, 'getProrateField'));
            foreach ($shipments as $shipment) {
                $detail = $this->detailBuilder->getDetail($charge, $shipment, array_shift($distributedCharges));
                $this->detailMapper->save($detail);
            }
        }
    }
}
?>
It's not a perfect recreation - some of the names are different, but this is the gist of it. Basically, my main trouble is that I have to mock out a bunch of stuff to test the prorate method: all of the dependencies, and some safe things for them to return. Am I perhaps doing too much in this class? Is this normal for complex classes with more than a couple dependencies?

The logic I am trying to encapsulate is that we must distribute charges in a specific way across the shipments for an invoice. I could pass the charges and shipments in directly, but I am preparing for another class in which shipments are pulled per-charge instead of per-invoice. I could also return the details, or yield them via a generator, but I am stuck in 5.3 and am limited by memory - sometimes I will have a dozen charges and several thousand shipments.

I'm also not sure if this is the right place to ask this question, but I figured I'd give it a shot.

Splinter
Jul 4, 2003
Cowabunga!
Anyone have recommendations for a good book and/or online (at your own pace) course for learning PHP for someone who already has programming and CS experience?

Robot Arms
Sep 19, 2008

R!
I want to make sure my theme busts visitors' caches whenever I update my WordPress site. It seems like the easiest way to do this would be to add something like "?year-month-day-hour-minute" to the stylesheet reference in the head. In other words, I want it to look something like this:

code:
<link rel="stylesheet" href="http://robots.samglover.net/wp-content/themes/lawyerist-wp/style.css?2013-10-21-22-53" type="text/css" media="screen, projection">
Here's how I'm trying to go about that:

code:

<link rel="stylesheet" href="<?php echo get_stylesheet_uri() . '?' . date ( "m-d-Y-H-i-s", filemtime( get_stylesheet_uri() ) ); ?>" type="text/css" media="screen, projection">
But it's not working. Apparently, filemtime doesn't think the stylesheet URL is the right path to the file. (I would post this in the WordPress thread, but it seems more like a PHP question.)

Thanks for help.

Impotence
Nov 8, 2010
Lipstick Apathy
filemtime requires a filesysetm path, not a http url

PleasantDilemma
Dec 5, 2006

The Last Hope for Peace
So Laravel and FuelPHP frameworks have a cool thing called Migrations that make it easy to keep database changes in your source code. Is there a PHP migration system that's independent of frameworks? Also are systems like this used in web frameworks in other languages?

crabrock
Aug 2, 2002

I

AM

MAGNIFICENT






DarkLotus posted:

Is there a published method for verifying Goon accounts on SA from our own web apps?
I'm interested in an automated method for verifying SA Goon signups.

I'm also interested in this. I was told to check out authdb from Rich, but apparently alluvion.org no longer exists?

McGlockenshire
Dec 16, 2005

GOLLOCKS!

PlesantDilemma posted:

So Laravel and FuelPHP frameworks have a cool thing called Migrations that make it easy to keep database changes in your source code. Is there a PHP migration system that's independent of frameworks? Also are systems like this used in web frameworks in other languages?

I've never encountered a generic one, mainly because everyone does database connections differently.

It's not hard to roll your own. The one we use at work is pretty simple.

  1. Create a directory structure. Say, directories named maintenance/database_updates/1.1, maintenance/database_updates/1.2, etc.
  2. Sort the directory list using semantic versioning.
  3. Each directory has a number of numerically-sequenced files, such as 001_ticket-208-fix-texas-taxes.sql, 002_ticket-2-new-configuration-tables.php, etc.
  4. Sort each version and each file
  5. Keep track of the file versions and numbers that have been run in a table in the db
  6. Run every file that hasn't been run so far. SQL files get intelligently split along semicolons, PHP files just get include()'d and inherit the context including the current database connection and whatnot.
  7. If running on a database engine that supports DDL inside transactions (which basically means not MySQL or SQLite), run each individual file inside a transaction from the script that does the executing.

Just stick the directories in the repo and make sure that your dev environment matches your live environment and you're good to go. We actually restore last night's database backup to the dev instances every day, minus sensitive information. This means that we know that the thing we're using is as close to live as possible in every way.

This only takes care of things that go from version A to version B. A lot of the modern frameworky things can also build logic to do reverse migrations.

McGlockenshire fucked around with this message at 07:16 on Oct 22, 2013

jony neuemonic
Nov 13, 2009

PlesantDilemma posted:

So Laravel and FuelPHP frameworks have a cool thing called Migrations that make it easy to keep database changes in your source code. Is there a PHP migration system that's independent of frameworks? Also are systems like this used in web frameworks in other languages?

I think Doctrine can do this without a framework: Doctrine Migrations. I've never used it though, so I don't know for sure or if it works well.

Migrations definitely exist in other languages. Rails has them built-in through ActiveRecord, based on some quick googling it looks like Django now has them built-in as well.

Baby Nanny
Jan 4, 2007
ftw m8.

crabrock posted:

I'm also interested in this. I was told to check out authdb from Rich, but apparently alluvion.org no longer exists?

https://gist.github.com/Ell/6237109

Not php but I wrote this super simple profile scraper in python that I guess you could call externally in your php script. The class returns a profile dictionary with values for all profile fields that you can then check against your sites code that randomly generates an auth code or whatever. Shouldn't be that hard to port to php either really if you wanna go that route

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.

PlesantDilemma posted:

So Laravel and FuelPHP frameworks have a cool thing called Migrations that make it easy to keep database changes in your source code. Is there a PHP migration system that's independent of frameworks? Also are systems like this used in web frameworks in other languages?

Yup, everyone uses migrations. It's the only way to somewhat sanely keep your database in check when working with a team (I've seen when teams don't use migrations and it's a mess).

I wrote a framework independent migration tool a LONG time ago. It doesn't comply with a lot of the recent changes in the PHP ecosystem, but it should still work to the best of my knowledge.

https://github.com/leftnode/dbmigrator

You might also check Packagist for some generic migration tools that are a bit more up to date.

LP0 ON FIRE
Jan 25, 2006

beep boop
For some reason I can't get a file upload error to trigger. I don't have it uploading yet, just checking stuff about the file.

code:
	// Product Name

	$productName = $_POST["productName"];

	if ($productName == "") {
	    $productName_errorMessage = "Please enter a Product Name."; //this works
		$formError = TRUE;
	}

	// Description

	$description = $_POST["description"];

	if ($description == "") {
	    $description_errorMessage = "Please enter a description."; //this works
		$formError = TRUE;
	}

	$allowedExts = array("jpeg", "jpg", "png");
	$temp = explode(".", $_FILES["productBG"]["name"]);
	$extension = end($temp);

	if ((($_FILES["productBG"]["type"] == "image/jpeg")
	|| ($_FILES["productBG"]["type"] == "image/jpg")
	|| ($_FILES["productBG"]["type"] == "image/png"))
	&& ($_FILES["productBG"]["size"] < 1536)
	&& in_array($extension, $allowedExts)){

		if ($_FILES["productBG"]["error"] > 0){

			echo "error!!!";

			$productImage_errorMessage = $_FILES["productBG"]["error"] . "<br>"; //this DOES NOT work
			$formError = TRUE;

		}

	}
This part of the script is run when the form is submitted. The productName and description will create the errors if needed, but the file upload does not. The input field is simply <input type='file' name='productBG'>

I'm basing this off of this tutorial: http://www.w3schools.com/php/php_file_upload.asp

jony neuemonic
Nov 13, 2009

LP0 ON FIRE posted:

For some reason I can't get a file upload error to trigger. I don't have it uploading yet, just checking stuff about the file.

This part of the script is run when the form is submitted. The productName and description will create the errors if needed, but the file upload does not. The input field is simply <input type='file' name='productBG'>

I'm basing this off of this tutorial: http://www.w3schools.com/php/php_file_upload.asp

Are you using enctype="multipart/form-data" on your form tag?

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Never, ever, ever trust anything you read on w3schools about PHP! It's complete pure and utter poo poo that never gets updated and teaches obsolete, insecure, objectively incorrect practices.

For example, you can't trust that the file extension and MIME type provided by the uploader are correct. If you want to do image validation, validate the MIME type using exif_imagetype or mime_content_type or the finfo_ functions depending on what's available in your PHP version, then use getimagesize to make sure it's even more of a real image.

LP0 ON FIRE
Jan 25, 2006

beep boop

Yes, but for some reason I typed a "}" next to it for some reason! Thanks for making me look there. ;)


McGlockenshire posted:

Never, ever, ever trust anything you read on w3schools about PHP! It's complete pure and utter poo poo that never gets updated and teaches obsolete, insecure, objectively incorrect practices.

For example, you can't trust that the file extension and MIME type provided by the uploader are correct. If you want to do image validation, validate the MIME type using exif_imagetype or mime_content_type or the finfo_ functions depending on what's available in your PHP version, then use getimagesize to make sure it's even more of a real image.

Thanks very much. I'll be very careful about this and read up about it.

It's really obvious just by looking at it but for some reason I didn't see the condition didn't make sense. It will never be able to check if the error is greater than 0 if the conditions outside of it are false. So that was a problem.

Mister Chief
Jun 6, 2011

You also want to have lines in your htaccess preventing image files from being executed as anything but images. It's possible to have an image pass all kinds of tests but embed PHP code inside of it and have it run on the server.

LP0 ON FIRE
Jan 25, 2006

beep boop

Mister Chief posted:

You also want to have lines in your htaccess preventing image files from being executed as anything but images. It's possible to have an image pass all kinds of tests but embed PHP code inside of it and have it run on the server.

Can you do this without a php extension? I've created php files with mime types of image files (they even work on the forums) but not files with an image extension with php code inside it.

Mister Chief
Jun 6, 2011

This page covers most things you should know: http://nullcandy.com/php-image-upload-security-how-not-to-do-it/

Peanut and the Gang
Aug 24, 2009

by exmarx

Oooo. I've never thought of using __halt_compiler() before. That's cool.

stoops
Jun 11, 2001
I have this $lines array:

code:
 array(
	(int) 0 => 'NeI     736 0.0000000117',
	(int) 1 => 'NeI     743 0.00000000108'
}
Each element should be separated. (NeI, 736, 0.000), so when I render my view, I can put each into it's own separate column in a table.

I'm just not sure how to achieve that.

Googling, I tried to do start something like this:

code:
foreach ($lines as $line) {
    $parts = explode(" ", $line);
    debug($parts[0]);
    debug($parts[1]);
    debug($parts[2]);
}
But it gave me a "reflectionClass" error, which I wasn't sure about.

Any help is appreciated.

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.
Should each element be separated by a comma and a space, or should they be separate array elements?

php:
<?php

$array = [
    'NeI     736 0.0000000117',
    'NeI     743 0.00000000108'
];

$results = [];

foreach ($array as $line) {
    $bits preg_split('/[ ]+/'$line);
    $results[] = array_map('trim'$bits);
}

print_r($results);

/*
Array
(
    [0] => Array
        (
            [0] => NeI
            [1] => 736
            [2] => 0.0000000117
        )

    [1] => Array
        (
            [0] => NeI
            [1] => 743
            [2] => 0.00000000108
        )

)
*/

stoops
Jun 11, 2001

musclecoder posted:

Should each element be separated by a comma and a space, or should they be separate array elements?

This is exactly what I wanted. Thanks a lot. (I'll look up preg_split and array map so I can get a better idea for next time.)

Thanks again.

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.
Sure thing.

The issue with explode() is that all of the spaces between NeI and the 736 would be separate array elements, which you don't want to spend the time to remove. preg_split() was used to split on any space one or more times.

Looking and testing it further, the array_map() and trim() aren't necessary, you can remove them.

stoops
Jun 11, 2001
I'm trying to get a range of elements from this array.

code:

(int) 0 => '0001.gif',
(int) 1 => '0002.gif',
(int) 2 => '0003.gif',
(int) 3 => '0004.gif',
(int) 4 => '0005.gif',
(int) 5 => '0006.gif', etc

(int) 235 => '236.gif',

If someone wants the gifs from 10 to 15, I want my new array to be

code:
(int) 0 => '00010.gif',
(int) 1 => '00011.gif',
(int) 2 => '00012.gif',
(int) 3 => '00013.gif',
(int) 4 => '00014.gif',
(int) 5 => '00015.gif'
I tried to use array_slice, but I wasn't sure how to get the end number of the elements.

I guess I can subtract my start and end and use that as the length for array_slice, but I feel I'm not doing it as well as it could be done.

I did see a range function but it didn't look like that's what I needed.

Any help or point to the right direction is appreciated.

The Laplace Demon
Jul 23, 2009

"Oh dear! Oh dear! Heisenberg is a douche!"
What exactly is wrong with array_slice($myArray, 10 - 1, 15 - 10 + 1)? This is exactly what it's supposed to be used for.

EDIT: VVV Oh, well you're definitely going about it correctly. :)

The Laplace Demon fucked around with this message at 21:11 on Oct 29, 2013

stoops
Jun 11, 2001

The Laplace Demon posted:

What exactly is wrong with array_slice($myArray, 10 - 1, 15 - 10 + 1)? This is exactly what it's supposed to be used for.

Nothing was wrong. I just didn't know if I was going about it the right way.

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker

stoops posted:

Nothing was wrong. I just didn't know if I was going about it the right way.

Well you are assuming that the array will be ordered and no image would be missing or duplicated. Otherwise, I'd use array_filter to make it more robust.

silentpenguins
May 9, 2013

Abysswalking
Hey, didn't see a drupal thread so posting this here. Does it make a big difference to call variable_get multiple times on the same variable that's not going to change in the same code, or is it better to define a global? Not sure if drupal has some sort of caching so it wouldn't matter. Version is drupal 7 by the way.

spacebard
Jan 1, 2007

Football~

silentpenguins posted:

Hey, didn't see a drupal thread so posting this here. Does it make a big difference to call variable_get multiple times on the same variable that's not going to change in the same code, or is it better to define a global? Not sure if drupal has some sort of caching so it wouldn't matter. Version is drupal 7 by the way.

Variables are cached so there's no database performance hit.

Ophidia
Oct 20, 2012
I have a Symfony question: how do I get the current Controller and Action?
I have a BaseController with a preExecute function and in this BaseController I need to find out the current controller and action. Google search led me to a page which suggested using $request->attributes->get('_controller') and filtering out the desired values with preg_match.
There HAS to be a better way to do this, right?

IcedPee
Jan 11, 2008

Yarrrr! I be here to plunder the fun outta me workplace! Avast!

FREE DECAHEDRON!
I hope this is the right thread for this.

I'm completely new to PHP. I've done plenty of C/C++/C# and a fair amount of ASP.NET and MVC, etc etc, and I got roped into working on a project with PHP and MySQL. I'm from an almost exclusively Microsoft background, and the hosting we're using is a LAMP stack. I'm setting up a testing environment to run through a few tutorials on my computers at home, and my question is this: should I bother setting up Apache on my Win7 box, or should I just configure PHP and MySql to work through IIS? Would the experience of using Apache on a Win7 box help at all when our hosting is all Linux, or has cross-platform publishing finally gotten painless?

McGlockenshire
Dec 16, 2005

GOLLOCKS!

IcedPee posted:

should I bother setting up Apache on my Win7 box, or should I just configure PHP and MySql to work through IIS? Would the experience of using Apache on a Win7 box help at all when our hosting is all Linux, or has cross-platform publishing finally gotten painless?

Unfortunately the answer is a big fat "it depends."

If the code you're working on is based on third party commercial (or OSS) software, then you should be fine on IIS. If it was originally developed in-house but knowing it would run cross-platform, then you should be OK. If it's a small application (dozens of files), you'll probably be OK but might encounter little things that are subtly wrong but fixable.

If it's a large application (hundreds of files), or the original developers did not expressly go out of their way to make sure it was safe to run cross-platform, then you might be making a mistake. If the PHP version on the server differs too much from the PHP version you're intending to install, you're going to have problems. If the PHP version on the server is lower than 5.3, then setting it up with IIS is going to be a real pain in the rear end.

The biggest problem isn't actually IIS vs Apache, it's Linux vs Windows. There are a handful of PHP functions and extensions which simply aren't available on Windows. Similarly, while most functions and extensions are perfectly fine cross-platform, if you're sloppy in their use, you can find yourself with code that isn't portable. Worse, there are things (like the document root and other things in $_SERVER) that can differ between servers regardless of platform, and over-reliance on those things without understanding that they might be different on other machines can also produce portability problems.

If you can, you should make your dev environment as close to the production environment as possible. If things don't immediately work under Windows and IIS, you might consider creating a Linux VM on your Windows machine using the correct distro and PHP version and simply working on it there. Of course, as you're more familiar with the Windows stack, this is going to come with a higher learning curve.

Adbot
ADBOT LOVES YOU

Sulla Faex
May 14, 2010

No man ever did me so much good, or enemy so much harm, but I repaid him with ENDLESS SHITPOSTING

IcedPee posted:

I hope this is the right thread for this.

I'm completely new to PHP. I've done plenty of C/C++/C# and a fair amount of ASP.NET and MVC, etc etc, and I got roped into working on a project with PHP and MySQL. I'm from an almost exclusively Microsoft background, and the hosting we're using is a LAMP stack. I'm setting up a testing environment to run through a few tutorials on my computers at home, and my question is this: should I bother setting up Apache on my Win7 box, or should I just configure PHP and MySql to work through IIS? Would the experience of using Apache on a Win7 box help at all when our hosting is all Linux, or has cross-platform publishing finally gotten painless?

As someone who is now struggling with a Windows/MSSQL server deployment I'd say do yourself a favour and just run a Linux install on virtualbox, and use that. If you have spare cash, rent a dedicated linux server from OVH for like $15/mo and muck around with that. The only issue is that if you gently caress something, they'll just re-install from scratch, which might take a little while.

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