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
duck monster
Dec 15, 2004

Bonus posted:

You also can't do
php:
<?
$bla = new Something()->method();
?>
and I don't know why the hell PHP doesn't allow that.

If your just after the output of the method, couldnt you just do something like

$bla = Something::method()

or are you after an initialised object?

Ie $address = new Customer('Dr Philodimo')->address()

PHP *does* have a few holes in that regard.

edit: Also x = thingo()[0] is a fairly common python idiom, as is the above, opening up awesomeness like
tag = xml('file.xml').parse().findtags('customers')[3].tag('name')

Maybe php6 will support it? One can only hope.


edit2: Add to the php orm's , ADODB 's Active Record.

duck monster fucked around with this message at 00:13 on Mar 20, 2008

Adbot
ADBOT LOVES YOU

duck monster
Dec 15, 2004

fletcher posted:

When I am validating fields submitted from a form I end up with a big if/else like:

php:
<?
if (!aValid) {
    //error information
} else {
    if (!bValid) {
        //error information
    } else {
        if (!cValid) {
            //error information
        } else {
            //db interaction
        }
    }
}?>
There's gotta be a better way than that. What's the right way to do this? Should the fields be validated by the setters of my class?

Heres another approach that I sometimes use

php:
<?
$errors = array(); $success = true;

if (!condition1) { $errors[] = "Condition 1 failed"; $success = false; }

if (!condition2) { $errors[] = "Condition 2 failed"; $success = false; }

if (!condition3) { $errors[] = "Condition 3 failed"; $success = false; }

if (!condition4) { $errors[] = "Condition 4 failed"; $success = false; }

if ($success) { 
           // Do stuff
} else {
   foreach ($errors as $error) {
          #Redraw the form and drop the errors into the template
   }
}
?>
It isn't as elegant as a validation array/loop thingo. And infact I'd strongly recomend building your own validation library where you can just pass it an array of validation data and have it spit out the goodness. You can then reuse it.

Or just find one on the net.

Another tip, not really php, is hunt down an old javascript library called 'fvalidate' for the javascript side of it. But remember NEVER rely on javascript validation. fvalidate is neat however, since it just involves setting alt tags on input fields. Setting the alt tags is kind of neat, since it validates, and normally alt tags have no real role on input fields, so they are handy for hijacking for metadata.

duck monster
Dec 15, 2004

duz posted:

The roll-your-own kind. Good luck figuring out that system!


Alt tags on inputs are for screen readers. jQuery has a nice form validation plugin that uses class names or you can use JSON to build you validation requirements.


Edit: fopen is GET only, not POST, sorry. vv Learn something new all the time, that might come in handy.

Yes, except that for input tags, you normally use the <label> tag to tell a screen reader what its for. Its yet another anomaly in html, but it means that the alt attribute on INPUT tags genuinely have no role.

duck monster
Dec 15, 2004

Back a whole bunch of pages was the question "How to stop image leeching".

Do this;- Compress 1 gig of zeros into a file named "image.jpg.gz". It'll come down to a megabyte.

Use url redirect and some magic to serve that as a gzip encoded http stream instead when the referer is all wrong.

Being that this satanic son of a bitch memory-murders anything that tries to leech it, the leeching stops very loving quickly.

:eng101: This is also a good way to massacre bots that ignore your robots.txt

put in something like dont_download_me_or_yourbrowser_will_die.html which is actually the browser bomb in your robots, and watch as spam spiders die screaming (some, not all, some will use smarter stream tech and not die.)

duck monster fucked around with this message at 08:27 on May 1, 2008

duck monster
Dec 15, 2004

Its a straight out rip of a technique people used to use to rape virus checkers , and particularly mail based ones, many moons ago.

Exchange (specifically) based virus checkers used to open up mails and examine them in-situ. The idea of the attack was to exploit the virus checkers ability to open zip files and examined them for virus's. So the trick was to get a gig or so of zeros and compress them to , like , a one meg file, and send it to the server. The server would then take it, open the zip file, and malloc() like an insane bitch to make memory for it, thus rendering itself completely gibberingly brain-dead. Eventually virus checkers got smart and switched to streams based zip processing.

