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!

Golbez posted:

Oh, well yeah, that would seem to me to be bad form. Especially if it's something easily deciphered like that, "Hm this form key is always the SHA1 of my session ID!"

It doesn't stop a logged in user from doing anything, it prevents CSRF. That is the only thing it does since the session variable is not known to a 3rd party.
It simply helps prevent this from happening:

Glory of Arioch posted:

A CSRF (cross-site request forgery) is an attack that lets third-party sites run commands on behalf of a user on your site.

An overly simplified example:
You are a bank, and you have a form that allows you to transfer money to another person. The form is invoked by the following URL: /transfer.php?to=IntendedUser&amount=100 . A third party site can rewrite that URL to be ?to=EvilHacker&amount=1000, drop it in an iframe, and embed it in a page with high traffic or an advertisement. The way it works is that if your cookie is still active on the bank site, the iframe loads the page and sends the request without the user knowing, which harvests $1000 from their account.

The way to defeat these requests is to include a token along with the request. E.g.: /transfer.php?to=IntendedUser&amount=100&csrf_token=skdfhslkfhsdahfds . The token is stored in the user's session, server side, and is included in the form when it's rendered to the user. When the form is submitted by the user, the submitted token is compared to the value in the session. If they match, the request is legit and the transfer goes through. A person designing an IFRAME with the malicious request cannot predict the contents of that token, and as such cannot use it to execute commands on the behalf of another user.

DarkLotus fucked around with this message at 21:20 on Oct 31, 2012

Adbot
ADBOT LOVES YOU

bobthecheese
Jun 7, 2006
Although I've never met Martha Stewart, I'll probably never birth her child.
The way my bank handles it, for example, is that it generates single-use keys for all actions. So, I assume, they store the "next action" key on the user's session, and attach the key into every link and form possible. If the passed key doesn't match the one in the session, then they reject the request and log the user out. On every successful request, they generate a new "next action" key.

The problem with this (like many of you will probably have realized already), is that you can't use the back-button or refresh. For a bank, that's not too bad - they provide 'safe' back and refresh buttons in the page, and I'm sure that I'm not going to accidentally trigger off multiple transactions by hitting back or refresh.

The other problem is that you can't have two browser windows open without having two separate sessions.

False Toaster
Dec 29, 2006

Stupidity, its both physically and mentally painful.
Cross posting, since I could not initially find the thread.
http://forums.somethingawful.com/showthread.php?threadid=2779598&pagenumber=230#post409145797

Viggen
Sep 10, 2010

by XyloJW

Your Joomla code looks, well, like Joomla.

You are doing a select *, rather than which fields, and no order; loadObjectList() works like mysql_fetch_array(), so I'm a bit confused what your issue is. Have you done a var_dump($jintrows) to see what's in there?

Zamujasa
Oct 27, 2010



Bread Liar

bobthecheese posted:

The way my bank handles it, for example, is that it generates single-use keys for all actions. So, I assume, they store the "next action" key on the user's session, and attach the key into every link and form possible. If the passed key doesn't match the one in the session, then they reject the request and log the user out. On every successful request, they generate a new "next action" key.

The problem with this (like many of you will probably have realized already), is that you can't use the back-button or refresh. For a bank, that's not too bad - they provide 'safe' back and refresh buttons in the page, and I'm sure that I'm not going to accidentally trigger off multiple transactions by hitting back or refresh.

The other problem is that you can't have two browser windows open without having two separate sessions.

You can get around this by only checking the "next request" key on actions that would reliably need it. Alternatively, store a different key, that would expire after some amount of time (10 minutes?), and if that expires, then log them out.

Breaking the open-in-new-tab and such features is a terrible design flaw.

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

I'll do a cross post too since I didn't get an answer in the Wordpress thread:
---
Anybody encounter any recent WP security problems? I've got a friend's site that keeps getting exploited. I've got his WP at 3.4.2, and have removed all plugins, and poo poo still goes wrong. Basically every night someone gets in and changes the mysql database account's password (and does nothing else). I was looking at the logs and I'm seeing two vectors for attacks:

