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
tef
May 30, 2004

-> some l-system crap ->
Also, if you wish to keep a copy of the sanitsed html, you can use a cache like memcached

Adbot
ADBOT LOVES YOU

DaTroof
Nov 16, 2000

CC LIMERICK CONTEST GRAND CHAMPION
There once was a poster named Troof
Who was getting quite long in the toof
I agree that sanitizing should be the last step before output or very close to it, but that doesn't necessarily have anything to do with string concatenation syntax. In most of my applications, the process that outputs data retrieves all of its input from a store that sanitizes everything it receives.

MononcQc
May 29, 2007

duz posted:

And braces allows you to do crazy things like:
php:
<?
$variable = 'something';
$obj->a = 'variable';
echo ${$obj->a};
?>

They were also my only way out of some heredoc trouble with arrays:
php:
<?
$array['john'] = "John Laurence"; //or whatever I'm just looking for a poo poo example
$value[1] = 'john';

echo <<<EOF

this is $array[$value[1]] and you will love him.

EOF;

?>
would output me something like
code:
this is Arrayjohn and you will love him.
Adding braces around $array[$value[1]] to get {$array[$value[1]]} was the best way to get the arrays to work properly.

Inquisitus
Aug 4, 2006

I have a large barge with a radio antenna on it.

MononcQc posted:

Adding braces around $array[$value[1]] to get {$array[$value[1]]} was the best way to get the arrays to work properly.

PHP :eng99:

Zorilla
Mar 23, 2005

GOING APE SPIT

Bonus posted:

I'm of the opinion that it's generally best to sanitize data as late as possible. So if you're sanitizing it for output, sanitize it right before outputting or when you know that you won't be doing anything with it other than outputting.

So would there be anything wrong with sanitizing as late as the MySQL query string? Right now, I'm getting away with processing form inputs with their original $_POST superglobals, then using htmlspecialchars() at the query function argument to keep form inputs from doing anything too powerful, though I don't know if that would leave you wide open on older, less secure versions of PHP.

Zorilla fucked around with this message at 02:29 on Apr 6, 2008

Khorne
May 1, 2002
Nevermind.

Khorne fucked around with this message at 20:14 on Apr 6, 2008

bt_escm
Jan 10, 2001

Zorilla posted:

So would there be anything wrong with sanitizing as late as the MySQL query string? Right now, I'm getting away with processing form inputs with their original $_POST superglobals, then using htmlspecialchars() at the query function argument to keep form inputs from doing anything too powerful, though I don't know if that would leave you wide open on older, less secure versions of PHP.

htmlspecialchars() won't stop sql injection. You'll need to you mysql_real_escape_string() to properly clean the string for inserting into the database.

hey mom its 420
May 12, 2007

Zorilla posted:

So would there be anything wrong with sanitizing as late as the MySQL query string? Right now, I'm getting away with processing form inputs with their original $_POST superglobals, then using htmlspecialchars() at the query function argument to keep form inputs from doing anything too powerful, though I don't know if that would leave you wide open on older, less secure versions of PHP.
Yeah.
But ideally I think the sanitizing for the database should be coupled with the layer that does the actual insertion. A good example of that is either ADOdb or mysqli where you do stuff like this:
php:
<?
$conn->Execute("SELECT * FROM TABLE WHERE COND=?", array($val));
?>
and
php:
<?
$stmt->prepare("SELECT District FROM City WHERE Name=?")) {
$stmt->bind_param("s", $city);
$stmt->execute();
$stmt->bind_result($district);
$stmt->fetch();
?>
respectively. The general idea is that this is good delegation of responsibility, in that the layer communicating with the database is responsible for not exposing the database to injection. So there's no way you could forget to escape data before giving it to the database layer for insertion because it's its responsibility and not yours. :science:
And you probably shouldn't sanitize the input in any other way (i.e. htmlspecialchars) before inserting it into the database. You should always have pure data in your database and then sanitize it for output after fetching it from the database.

hey mom its 420 fucked around with this message at 00:15 on Apr 7, 2008

hey mom its 420
May 12, 2007

Incidentally, does anyone else think that the interface for mysqli is loving terrible? Especially the bind_param method. First you have to prepare the statement, then you have to bind parameters to it by giving it variables and strings like "sssd", then execute, bind results to variable, then fetch the data and then loop and output the variables that have the results binded to them repeatedly.
Sure, binding results to variables and then the current row being assigned to those variables saves memory by not storing all results in an array but it's not like you're going to be outputting 1 million records on a single page.
ADOdb does it way better.

gibbed
Apr 10, 2006

Bonus posted:

Incidentally, does anyone else think that the interface for mysqli is loving terrible? Especially the bind_param method. First you have to prepare the statement, then you have to bind parameters to it by giving it variables and strings like "sssd", then execute, bind results to variable, then fetch the data and then loop and output the variables that have the results binded to them repeatedly.
Sure, binding results to variables and then the current row being assigned to those variables saves memory by not storing all results in an array but it's not like you're going to be outputting 1 million records on a single page.
ADOdb does it way better.
Havn't used ADOdb, but PDO allows both (I hate that binding stuff).

Zorilla
Mar 23, 2005

GOING APE SPIT

bt_escm posted:

htmlspecialchars() won't stop sql injection. You'll need to you mysql_real_escape_string() to properly clean the string for inserting into the database.

Right, I was just trying to prevent users from embedding HTML into pages.

One of the things I've noticed is that the query string is already escaped for you (PHP 5.2.0) and attempting to use mysql_real_escape_string() will end up escaping your string twice.

I'm guessing my hosting has magic_quotes_gpc turned on. What's the proper way to handle things whether this is on or off? Detect whether magic_quotes_gpc is turned off and only escape the query string manually then?

If you haven't guessed, I'm a total beginner and suck at programming anyway.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Zorilla posted:

Right, I was just trying to prevent users from embedding HTML into pages.

One of the things I've noticed is that the query string is already escaped for you (PHP 5.2.0) and attempting to use mysql_real_escape_string() will end up escaping your string twice.

I'm guessing my hosting has magic_quotes_gpc turned on. What's the proper way to handle things whether this is on or off? Detect whether magic_quotes_gpc is turned off and only escape the query string manually then?

If you haven't guessed, I'm a total beginner and suck at programming anyway.

For stuff that's to run on servers I can't control, I put this at the start of my script(s)
php:
<?
if (get_magic_quotes_gpc())
{
    if (!function_exists(stripslashes_array))
    {
        function stripslashes_array($array)
        {
            return is_array($array) ? array_map('stripslashes_array', $array) : stripslashes($array);
        }
    }
    $_GET = stripslashes_array($_GET);
    $_POST = stripslashes_array($_POST);
    $_REQUEST = stripslashes_array($_REQUEST);
}
?>
so I don't have to worry about magic_quotes.

Zorilla
Mar 23, 2005

GOING APE SPIT
That's pretty much what I just ended up doing:

php:
<?
if (get_magic_quotes_gpc()) {
    $cleanquery = $query;
} else {
    $cleanquery = stripslashes($query);
}
?>
Yeah, I know it keeps me from escaping characters in the query string on purpose, but it seems to be on the right track.

Zorilla fucked around with this message at 01:37 on Apr 7, 2008

nbv4
Aug 21, 2002

by Duchess Gummybuns
Say, since we're on the subject of escaping, I noticed a little while ago that whenever data comes in through a <textarea>, the string is already escaped. If I run it through mysql_real_escape_string, double escaping will occur. I don't know if it's the browser thats doing this, or if it some kind of magic quotes thing... After I finally realized this, I just stopped escaping all my textarea data. Is this a bad decision?

Zorilla
Mar 23, 2005

GOING APE SPIT

nbv4 posted:

Say, since we're on the subject of escaping, I noticed a little while ago that whenever data comes in through a <textarea>, the string is already escaped. If I run it through mysql_real_escape_string, double escaping will occur. I don't know if it's the browser thats doing this, or if it some kind of magic quotes thing... After I finally realized this, I just stopped escaping all my textarea data. Is this a bad decision?

Well, the conclusion I think I just came to hours earlier (with some help) is that you should check to see if magic quotes is enabled, then either don't escape if it's on or do escape if it's off.

Also, when loading MySQL fields into a textarea, be sure to encode any HTML markup inside them. Web browsers will render anything between textarea tags as plaintext so you probably aren't vulerable to XSS, but it will result in invalid (X)HTML if there is actual markup in there.

For instance:

Invalid:
code:
<textarea cols="25" rows="10" name="textcrap">words words <b>bold words</b></textarea>
Valid:
code:
<textarea cols="25" rows="10" name="textcrap">words words &lt;b&gt;bold words&lt;/b&gt;</textarea>

Zorilla fucked around with this message at 08:29 on Apr 7, 2008

Atom
Apr 6, 2005

by Y Kant Ozma Post

Zorilla posted:

Well, the conclusion I think I just came to hours earlier (with some help) is that you should check to see if magic quotes is enabled, then either don't escape if it's on or do escape if it's off.



While I've never heard of it causing problems, it is recommended to unescape it and use the MySQL extension's escape function if magic quotes is on.

Zorilla
Mar 23, 2005

GOING APE SPIT

Atom posted:

While I've never heard of it causing problems, it is recommended to unescape it and use the MySQL extension's escape function if magic quotes is on.

I think the PHP documentation says the same thing. In other words, something like this?

php:
<?
// Pretend a MySQL connection is open already

$cleanquery = mysql_real_escape_string(stripslashes($query));
$result = mysql_query($cleanquery);
?>

Zorilla fucked around with this message at 09:05 on Apr 7, 2008

admiraldennis
Jul 22, 2003

I am the stone that builder refused
I am the visual
The inspiration
That made lady sing the blues

Zorilla posted:

I think the PHP documentation says the same thing. In other words, something like this?

php:
<?
// Pretend a MySQL connection is open already

$cleanquery = mysql_real_escape_string(stripslashes($query));
$result = mysql_query($cleanquery);
?>

That's what I usually do if magic quotes is on.

nbv4
Aug 21, 2002

by Duchess Gummybuns
I have this one class which is getting so huge, it's almost 2000 lines. I want to split it up into smaller text files to make editing easier, but I'm having trouble doing so. Apparently you can't just do:

php:
<?

class foo extends lol
{
     include "text_file_with_methods.php";

     function blah()
     {
       ...
?>
nor can you have a class extending from multiple classes. What can I do here?

Inquisitus
Aug 4, 2006

I have a large barge with a radio antenna on it.

nbv4 posted:

I have this one class which is getting so huge, it's almost 2000 lines. I want to split it up into smaller text files to make editing easier, but I'm having trouble doing so. Apparently you can't just do:

php:
<?

class foo extends lol
{
     include "text_file_with_methods.php";

     function blah()
     {
       ...
?>
nor can you have a class extending from multiple classes. What can I do here?

Either try and split the class up logically into smaller classes, or leave it as it is if you can't.

nbv4
Aug 21, 2002

by Duchess Gummybuns

Inquisitus posted:

Either try and split the class up logically into smaller classes, or leave it as it is if you can't.

I could do that fairly easily because this huge class is essentially two classes in one anyways, but the only problem is that this classes constructor runs like 20 SQL queries which provide information for pretty much every function in that class. If I split it into two or three classes, I'll have to run those constructors another time or maybe even twice more. I'd really hate to do that for just the convenience of having seperate text files...

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


You can have constructors run the parent's constructors or you can have your queries just use the last used connection.

nbv4
Aug 21, 2002

by Duchess Gummybuns

duz posted:

You can have constructors run the parent's constructors or you can have your queries just use the last used connection.
I'm not worried about that, I'm worried about actually running the queries twice, one for each object. I'm kind of a performance stickler like that. Is there anyway to easily copy a bunch of member variables from one object to another? I admit I'm not really an OOP expert.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

nbv4 posted:

I'm not worried about that, I'm worried about actually running the queries twice, one for each object. I'm kind of a performance stickler like that. Is there anyway to easily copy a bunch of member variables from one object to another? I admit I'm not really an OOP expert.

Not really sure how you are instantiating them, but this should work fine. Or if you are instantiating Bar inside of Foo's construct, $bar->fields = $this->fields, etc. I'm new to oop as well, so hopefully somebody else will weigh in on this too.

php:
<?
$foo = new Foo();
$bar = new Bar();

$foo->fields = $bar->fields;?>
This is also pretty neat:
php:
<?
get_class_vars(get_class($this));?>

fletcher fucked around with this message at 18:56 on Apr 7, 2008

<deleted user>

nbv4 posted:

I'm not worried about that, I'm worried about actually running the queries twice, one for each object. I'm kind of a performance stickler like that. Is there anyway to easily copy a bunch of member variables from one object to another? I admit I'm not really an OOP expert.

You don't want to copy member data or do the SQL multiple times -- that defeats the purpose of OOP. Remove functionality from the large object into other classes. It may make sense for the main class to hold instances of these new classes. The new classes could use properties of the main object by receiving a reference to it:

php:
<?

class Foo {
   var $fighter;
   var $some_data = 'awesome';

   function Foo() {
      $this->fighter = new FooFighter();
   }

   function attack() {
      $this->fighter->kungfoo($this);
   }
}

class FooFighter {
   function kungfoo(&$foo) {
       echo "HIII-YAH!  I'm " . $foo->some_data . "!\n";
   }
}

...

$foo = new Foo();
$foo->attack();
// prints "HIII-YAH! I'm awesome!"
?>

OlSpazzy
Feb 10, 2004

I've given up trying to fix my comments problem from previous posts. I just don't understand php well enough to do the job myself.

Does anyone know of a php news publishing script that can be integrated into an existing site (not a cms script) that includes the comments inside the news posts at all times?

In other words, you don't have to view the full story or load a new page to view comments as they are already displayed on the initial post, along with the comment submission form.

the talent deficit
Dec 20, 2003

self-deprecation is a very british trait, and problems can arise when the british attempt to do so with a foreign culture





Is this the right place for Zend questions? I hope so.

I've got an IndexController with four actions. indexAction works fine, the other three give me 404 errors. (I have views setup for all four). Is this because mod_rewrite isn't setup properly? Or my .htaccess is badly written?

minato
Jun 7, 2004

cutty cain't hang, say 7-up.
Taco Defender

nbv4 posted:

I have this one class which is getting so huge, it's almost 2000 lines. I want to split it up into smaller text files to make editing easier, but I'm having trouble doing so. Apparently you can't just do:

php:
<?

class foo extends lol
{
     include "text_file_with_methods.php";

     function blah()
     {
       ...
?>
nor can you have a class extending from multiple classes. What can I do here?

This is where C#'s "partial class" definitions feature would come in handy. But we don't have that, so here's what I do with my 18000 line class that contains all the DB schema upgrades we've made since version 1:


php:
<?
class DBUpgraderBase {
  function upgrade_version_1() {
     ...
  }
  function upgrade_version_2() {
     ...
  }
  ...
  function upgrade_version_99() {
     ...
  }
}
?>
and in another file
php:
<?
class DBUpgraderBase1 extends DBUpgraderBase {
  function upgrade_version_100() {
     ...
  }
  ...
  function upgrade_version_199() {
     ...
  }
}
?>
and so on, until finally we get to:
php:
<?
class DBUpgrader extends DBUpgraderBase6 {
  function upgrade_version_700() {
     ...
  }
}
?>
That way we just instantiate "DBUpgrader" and it will automatically include all the functions from the parent classes.

Zorilla
Mar 23, 2005

GOING APE SPIT

minato posted:


Yeah, I was going to say he should start with a class and then subsequent classes should extend it. I guess this is one way of saying it.

brae
Feb 2, 2006

genericadmin posted:

code

I would suggest this. Your problem is a good application for a class factory. Have a class (the factory) that does the expensive sql and add methods on it to get instances of the chunks of your big class that you've created. Have the chunks take a reference to the factory (so they can get at the stored results of the expensive SQL). You run the queries once and can produce different objects that can get at one copy of the results.

Zorilla
Mar 23, 2005

GOING APE SPIT
I've got a client we're doing a web page redesign for and it turns out he would like to be able to edit basically anything that might need changing on the site on his own. Normally, I would just set up some system like Website Baker or CMS Made Simple, but this site in particular has quite a bit of markup I don't want the client to disturb. Plus, the site has some dynamic content with a backend I wrote a month or so ago to edit its contents.

I just found out about a system called Cushy CMS, which looks like it would work brilliantly. Unfortunately, it seems to only support static pages and appears to be a service you have to use through their site instead of installing on your web server. And it's in closed beta- not something I want business clients using.

Are there any systems out there that are fairly easy to set up like Cushy CMS that would work with PHP pages? The idea is for the site owner to be able to edit snippets of information such as the welcome text or store hours in the backend without having to muck around in HTML.

If creating a solution to this is beyond me, it can be contracted out. I'm just looking for recommendations.

Zorilla fucked around with this message at 03:04 on Apr 9, 2008

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

How do I search for <br /> with preg_match_all?

<deleted user>

drcru posted:

How do I search for &lt;br /> with preg_match_all?

preg_match_all("#&lt;br />#", $string, $m)

Or, if you want to be slashy...

preg_match_all("/&lt;br \/>/", $string, $m)

Or, if you want to be flexible...

preg_match_all("#&lt;br(?: /)>#", $string, $m)

admiraldennis
Jul 22, 2003

I am the stone that builder refused
I am the visual
The inspiration
That made lady sing the blues

drcru posted:

How do I search for <br /> with preg_match_all?

preg_match_all("/<br \/>/i",$in,$out);

(case-insensitive, will only match <br /> and not <br>)

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Can I assume that #\n# will find all new lines?

admiraldennis
Jul 22, 2003

I am the stone that builder refused
I am the visual
The inspiration
That made lady sing the blues

drcru posted:

Can I assume that #\n# will find all new lines?

Yes.

If you have any more questions you should probably just google a regular expressions tutorial.

gibbed
Apr 10, 2006

drcru posted:

Can I assume that #\n# will find all new lines?
If you're serious about using a regular expression to find newlines, you probably want #\r?\n|\r# instead.

admiraldennis
Jul 22, 2003

I am the stone that builder refused
I am the visual
The inspiration
That made lady sing the blues

gibbed posted:

If you're serious about using a regular expression to find newlines, you probably want #\r?\n|\r# instead.

You should probably just normalize newlines from the get-go with something like:

$str = str_replace(array("\r\n","\r"), "\n", $str);

especially since PCRE by default understands \n as the newline character

admiraldennis fucked around with this message at 06:21 on Apr 9, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Is it a bad idea to write a backup script in PHP? I just need it to dump the database, tar.gz a folder, delete the oldest backup on the backup server, and upload the new one. It seems like it would be cake to write it in PHP, but should I? Is there a reason I have to write this as a bash script?

Adbot
ADBOT LOVES YOU

bt_escm
Jan 10, 2001

fletcher posted:

Is it a bad idea to write a backup script in PHP? I just need it to dump the database, tar.gz a folder, delete the oldest backup on the backup server, and upload the new one. It seems like it would be cake to write it in PHP, but should I? Is there a reason I have to write this as a bash script?

Since you already know PHP, writing it PHP would make the most sense. I really don't think it would matter what you write it in.

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