Thing is, this attack vector STILL works against browsers and MANY spiders. You basically tell apache to take the gzip file and under NO circumstance open it for sending (because you'll end up raping your own box) , but just send it as the pre gzipped html page.

When I first tested it against a known spider, I noticed it accepted gzip html, so I tried it out. As the spider hit, I started pinging it, and watched as it fell for the trap. Very quickly the pings slowed down until after about 2 minutes, it just dropped off. Presumably the spider went catatonic.

Its nasty, its brutal, and it serves weblog spammer cunts right.

duck monster
Dec 15, 2004

Standish posted:

Because in all but pathological situations, small frequently-accessed files like the HTML headers/footers being described will be in the disk cache.

Trick we worked out in an old job was to store all our HTML in ramdisks (which you script to load in on server boot).

Even better with something like Smarty (or whatever), and keep the cache in ramdisk.

If Xdebug is to be believed, the performance increase was astronomical.

duck monster
Dec 15, 2004

redacted. unnecesarily agro.

duck monster
Dec 15, 2004

Zorilla posted:

Or the more context highlighting-friendly way:

php:
<?php

ob_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head profile="http://www.w3.org/2005/10/profile">
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <meta name="DESCRIPTION" content="stupid description goes here." />
        <meta name="KEYWORDS" content="keywordz" />
<?php
$meta_header ob_get_contents();
ob_end_clean();

?>


I'd actually strongly discourage doing this, because its not nestable and thus its not scaleable.

If you find later down the track your output needs to be captured for some sort of nefarious cacheing type purpose or whatever, then your kinda hosed.

duck monster
Dec 15, 2004

code:
echo "<td><tr>";
if ($address != "" && city != "") {
  echo "Address: $address<br> City: $city";
} 
elseif ($address != "" && city == "") {
  echo "Address: $address<br> City: none"
}
elseif ($address == "" && city != "") {
 echo "Address: none<br> City: $city";
}
elseif ($address == "" && city == "") {
  echo "Address: none<br> City: none";
}
echo "</tr></td>";
You could probably optimise it further with a switch/case thingo

duck monster
Dec 15, 2004

code:
echo "<td><tr>";

if ($address != "") echo "Address: $address<br>" 
else echo "Address: none<br>";

if ($city != "") echo "City: $city"
else echo "City: none";

echo "</tr></td>";
Just break it down bit by bit I guess v:shobon:v

edit: You'd want to test that. Its probably broken.

But if you want to modernise it, use a templating system like smarty or whatever, and investigate MVC systems like codeigniter or qcodo if your feeling adventurous.

duck monster fucked around with this message at 07:03 on Oct 11, 2008

duck monster
Dec 15, 2004

Khorne posted:

Are there any extremely light-weight CMS systems that are easy to modify to fit in to an existing framework?

Things I am looking for:

Very simple user table (accountId, Username, Password, Email, Access) so it can just use the existing one
News posts/static pages (updates / information pages)
Article types with varying access requirements and an easy way for admins to revert edits (wiki-like system for documentation)
Loads a php file and passes it an array or object with page information (no smarty, no intricate templating systems)

All requirements don't have to be met. I know I am going to have to modify whatever I do choose to use. I cringe at the sight of most CMS systems I've checked out. TikiWiki and MediaWiki are bloated and geared more toward lame wiki sites than practical applications. Most of the smaller CMS projects seem poorly implemented or downright bad.

I'm fairly close to coding it myself, but it's a bad idea for me to take on another project. I have far too many left unfinished and an ever decreasing amount of free time.
CMS Made simple is what I use, partly because its basically just a tiny little CMS for use with smarty templates.

Its got a pretty configurable user auth system, but you might be on your own regarding an audit trail for edits.

I guess you could just add your own.

duck monster
Dec 15, 2004

This
code:
  function num_rows() {
   // return count($this->Query_ID->fetchAll()); //Always returns zero also yuck.
   //return mysql_num_rows($c); //old code
  }
Has me miffed. Anyone know the equivilent to mysql_num_rows in pdo? Unfortunatelyt we cant use the count(id) thing, because its an attempt at switching toolkit on 40K+ lines of code, so we have to use pdos version of num_rows, but for the life of me I cant find it documented, and it seems utterly clownshoes that they'd have one for updates but not selects.

But I'd be hosed if I know what it is.

duck monster
Dec 15, 2004

duck monster posted:

This
code:
  function num_rows() {
   // return count($this->Query_ID->fetchAll()); //Always returns zero also yuck.
   //return mysql_num_rows($c); //old code
  }
Has me miffed. Anyone know the equivilent to mysql_num_rows in pdo? Unfortunatelyt we cant use the count(id) thing, because its an attempt at switching toolkit on 40K+ lines of code, so we have to use pdos version of num_rows, but for the life of me I cant find it documented, and it seems utterly clownshoes that they'd have one for updates but not selects.

But I'd be hosed if I know what it is.

Possibly solved my own question
code:
  function num_rows() {
  	$this->cQuery_ID = $this->dbh->query('SELECT FOUND_ROWS()');
  	return $this->cQuery_ID->fetchColumn(0);
  }
This seems to actually work, but if someone has a reason why this is a terrible solution, I'd love to hear it.

duck monster
Dec 15, 2004

Oh god my current job is driving me nuts.

The place I started working for has a loving *massive* inhouse CMS , and its atrociously written. You know the sort. Load in the chrome, ?action=xxxxxxx include (getIncludeFile($_GET['action'])); blah

All procedural. Theres a custom database layer that doesn't seem to understand cursors and cant do prepared statements.

On the upside, it has smarty, which is something I guess, since its a 40 man dev team.

Or is it? One of the sites had a smarty template with about 4-5 thousand lines of smarty conditional template logic mangled with javascript that generated custom javascipt to deal with some poo poo that was all if product='aaaa' then bbbbbbb else if product = 'bbbb' then ccccc else if pro<blah> for thousands of lines.

gently caress PHP with a rusty screwdriver. It encourages some *horrifying* coding sometimes..

I'm dying for a django job here folks.

duck monster
Dec 15, 2004

Just a quick reminder how utterly broken this language can be...

code:
 <?
  print (5 + (int)$nuts) . "<br>";
  print (5 + $nuts);

?>
Outputs

quote:

5
5

:psyduck:

How the gently caress is x + Null = x??????

x + Null = Null!!!!!!!!!!!!!

duck monster
Dec 15, 2004

supster posted:

Uh... there's a lot of things wrong with PHP, but this isn't one of them.

How is "Incorrectly evaluates null" not a problem. When your language cant do basic maths properly, yeah man, its a problem, and this problem has caused our team about a week and a half running around in circles looking for very obscure bugs.

The example I posted has PHP just inventing that Null = zero. Null is never equal to zero, otherwise it would not be null, it'd be zero.

The top line is *sort of* correct, because I'm using type forcing to specify to handle null as an integer. Well it might as well be zero, although 42 is equally valid.

The second line is an outright bug.

duck monster fucked around with this message at 04:51 on Feb 2, 2009

duck monster
Dec 15, 2004

Hammerite posted:

Surely if the first example is all right then the second example is as well. By using + after 5 it would seem that you're inviting PHP to perform integer (well, maybe even real number) addition, in which case it seems quite reasonable that it makes no difference whether you put (int) in there or not; it ought probably to convert whatever it sees after the + to an integer, regardless.

Also, you're describing something as "basic maths" which to me (algebraic topologist in training) is really some kind of point of computer science orthodoxy, not truly mathematics, but w/e.

Sure. Let me explain.

Null means "I dont have a value for this." , or alternatively "Not a number" (Some languages have different signifiers for null, and not-a-number), so if Y = null, then X + Y = null because if you dont have a value for Y , then you dont have a value for X. Same with subtraction, multiplication and in fact pretty much any operation, with a few knobs.

Now when you type cast to an int your actually saying , you MUST return this as an integer. The truly correct answer is to explode in flames and drop an exception, but assuming you don't actually want that (int) Null might as well be a good way of saying "Treat Null as zero".

duck monster
Dec 15, 2004

gibbed posted:

Or you can just live with PHP's implicit casting of your null value to 0. It's not that bad.
Except that its wrong and causes serious loving headaches.

duck monster
Dec 15, 2004

gibbed posted:

In what situation would you find '1 + null = null' useful?

Well i've been working with a reverse chain induction algorithm where 1 + null should always evaluate to null, because it means we dont have the pieces to evaluate the solution correctly.

Even if its not usually that useful, its yet another example of PHP breaking itself to hold innexperienced coders hands.

Take the old php3/4 register globals problem, you'd actually eliminate half of the problems it caused by treating null as null, because at least you'd be treating a lack of data as a lack of data. "Insufficient data" means "Insufficient data", if you treat it as zero, you clearly are not "getting" algebra.

And if Javascript treats nulls as zero, then javascript is broken too, although by and large, most of us already knew that.

duck monster
Dec 15, 2004

supster posted:

It's not wrong, it is how weakly typed dynamic typing languages behave. Numeric types cannot have a null value. Obviously this is specified by the language, but I cannot think of a single language that allows for null valued numeric types. If you're complaining about this characteristic of PHP then you might as well be complaining about C, C++, Java, Python, Ruby, C#, etc.

Wrong, and remember that Python does a fair bit of type cohercion via magic methods where possible.

code:
>>> x = None
>>> print x
None
>>> print x + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
>>>
This is correct behavior

Also a bit of research is telling me javascript doesn't behave the way many here seem to think it behaves.

http://saladwithsteve.com/2008/02/javascript-undefined-vs-null.html

edit:
>> alert(1 + y)
y is not defined

dropping an exception is correct behavior.

Note that Javascripts diferentiates Null, undefined and NaN, which is even more correct, so..

z = undefined
>> z + 1
NaN

duck monster fucked around with this message at 05:53 on Feb 2, 2009

duck monster
Dec 15, 2004

supster posted:

Python is strongly typed. PHP is weakly typed. You're comparing apples to oranges.

Python doesn't evaluate 1 + "1" to 2 (it throws a very similar error). PHP does. Does this make one right and the other wrong? No. These are characteristics that define the languages.

Mind you I'll add that 1 + "1" = 2 is loving terrible, especially if your expecting the correct answer of 50. (The ordinal position of ASCII "1" is 49). We are reverting back from Pascal to Cobol here folks, thats how regressive it is.

Weak typing is the worst thing ever, especially when it lets so many plainly wrong things pass without complaint. But for comparison, check out VB's evaluation of Nulls. VB is a loving awful language thats also weak typed, but it knows about Null and Not a number, at least if my memory serves me right.

duck monster
Dec 15, 2004

supster posted:

Are you loving retarded? If you're here to complain about PHP being weakly typed, this isn't the thread to do it in. There is nothing wrong with weakly typed languages if you use it properly and understand how typing works.

Yes, it would be a terrible idea for a php coder to discuss a fault in PHP in the PHP thread.

Anyway, it gets more fun..

At the same time is evaluating null as zero in math,
code:
$v = Null;
var_dump(isset($v));
will evaluate as false, because casting to null causes the interpreter to unset the variable. So with this in mind let me clarify my complaint, it is not the "Nothing" sense of "Null" thats evaluating to zero, its the "undefined" sense of null. That is to say, Null un-defines a variable, and its not Null, but the the undefined variable that evaluates as zero, so it quite *explicitely* defines "unknown" as zero, and that is obviously incorrect maths. That is what you have to compare with other languages, and I cant think of a language, including Javascript that doesnt at least throw an exception when attempting arithmatic in a variable that hasnt even been allocated yet.

duck monster fucked around with this message at 06:30 on Feb 2, 2009

duck monster
Dec 15, 2004

As part of a work project I've been asked to port some basic Django/Rails type functionality into the inhouse CMS.

Oh boy. Unfortunately my prefered option of "welp, lets use django" probably wont go down well considering the company is convinced this godawful sluggish php cms it owns is worth millions in IP blah blah :sigh:

Anyway, I've written a url router, with the following code;-

php:
<?
class router {
    
    function router() {
        $this->table = array();
        $this->references = array();
    }
    function addroute ($route,$obj,$funct) {
        $this->table[$route] = array($obj,$funct);
    }

    function route() {

        foreach ($this->table as $k=>$v) {

            $urlsplit = explode(URL_SLICE,$_SERVER['REQUEST_URI']);
            $url = $urlsplit[1];
            if (preg_match_all($k,$url,$matches)) {
                global $_URL;
                $_URL = $matches;
                $obj = new $v[0]();
                print $obj->$v[1]($_SESSION,$_REQUEST,$_URL);        
            }
        }
    }
    
}
?>
Theres some fugly hacks in there, but its just prototype stuff for now.

The questions is, how does one write a regex that preg_match_all can read so that a url like

/users/32 can match on /users/ and then extract the 32 into a variable. I know in perl and python you can use named capture groups to do this , but I honestly have no loving idea how to do it in any of these, let alone php.

Any regex gurus able to help me here?

duck monster
Dec 15, 2004

FeloniousDrunk posted:

Not a guru, but something like this:
php:
<?
    function route() {
        foreach ($this->table as $k=>$v) {

            $urlsplit = explode(URL_SLICE,$_SERVER['REQUEST_URI']);
            $url = $urlsplit[1];
            if (preg_match('!^/'.$k.'/(.*)$!',$url,$matches)) {
                global $_URL;
                $_URL = $matches[1];
                $obj = new $v[0]();
                print $obj->$v[1]($_SESSION,$_REQUEST,$_URL);        
            }
        }
    }
    
}
?>
$matches[0] has the whole matching string (useless), $matches[1] will have the first group, etc.