1. xmlrpc in wordpress, with several hits for things like:
code:
/adxmlrpc.php HTTP/1.0" 404 2209
/adxmlrpc.php HTTP/1.0" 404 2209
/adserver/adxmlrpc.php HTTP/1.0" 404 2227
/adserver/adxmlrpc.php HTTP/1.0" 404 2227
/phpAdsNew/adxmlrpc.php HTTP/1.0" 404 2229
/phpAdsNew/adxmlrpc.php HTTP/1.0" 404 2229
/phpadsnew/adxmlrpc.php HTTP/1.0" 404 2229
/phpadsnew/adxmlrpc.php HTTP/1.0" 404 2229
/phpads/adxmlrpc.php HTTP/1.0" 404 2223
/phpads/adxmlrpc.php HTTP/1.0" 404 2223
/Ads/adxmlrpc.php HTTP/1.0" 404 2217
/Ads/adxmlrpc.php HTTP/1.0" 404 2217
/ads/adxmlrpc.php HTTP/1.0" 404 2217
/ads/adxmlrpc.php HTTP/1.0" 404 2217
/xmlrpc.php HTTP/1.0" 404 2205
/xmlrpc.php HTTP/1.0" 404 2205
/xmlrpc/xmlrpc.php HTTP/1.0" 404 2219
/xmlrpc/xmlrpc.php HTTP/1.0" 404 2219
/xmlsrv/xmlrpc.php HTTP/1.0" 404 2219
/xmlsrv/xmlrpc.php HTTP/1.0" 404 2219
/blog/xmlrpc.php HTTP/1.0" 404 2215
/blog/xmlrpc.php HTTP/1.0" 404 2215
/drupal/xmlrpc.php HTTP/1.0" 404 2219
/drupal/xmlrpc.php HTTP/1.0" 404 2219
(but they all 404; the only that might work is /blog/xmlrpc.php, and as far as I can tell this exploit was plugged a long time ago)