Well yeah, obviously, the question I was asking is how to craft the regex.

duck monster
Dec 15, 2004

Big gotcha. Check for spaces, enters and cruft before the first <?

Thats often a big cause of 'headers already sent' type errors.

duck monster
Dec 15, 2004

Hmm. Maybe my regex question needs a thread

duck monster
Dec 15, 2004

That ought work. Change the include to require just to verify it is getting the person class definition.

Failing that change __construct to person , which is the alternative constructor syntax (use class name as method name) and see if that works.

duck monster
Dec 15, 2004

eHacked posted:

Hi, thanks, changing the constructor name seemed to work... would this have anything to do with the server I'm learning off of running php 4?

Ah yup. Php 4 is a pretty basic version of OO. You need to get your hands on something with Php 5 since 4 is pretty much redundant.

duck monster
Dec 15, 2004

Try reading the file in, making GBS threads it back out, and tacking on an appropriate mime header there.

duck monster
Dec 15, 2004

drcru posted:

I'm currently using ADODB to handle MySQL abstraction on my website but I recently updated to PHP5 and thought it might be a better idea to use something like mysqli or PDO.

Which of the two should I use to handle all my MySQL transactions?

If it matters, I use "update" a lot.

Stick with ADODB if you can. Its still a fine library.

duck monster
Dec 15, 2004

Clone5 posted:

strtotime — Parse about any English textual datetime description into a Unix timestamp

php:
<?
$fivedaysago = strtotime("-5 days", $timestamp);
# or
$fivedaysago = strtotime("5 days ago", $timestamp);
?>

Quick heads up. Never ever ever use strtotime to just blindly parse user input. Things will go horrifyingly wrong and probably at the level of your database and thats bad.

duck monster
Dec 15, 2004

VerySolidSnake posted:

This is a really bad idea. You have to write everything from scratch, opening up the potential of security holes and exploits. Frameworks have teams of people testing these things all the time, something Uncle Joe's PHP Framework will lack. Also, you are going to have to think of every possible way you might want to expand this thing, as you can accidentally put your entire site in handcuffs with a bad design decision early on. I did this "roll your own" thing on 3 websites, and I regretted it after spending the time to learn Yii.
Relying on the dude who originated PHP for advice is just inviting dark counsel. This is the man that designed a language that allowed such horrors as;-

/index.php?id=5

$SQL = "SELECT * FROM TABLE WHERE id= ".$id;

PHP isn't quite the cosmic horror it once was, but that doesn't change the fact that this dude was responsible for the terrible hell early php represented.

duck monster fucked around with this message at 15:02 on Dec 24, 2011

duck monster
Dec 15, 2004