2. Checking for the presence of cPanel (Godaddy, it's there, latest version) e.g.:
code:
/img-sys/bg.jpg HTTP/1.1" 200 508
/img-sys/bg.jpg HTTP/1.1" 200 508
/img-sys/contentbox.jpg HTTP/1.1" 200 8846
/img-sys/contentbox.jpg HTTP/1.1" 200 8846
/img-sys/header.jpg HTTP/1.1" 200 19080
/img-sys/header.jpg HTTP/1.1" 200 19080
But they never actually try to do anything with cPanel, or at least nothing that shows up in the logs. So I've narrowed it down to either WordPress or cPanel, and was wondering if there's some new exploit hotness in WordPress that you guys have heard about that I haven't?

McGlockenshire
Dec 16, 2005

GOLLOCKS!
Judging from the fact that they're crawling only xmlrpc endpoints for various products in default locations, chances are that they're probing for some of the really, really old bugs in various xmlrpc libraries instead of just targetting Wordpress itself.

You might want to look up fail2ban.

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

Huh, weird that I finally got some movement on this just when you replied. He finally gave me shell access instead of just the logs/cpanel and I noticed this suspiciioooooous directory:
code:
/test/phpMyAdmin-2.6.2-pl1/
Wonder what that could be doing there, with its permissions of 000 and a create date at exactly the time this started happening. Ugh now I have to figure out how it got in there.

Okita
Aug 31, 2004
King of toilets.
I have a client who wants a PHP site with a framework that I have to choose. I usually don't use a framework and just custom-build every site differently, but this time the client demands that a framework(any framework of my choice) be used. The OP seems to have the major ones listed, but I haven't seen Yii in there. I'm currently leaning towards Yii after researching all the major ones (CodeIgniter, Symfony, CakePHP, etc). It seems to boast pretty good performance numbers and it looks pretty decent.

There is an issue though, the site I'm building will require RESTful web services. I really wanted to find a framework that has this out of the box with XML/JSON support and without too much hassle. At first I was heavily leaning towards CodeIgniter but it doesn't seem to have it (though I did see XML-RPC classes in there... a bit of a dated technology don't you think?).

Yii appears to only support SOAP web services out of the box, but I read on their forums that you can just define a custom controller to work with JSON or whatever.

The other catch is that this is a very time-sensitive project and needs to get done within a deadline. I don't want to spend weeks learning a complicated framework that does everything plus the kitchen sink. The site itself will not be doing any rocket surgery, mostly simple CRUD database operations with some calendar scheduling, reporting/analytics, social media tie-ins, and administrative tasks.

I guess my question is, which framework(s) should I be looking at to get this done?

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Scaramouche posted:

Huh, weird that I finally got some movement on this just when you replied. He finally gave me shell access instead of just the logs/cpanel and I noticed this suspiciioooooous directory:
code:
/test/phpMyAdmin-2.6.2-pl1/
Wonder what that could be doing there, with its permissions of 000 and a create date at exactly the time this started happening. Ugh now I have to figure out how it got in there.

Your server has been compromised. There's no way of telling what was changed or what they managed to get access to. Shut it down, nuke everything, restore from backup, apply patches.

IT Guy
Jan 12, 2010

You people drink like you don't want to live!

Okita posted:

I have a client who wants a PHP site with a framework that I have to choose. I usually don't use a framework and just custom-build every site differently, but this time the client demands that a framework(any framework of my choice) be used. The OP seems to have the major ones listed, but I haven't seen Yii in there. I'm currently leaning towards Yii after researching all the major ones (CodeIgniter, Symfony, CakePHP, etc). It seems to boast pretty good performance numbers and it looks pretty decent.

There is an issue though, the site I'm building will require RESTful web services. I really wanted to find a framework that has this out of the box with XML/JSON support and without too much hassle. At first I was heavily leaning towards CodeIgniter but it doesn't seem to have it (though I did see XML-RPC classes in there... a bit of a dated technology don't you think?).

Yii appears to only support SOAP web services out of the box, but I read on their forums that you can just define a custom controller to work with JSON or whatever.

The other catch is that this is a very time-sensitive project and needs to get done within a deadline. I don't want to spend weeks learning a complicated framework that does everything plus the kitchen sink. The site itself will not be doing any rocket surgery, mostly simple CRUD database operations with some calendar scheduling, reporting/analytics, social media tie-ins, and administrative tasks.

I guess my question is, which framework(s) should I be looking at to get this done?

Take a look at http://laravel.com/

It's a RESTful framework and gaining a lot of popularity. However, you need at least PHP 5.3

Okita
Aug 31, 2004
King of toilets.

IT Guy posted:

Take a look at http://laravel.com/

It's a RESTful framework and gaining a lot of popularity. However, you need at least PHP 5.3

Thanks, I dug into Laravel and I'm strongly considering it for this project. I'd be interested to see how it compares performance-wise to the other frameworks.

IT Guy
Jan 12, 2010

You people drink like you don't want to live!

Okita posted:

Thanks, I dug into Laravel and I'm strongly considering it for this project. I'd be interested to see how it compares performance-wise to the other frameworks.

From the benchmarks I've seen (too lazy to look them up right now), laravel performs quite well. It's not the fastest, but it's usually around the 70-80% fastest range of the major players.

IT Guy fucked around with this message at 22:44 on Nov 4, 2012

Dyrejb
Nov 18, 2009
I'm unsure what the best way to do this but how would I go about sorting a group of 10 integers into 2 near equal groups of 5? My current solution is where I sort by descending and then alternate putting the integers in each group but surely there must be a better method?

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Dyrejb posted:

I'm unsure what the best way to do this but how would I go about sorting a group of 10 integers into 2 near equal groups of 5? My current solution is where I sort by descending and then alternate putting the integers in each group but surely there must be a better method?

What do you mean by "near equal"? Can you give an example of the sort of input and output you expect?

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Dyrejb posted:

I'm unsure what the best way to do this but how would I go about sorting a group of 10 integers into 2 near equal groups of 5? My current solution is where I sort by descending and then alternate putting the integers in each group but surely there must be a better method?

This question is kind of vague. It's going to be difficult for anyone to answer because it's not really clear what "near equal" means, in terms of sets-with-multiplicity of 5 integers.

There are three routes you could go (that I can see). The first is to just come up with some kind of heuristic for separating out the numbers into two groups. A good heuristic might be one that "seems to" generally give more or less the sort of output you expect.

The second approach is this: The number of ways of partitioning a 10-element set into two 5-element subsets is 252, which is not a very big number at all. It is therefore feasible, given a function that returns the "badness" of a given partition, to calculate the partition which has the least "badness". If you know that you are always going to be dealing with sets of size 10, then this will work fine, provided you can indeed write a function that calculates the badness of a partition. If you might later have to apply your solution to, say, partitioning a set of size 1000 into two 500-element subsets, then this solution is not going to work very well because the number of ways of doing that is on the order of 10 to the power 299.

On the other hand, perhaps there exists an efficient algorithm that can be proven to always partition the 10-element set into two 5-element subsets in a way that minimises badness. But without knowing what you mean by "near equal" who can say whether there is.

Dyrejb
Nov 18, 2009
Basically I have 10 players who all have a rating assigned to them. I want to sort the players into 2 groups so that each groups rating is as similar as possible.

Example of the data I will pull with their Name and Rating.

Alanis - 100
Benedict - 120
Corbyn - 185
Derren - 155
Elsie - 140
Florentine - 130
Graeme - 170
Harrington - 130
Idris - 110
Jaqueline - 190

The total rating adds up to 1430 so ideally, I want to split those players into groups where each groups total rating adds up to 715. If I sort by Rating in descending order and then alternate adding them to each group I'd end up with Group 1's rating being 740 and Group 2's rating being 690.

Sorry for the vagueness, it looks like the second approach is what I should be using. Cheers.

McGlockenshire
Dec 16, 2005

GOLLOCKS!
Instead of alternating, instead try adding the current member to the list that has the lowest total, and to a random one in the event of a tie.

Example code:
php:
<?php
$scores = array(
        'Alanis' => 100,
        'Benedict' => 120,
        'Corbyn' => 185,
        'Derren' => 155,
        'Elsie' => 140,
        'Florentine' => 130,
        'Graeme' => 170,
        'Harrington' => 130,
        'Idris' => 110,
        'Jaqueline' => 190
);

arsort($scores);
print_r($scores);

$teams = array( => array(), array() );

foreach($scores as $name => $score) {
        $team_one = (array_sum($teams[1]) < array_sum($teams[2]));
        $team_two = (array_sum($teams[1]) > array_sum($teams[2]));
        if($team_one) 
                $teams[1][$name] = $score;
        elseif($team_two)
                $teams[2][$name] = $score;
        else
                $teams[mt_rand(1,2)][$name] = $score;
}

print_r($teams);
echo "\n";
echo array_sum($teams[1]), "\n";
echo array_sum($teams[2]), "\n";

Example output:
code:
Array
(
    [Jaqueline] => 190
    [Corbyn] => 185
    [Graeme] => 170
    [Derren] => 155
    [Elsie] => 140
    [Florentine] => 130
    [Harrington] => 130
    [Benedict] => 120
    [Idris] => 110
    [Alanis] => 100
)
Array
(
    [1] => Array
        (
            [Jaqueline] => 190
            [Derren] => 155
            [Elsie] => 140
            [Benedict] => 120
            [Idris] => 110
        )

    [2] => Array
        (
            [Corbyn] => 185
            [Graeme] => 170
            [Florentine] => 130
            [Harrington] => 130
            [Alanis] => 100
        )

)
715
715
Because of the random addition, the teams won't be exactly the same every single time, but it should be a decent approximation. It's also quite possible that a combined list with both huge and tiny scores could result in really unbalanced teams. Same thing with a combined list with an odd count instead of an even count.

Orbis Tertius
Feb 13, 2007


Not an answer to your question, but I suggest you look into using the Fabrik extension when doing any sort of database stuff when you're working with Jooma.

You can shoot me a PM if you have any questions about it.

Orbis Tertius fucked around with this message at 03:09 on Nov 5, 2012

Spatulater bro!
Aug 19, 2003

Punch! Punch! Punch!

What can you guys recommend for a good book to learn PHP? I'm not an absolute beginner (I've posted in here before), but I need a resource to supply me with a solid and thorough understanding. I've looked at online guides, but I feel a book will be the most up to date and comprehensive. A few things I'm wanting/not wanting:

-I don't want long-winded explanations of EVERY SINGLE obscure built-in function. A more practical overview approach would be better.

-I'd like it to do a good job teaching how to incorporate PHP with JavaScript.

-I need the book to have good exercises that actually help me learn what I read. Exercises that actually make me use my head rather than just copy the code from the page.

-Obviously, I need up-to-date best practices (eg. using mysqli instead of mysql, etc.

What do you all suggest?

Impotence
Nov 8, 2010
Lipstick Apathy
Using PDO instead of mysql

IT Guy
Jan 12, 2010

You people drink like you don't want to live!

caiman posted:

What can you guys recommend for a good book to learn PHP? I'm not an absolute beginner (I've posted in here before), but I need a resource to supply me with a solid and thorough understanding. I've looked at online guides, but I feel a book will be the most up to date and comprehensive. A few things I'm wanting/not wanting:

-I don't want long-winded explanations of EVERY SINGLE obscure built-in function. A more practical overview approach would be better.

-I'd like it to do a good job teaching how to incorporate PHP with JavaScript.

-I need the book to have good exercises that actually help me learn what I read. Exercises that actually make me use my head rather than just copy the code from the page.

-Obviously, I need up-to-date best practices (eg. using mysqli instead of mysql, etc.

What do you all suggest?

Start with this: PHP & MySQL: Novice to Ninja, 5th Edition

Then read these:
PHP Master: Write Cutting-edge Code
PHP Objects, Patterns and Practice

Then this:
https://github.com/php-fig/fig-standards/tree/master/accepted

Then this:
http://www.phptherightway.com/

None of these touch on JavaScript like you wanted though.

Spatulater bro!
Aug 19, 2003

Punch! Punch! Punch!


Purchased. Thanks!

IT Guy
Jan 12, 2010

You people drink like you don't want to live!

caiman posted:

Purchased. Thanks!

No problem. The book does a good job of explaining SQL injection and how to escape your output as well and he uses best practices such as using PDO.

Hadlock
Nov 9, 2004

Is there a simple PHP script that would allow users to upload and download a text file from a web page? Preferably it would save a second timestamped copy as a running archive to prevent vandalism.

We want to add in "asynchronous multiplayer" to Kerbal Space Program now that they're adding in docking. forum discussion here

Basically it would

1a) allow user to download ("check out") *.sfs (text) file by doing a simple download by pushing a button
1b) give user a 4 hr cookie or auth of some sort to access the upload page to save the new file back to the web for others to check out
2) lock out other users' download for 4 hours, or until "safe" flag is triggered by user uploading ("check in") a new file
3) save a backup copy of each new save file in a separate folder with a timestamp*.sfs file name.