I have a problem. I've got a new job where I'm maintaining this utterly *ancient* piece of code , like 12 years old and as many years of haphazard patching leaving a bloody awful website based on table layouts ( :suicide: ) , magic quotes, get variables coming in via some sort of magic and so on.

The dude however believes that the code is SUPER SECURE because the guy who wrote it was an ENGINEER. Its loving awful. I've found a number of SQL injections, but it seems at some point the guy decided to use htmlentities as his cleaning mechanism for sql. My gut instinct tells me this is wrong, but I'm not entirely sure how to exploit it.

There is THIS clanger however
PHP code:
		$result = exec("/usr/bin/nslookup ".substr($email, strpos($email, "@")+1), $output); //I dont trust this at all.
		if (!substr_count(implode(",", $output), "NXDOMAIN")) { 
			create_user($email);
Ok. Whats going on here, is that the $email (which just sort of magically passes in via the URL) is split so that everything after the first @ is passed as the second paramater of /usr/bin/nslookup , well actually kind of lobbed onto the command

so

duckmonster@magicalwebsite.com

becomes

/usr/bin/nslookup magicalwebsite.com

If it returns with the word NXDOMAIN anywhere, it means the domain isn't real and its not a real email address.

This is borked. But I need to prove it. I had him leaning over with me fuming about this insane code as I tried to exploit it using stuff like

duckmonster@magicalwebsite.com ; cat /etc/passwd > /var/www/passwds.txt

etc....

But nothing I could do could exploit this. Anyone know a good way to DEMONSTRATE that this code is insane and broken to my boss?

I'm trying to get him to let me rewrite the whole drat site either in DJANGO or PHP (preferably using either Cake or a combo of Smarty and an ORM

duck monster fucked around with this message at 23:14 on Apr 28, 2013

duck monster
Dec 15, 2004

This is the problem with being an honest man. I know how all these vunerabilities work. I've just never had a reason to actually try and use the drat things :(

duck monster
Dec 15, 2004

v1nce posted:

Hammerite makes the best point here; simply because you can't exploit it doesn't mean it's secure. I see MySQL injection being thwarted on most recent setups simply because mysql_query() refuses to run multiple queries (dies when it hits the semicolon) , rather than anyone sanitizing their data properly. I'm guessing the same thing is why your exec() isn't exploitable.

That said, it's very much worth pointing out to whoever the developer is that they're doing it very, very wrong. For instance, you could swap out that horrible exec() for the following (stolen from stack overflow)
php:
<?
// Check email is valid
if ( filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
    echo "Your email is invalid.";
}

// Check domain
$domain = substr($email, strpos($email, '@'));
elseif (checkdnsrr($domain) === FALSE) {
    echo "That domain doesn't exist."
}

// Create account if OK
else
{
    create_user($email);
}
?>
My other recommendations would be:

* Throw this whole thing into GIT and branch off of it. Your nemesis can continue to work on it, and you can hack it up and fix it then merge it back with his stuff later on.

Nemesis rapidly losing favor. He mailed in a patch with some code like this

code:
$value = $_GET['parameter']

$blah = mysql_query ('SELECT * FROM A_TABLE WHERE NAME=$value');
It took my about 10 seconds to craft a URL that creates a table called "owned" with all the users email addresses and passwords. Nemesis might not be working for us soon, and the boss is now taking me seriously.

quote:


* If the DB stuff isn't written too horrendously, you might be able to find-and-replace your way out of this, and wrap everything in a DB accessor class.

One fortunate thing is most of this is long drop (code starts at top and just drops through to the bottom with little in the way of structure) spagetti code with very little in the way of intertwangled dependencies. This makes it easier to just go "Today I'm replacing ALL the code for THIS page" to take the sting out of a rewrite.

I'm going to start either moving stuff across to an ORM or just PDO with a strict policy of using stored procedures for data and parameter passing rather than string interpolation. Its hard work though, some of these are 10K long pages of table laid out HTML mushed in with PHP and SQL.

quote:

* If it's not doing stuff like isset($_POST) to determine the execution path, find-and-replace all the $_GET and $_POST stuff with $_REQUEST just because.
* If you're using an IDE like PHP Storm, just blanket replace htmlentities with mysql_real_escape_string (or whatever) and then go through the changes as a git diff and revert anything inappropriate. This isn't the right way to do it, but for blind blanket changes I find this workflow really fast.
Yeah already onto it. I've introduced the boss to Mercurial (Because I'm a retard who finds git hard, hey shoot me, mercurial owns) and he was loving hard when I showed him how diffing branches worked. I'm hooking it all into redmine with an eventual view to getting a Hudson server up to run PHPUnits when I get my rewrite.

quote:

*llght as well learn some basic PHP than everyone having to learn Smarty. If you already know Smarty, you should know it's a complete bitch to do anything truly complex in it, and you're much better off just using straight PHP, hopefully in some kind of view wrapper class (ie. CakePHP).
I'll respectfully disagree with this. PHP in HTML is never a good idea when dealing with real world implentors and graphics designers. Too much power coupled with too little experience.

With PHP comes programming attempts. With programming attempts come power. With power comes sql-injection and other assorted stupidities. I just want HTML templates with holes poked in them for my code to stick its dick into. HTML people need to stay the gently caress away from my code. My major problem with smarty is its too functional and encourages people to try and do logic in presentation. Trust me I've seen smarty files with giant decision trees of madness branching through them. My optimal template engine would allow substitution, and instantable blocks with a non-controller view behind it automating the instantiation. Alas, It'd probably give most people migranes.

quote:

Usually the best argument to a boss about this kind of code is; the current framework is barely a framework at all, and you're spending far too much time writing basic functionality rather than actual program code. The method of data sanitation is awful and should be handled by the framework and not need writing every time you want to manipulate data.
If your application is front-facing, point out the recent breaches with Sony, PBS, Yahoo! and the Royal Navy (http://en.wikipedia.org/wiki/SQL_injection#Examples). These guys probably thought their stuff was secure too because ~engineers~, but if you're not doing it right, and you're pointing this out to them now, then you're heading for a world of hurt.

Yeah I'm starting to get the message through.

duck monster fucked around with this message at 16:47 on Apr 29, 2013

duck monster
Dec 15, 2004

I've spend a decade and a half around web design shops and trust me man, theres a reason for that isolation of powers.

Its certainly not unique to templates. Think about private/public variables on classes. Whilst there are some scope and optimization type reasons, frankly
much of its about stopping stupid junior coders from breaking poo poo they don't understand.

We're not even talking about junior programmers, we're talking about an entire industry of arts grads, its that bad. And trust me, I'm an art grad, I should know.

duck monster
Dec 15, 2004

Jabor posted:

Wait, are you saying that you make all your class members public if you're the only one who's going to be working on a project?

Chances are if I'm the only one working on it, my language choice wont even support private variables, because there isn't a reason ever not to use python
in a situation where you have a choice 99.99% of the time. And with due respsect to where I am, given a choice on a project language , in 2013 it sure as hell it won't by PHP. Time, and sanity, is money.

edit: Oh god, magic_variables_gpc breaks mysql_escape_string and creates *double slashes* thus rending things MORE insecure.
:negative:
Burn the fields and salt the earths, I need to move this shop to either a good framework, or something not php loving pronto. The "long drop"(poo poo starts at the top and executes through the code to the bottom, then the programmer hangs himself with it in despair) method of web coding needs to die.

edit2: Oh god, I just discovered the boss who's that untrained he doesn't know how functions work codes *on the live server* using an ftp client. I was loving wondering where his copy of the code was. I have so much work to do. :(

duck monster fucked around with this message at 02:42 on May 2, 2013

duck monster
Dec 15, 2004

Zamujasa posted:

:stonk: Why are you using magic_variables_gpc? Jesus Christ write a drop-in replacement using mysqli and even the most basic of prepared queries or something as soon as you can.

This is a massive (Thousands of files) spageti codebase , roughly 12 years worth of monkey patched turds, and the boss insists that it has to stay until its rewritten. Thus I'm not allowed to.

Its loving insanity and I'm going to rewrite the *poo poo* out of it, but its a hell of a task.

duck monster
Dec 15, 2004

Whats the current thinking around these woods on railsy type frameworks for php.

I'm wanting to rewrite a very loving insane php app I've had shat upon my lap. Its loving huge, and its a mess of bad security, embedded html (with table layouts and < font> tags and poo poo, its a horror) , and almost no concept of structured design. It has to all be burnt to the ground, its that bad.

So looking around, I need something that'll work well with an *existing* database, has templates (or at least a php view system I can teach a retarded dreamweaver wrangler how to use in under half an hour) , a decent selection of modules and if possible database migrations. And no php 5.4 because the existing codebase is loving terrible and relies on now deprecated features, and I need to co-pilot the system across.

So Cake. Seems good, but uh, its kinda bulky and crufty looking.
Code igniter looks neat, but I sure do see a lot of people claiming its redundant on the net.
Laraval... Looks neat, but its also a bit huge looking and I dont know how well supported it is.

What else is there. Learning curve is important! If I had my way I'd do it in Django, but I'm not sure the boss (who insists on hacking this himself too) wants to learn a new language, even though python is actually amazingly easy.

Adbot
ADBOT LOVES YOU

duck monster
Dec 15, 2004

mooky posted:

Amazing!!! This is most helpful!



Well, if its complex and slow and I can use PDO or the mysql_ functions (OMG, I KNOW!), why should I spend the time to learn Doctrine? I don't want to take the time to learn something that I won't use all the time. I may use it for this project, but what about projects that I don't build with a Framework? It just seems like an extra step, or complication that I don't need right now.

What real benefit does Doctrine offer over traditional methods for accessing a MySQL database? Anything that really really justifies learning Doctrine?

Because once you understand ORMs they make life amazingly easy, because they basically abstract away the gritty details of databases into something more akin to having persistant objects that can be queried as a database. More to the point, you can *extend* the objects and fit behaviors to them to facilitate an approach to OO more about *modelling* behavior rather than simply grinding over instructions procedural style.

I have a tendency to architect my code , starting with UML and moving stepwise towards a final product. Not very agile, but I'm a greybeard, I earned that right. You think in terms of entities and how they behave. Rather than just a "members" table, which you hit with SQL and then do stuff to it, you instead have "members" objects with properties and methods that are specific to that object. So rather than authenticate($member,$username,$password) you have member=>authenticate($username,$password);. It might seem to be splitting hairs, but its conceptually very powerful and is easier to reason about at a higher level than just code.

That said, ADODB has an ActiveRecord implementation in it, thats surprisingly useful, if not a bit simple (Pro-tip: Just wrap your more complex stuff in Mysql views and treat them as tables). I dont really get why ADODB doesnt get more love then it does.

duck monster fucked around with this message at 02:30 on May 9, 2013

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