...sort of like a really simple web-based SVN system

Actually if I could just get the file submit with *.sfs suffix check I could probably figure out the rest. This seems really simple and I bet a php guru has already written half of this in their head by the time they've read this. Any help? :)

Viggen
Sep 10, 2010

by XyloJW

Hadlock posted:

Actually if I could just get the file submit with *.sfs suffix check I could probably figure out the rest. This seems really simple and I bet a php guru has already written half of this in their head by the time they've read this. Any help? :)

Honestly, if this is how far along you are, you need a lot more help. There are tons of things to take into account, such as if file regex's properly but is a different mime type (.php.sfs), how webserver is setup to serve files, et al.

There are tons of error-prone examples.

You really should speak with whomever is managing the services and get a bit more time under your belt with basic webserver configuration so you can keep yourself from getting hosed on something trivial.

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker
http://pastebin.com/5aiWDTDv

Change username/password to something less dumb.

It saves every uploaded file in a folder called 'files', but you can change it easily if you want.

This is what you can do:
1) log in
2) either a) download the current sfs file to look at, or b) upload a new one directly without checking out first, or c) check it out so no-one else is able to upload a new one for 4 hours (time can be changes)
3c) upload a new one in the download folder (defaults to 'files')
4) that's it.

karms fucked around with this message at 23:21 on Nov 9, 2012

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION
For those of you wondering which framework you should be using, if you are able to guarantee your server will have PHP 5.3 then you should almost certainly be using Laravel - it's super amazing.

IT Guy
Jan 12, 2010

You people drink like you don't want to live!
Here's a good tutorial on beginning Laravel.

https://www.youtube.com/watch?v=m5Jmh9JKnyQ

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

Gnack posted:

For those of you wondering which framework you should be using, if you are able to guarantee your server will have PHP 5.3 then you should almost certainly be using Laravel - it's super amazing.

Would it be good for migrating from a mature but poorly-written corporate project? I am so insecure about this because I don't want to make a decision we'll regret in three years.

bobthecheese
Jun 7, 2006
Although I've never met Martha Stewart, I'll probably never birth her child.

Golbez posted:

Would it be good for migrating from a mature but poorly-written corporate project? I am so insecure about this because I don't want to make a decision we'll regret in three years.

It's PHP. You'll regret something in 3 years anyway. Actually, that applies to most corporate systems, but PHP does tend to increase the regrets.

Don't spend too much time worrying about regrets, and spend time worrying about how to implement code standards instead. So long as everything is consistent, then the other regrets don't really matter so much.

Fluue
Jan 2, 2008
Hey everyone.

I'm trying to work through this issue in a really small project. It takes a person's ID number (noted as CWID) and then looks up all the events he or she has attended. It then lists the events along with the club name of the associated events. I have 2 tables: clubsName and attendance.

I'm having trouble creating a match between the clubsName and attendance table. Both have clubID, but they're in different tables. Should I be doing some kind of triple join or some wizardry with arrays?

Here's a picture representation of what I'm talking about.



And what I hope to accomplish:

code:
Beachball Club
---------------
Event # 1 - date
Event # 2 - date

Yoga Club
--------------
Event #9 - date

Movie Club
------------
Movie Night - date

Only registered members can see post attachments!

Fluue fucked around with this message at 02:25 on Nov 13, 2012

Mister Chief
Jun 6, 2011

I don't see a person ID any any of those tables so how are you supposed to know what events they attended?

Fluue
Jan 2, 2008

Mister Chief posted:

I don't see a person ID any any of those tables so how are you supposed to know what events they attended?

Sorry, forgot to mention that the CWID is the person ID. I'll add that now.

Mister Chief
Jun 6, 2011

code:
SELECT clubsName.*, events.*, attendance.*
FROM attendance
INNER JOIN events ON (attendance.clubID =  events.clubID) 
JOIN clubsName ON ( events.clubID = clubsName.clubID)
WHERE attendance.CWID = personID 	
This is a start.

Izanagi
May 25, 2012

There are people who do and people who wish they had.
code:
SELECT e.eventTitle, e.meetingDate, c.clubName 
	FROM attendance a JOIN events e ON a.eventID = e.eventID 
	JOIN clubsName c ON a.clubID = c.clubID
	WHERE a.CWID = $IDNUMBER
	ORDER BY c.ClubName
$IDNUMBER is wherever you are getting the ID from. This will work in MSSQL but you will probably need punctuation for MYSQL to work but that should be fine.

This will join all tables together at their appropriate places so you can put whatever you like in the select part of the statement.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
I have a magic number that will be used across multiple pages and classes, but only in a particular module of the site. My predecessor and others have told me to only use constants if they are truly site-wide, but why not use them if they're module-wide?

Null Set
Nov 5, 2007

the dog represents disdain

Golbez posted:

I have a magic number that will be used across multiple pages and classes, but only in a particular module of the site. My predecessor and others have told me to only use constants if they are truly site-wide, but why not use them if they're module-wide?

define() creates constants that are global to the entire application. You should only use them if they are meant to be globally accessible. If your module is ever loaded elsewhere, the constant will be as well, and will be available to the entire app.

PHP also has the const keyword, which allows you to define constants scoped to a class or namespace. If this is module-wide, this is probably what you want.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

Null Set posted:

define() creates constants that are global to the entire application. You should only use them if they are meant to be globally accessible. If your module is ever loaded elsewhere, the constant will be as well, and will be available to the entire app.

PHP also has the const keyword, which allows you to define constants scoped to a class or namespace. If this is module-wide, this is probably what you want.

Right now the controller is not in a class though, it's functional, but things within it are classes and this needs to be available to all of those. This part of the site wouldn't be loaded by other code.

Adbot
ADBOT LOVES YOU

Null Set
Nov 5, 2007

the dog represents disdain

Golbez posted:

Right now the controller is not in a class though, it's functional, but things within it are classes and this needs to be available to all of those. This part of the site wouldn't be loaded by other code.

Are you on 5.3+? Define a namespace for the module, and set up your constants within that. Then load the containing file and call the constant where necessary.

Something like:

php:
<?
namespace MyModule;

const MY_CONSTANT = 'butts';
?>
Then when you want to call it:

php:
<?
$value = foo($bar, \MyModule\MY_CONSTANT)
?>

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