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
Innocent Bystander
May 8, 2007
Born in the LOLbarn.
Not trying to start a flame here, I've just gotta vent:

Sigh, I am now responsible for maintenance of an old PHP app, for some reason. I can do PHP, but there are other people at the company who are much more used to its idiosyncrasies. I never really understood all the hate for PHP programmers but now I think I'm coming around. This is admittedly an old project but goddam, I'm hoping that maybe I can talk about some things that annoy me and you guys can tell me why it actually makes sense in a PHP context.

PHP Tag Fairy Dust

Going in and out of PHP, I know its a templating language but gently caress! I cannot handle it.

code:
<?php 
    $rowC = 'even';
    foreach($optionarray as $iterator) {
?>
<option <?php $out = ($disabled) ? '' : 'selected';echo $out ?>><?php echo $iterator ?></option>
<?php ... 2500 lines more madness
Thats a snippet of what a large part of the file is like. Is this normal coding style? It makes almost no sense to me, except in the 'wow programming is cool' youngster sort of way.

Not using classes

Anytime I've done websites in PHP its used classes. Is there a reason not to use classes? I think PHP has pretty good object oriented system going in PHP5, is it just the blockheads I follow up that don't use it? It makes way too much sense to use classes? Am I just broken from Python and relying on classes for web design when they are actually a hindrance?

Adbot
ADBOT LOVES YOU

baquerd
Jul 2, 2007

by FactsAreUseless

Innocent Bystander posted:

PHP Tag Fairy Dust

Going in and out of PHP, I know its a templating language but gently caress! I cannot handle it.

code:
<?php 
    $rowC = 'even';
    foreach($optionarray as $iterator) {
?>
<option <?php $out = ($disabled) ? '' : 'selected';echo $out ?>><?php echo $iterator ?></option>
<?php ... 2500 lines more madness
Thats a snippet of what a large part of the file is like. Is this normal coding style? It makes almost no sense to me, except in the 'wow programming is cool' youngster sort of way.

As a preface, I use PHP sparingly, and typically just when I need to write up a simple database manipulation frontend for personal use.

I don't get how this works, isn't this variable assignment that evaulates to true always? And what's meant to be in $out anyway?
code:
$out = ($disabled) ? '' : 'selected'
With a little modification it's a bit clearer:
code:
<?
    foreach($optionArray as $optionValue) {
        echo "<option ";

        if ($out == $enabled) {
            echo "selected ";
        } 
        echo $out . ">" . $optionValue. "</option>";
    }
?>
Personally, I think there's a balance to be struck between using blocks of PHP and blocks of HTML to maximize readability.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

quote:

Is this normal coding style?
Yeah, but as you can see, it's horrible. The more PHP logic in a template, the less and less sense breaking out of PHP to emit HTML makes. Sooner or later you're breaking in and out multiple times a line and it's just a *bear* to keep up to date.

There aren't too many alternatives that make sense. Keep in mind that echo is a language construct and can take a list. This pattern has become popular at work:
php:
<?php
echo '<select ...>';
foreach($records as $row) {
    echo '<option',
         ($row['selected'] ? ' selected="selected"' ''),
         ($row['value']    ? ' value="' htmlspecialchars($row['value']) . '"' ''),
         '>',
         htmlspecialchars($row['derp']),
         '</option>';
}
echo '</select>';
At first, it looks like an immense waste of space that's horrible to read, but it wins out big-time over constantly switching in and out.

Switching in and out does feel a bit better when you're able to turn on short tags and can use <?= to echo. Short echo is always enabled as of PHP 5.4.

quote:

Is there a reason not to use classes?
Think of your average PHP code, then your average PHP coder... then think of the mental effort required to design a proper OO structure for your code, and you will become enlightened. The average so-called OO PHP code is a horrid mess of misapplied design patterns and idiocy. You're almost better off with procedural code sometimes.

Also, keep in mind that OO is not a magic bullet. It helps when building complex systems, but you don't need some big complex MVC framework to do day to day tasks. Use objects to manage complexity, not create it.

McGlockenshire fucked around with this message at 07:34 on Feb 7, 2012

revmoo
May 25, 2006

#basta
Can someone explain when it is appropriate to use closures/anonymous functions in PHP. Obviously you don't NEED to, but I'd like to understand when it would make sense to use them. This could probably apply to any language. I use it all the time in jQuery, but only out of 'this is how other people do it' rather than an understanding of the concept.

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

revmoo posted:

Can someone explain when it is appropriate to use closures/anonymous functions in PHP. Obviously you don't NEED to, but I'd like to understand when it would make sense to use them. This could probably apply to any language. I use it all the time in jQuery, but only out of 'this is how other people do it' rather than an understanding of the concept.

In general, you give names to things for two reasons: Either the name improves understanding for someone reading the code, or you need to use the thing more than once. This applies to all kinds of values, be they numbers, strings, arrays, objects, or functions.

So, if you use a function more than once, it should have a name. If a function's purpose is not obvious from looking at it, it should probably have a name that helps convey what its purpose is. If a function definition is long and ugly and would interfere with reading the code around it, then give the function a name and move its definition somewhere it doesn't make reading the code hard.

Single-use functions with obvious use that fit into the flow of the code around their usage site are excellent candidates for becoming anonymous functions.

revmoo
May 25, 2006

#basta
So, something small that you would only do once in a specific piece of code that doesn't warrant its own full function? Am I barking up the right tree? That actually makes a lot of sense. It's just an easy way to encapsulate a few lines of code that don't deserve their own actual function inside other logic. Right? I could see where that would come in useful.

The Gripper
Sep 14, 2004
i am winner

revmoo posted:

So, something small that you would only do once in a specific piece of code that doesn't warrant its own full function? Am I barking up the right tree? That actually makes a lot of sense. It's just an easy way to encapsulate a few lines of code that don't deserve their own actual function inside other logic. Right? I could see where that would come in useful.
I generally only use it for passing things to functions that take other functions as arguments (callbacks, generally), like array_walk:
code:
$items = array("a" => "one", "b" => "two", "c" => "three", "d" => "four");
$callback = function($value, $key) { 
                echo "$key. $value";
            };

array_walk($items, $callback);
but only if the anonymous function is only used in that one location, and it's logic is obvious. Code in the closure can access variables from the parent scope as well ( function ($x, $y) use (&$total) {}; ), so it's particularly handy if you're using array_walk to create a running total etc.

The Gripper fucked around with this message at 02:14 on Feb 9, 2012

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.
ShoulderDaemon is onto something with the idea behind naming. With functional languages, the idea of doing

code:
for (i=0; i<0; i++) {
   // do some stuff on an array with each element
}
is not very descriptive of what the code in the for loop is really doing. However, if you map a function over an array, it immediately becomes clearer what is happening.

code:
func cube(n) {
  return(n*n*n);
}

array_of_integers = map(array_of_integers, cube);
So, while longer to write, it's more descriptive because the code is telling me you are mapping the function cube() to each element of the array_of_integers array.

Like most things with PHP, anonymous functions are just crowbared in there and are awkward to use. Look into a real functional language (or at least one where functions were first order citizens to start with, like LISP or Scala) and you'll get a better feeling for how it's done well.

KuruMonkey
Jul 23, 2004

Innocent Bystander posted:

Going in and out of PHP, I know its a templating language but gently caress! I cannot handle it.

Well; as you said PHP is for templating really. Adn so the injection of <?php echo $whatever; ?> into HTML blocks is a key feature of the language, so yes people do it.

However; what you have there is a combination of almost obfuscated code structure, and a stupid mixing of decisions and templating. The fact that that's been interwoven through HTML is just the straw that breaks the camel's back there.

Innocent Bystander posted:

Anytime I've done websites in PHP its used classes. Is there a reason not to use classes? I think PHP has pretty good object oriented system going in PHP5, is it just the blockheads I follow up that don't use it?

Again; 2 things. It is in fact a logical fallacy to think that OO design is inherently 'better' than procedural design. So if an engineer is palpably better at procedural design and decomposition; they have a pretty compelling reason to go that route. (your previous example hints that the standard of procedural code you're dealing with will also be poor, though)

Second; how old is this legacy code? Because in PHP 4 the OO implementation was pretty awful - and certainly not bothering with it was a more believable proposition than it is now.

KuruMonkey
Jul 23, 2004

revmoo posted:

So, something small that you would only do once in a specific piece of code that doesn't warrant its own full function? Am I barking up the right tree? That actually makes a lot of sense. It's just an easy way to encapsulate a few lines of code that don't deserve their own actual function inside other logic. Right? I could see where that would come in useful.

You'd want them to be small; otherwise the local (calling) code will be a mess.

You'd want them to be specialised; if its too generic then really its something that's worth factoring out for the likely re-use. (I keep a library of common functions to throw into array_map, array_filter and array_reduce)

poxin
Nov 16, 2003

Why yes... I am full of stars!
So out of the blue I'm having a problem with images loading on my website. The data for these is pulled from a database and displayed. Works great, and has worked for a while, in chrome and firefox. Now for whatever reason it decides to not display the images in Internet Explorer. I have no idea what the hell happened, no one has access to change anything but me I don't know how to fix it. This is our busy season (tax returns) :smith:

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

poxin posted:

So out of the blue I'm having a problem with images loading on my website. The data for these is pulled from a database and displayed. Works great, and has worked for a while, in chrome and firefox. Now for whatever reason it decides to not display the images in Internet Explorer. I have no idea what the hell happened, no one has access to change anything but me I don't know how to fix it. This is our busy season (tax returns) :smith:

Can post post the portion of the script that is sending the image data to the browser? Is there a public link we can use to reproduce the issue ourselves?

musclecoder
Oct 23, 2006

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

poxin posted:

So out of the blue I'm having a problem with images loading on my website. The data for these is pulled from a database and displayed. Works great, and has worked for a while, in chrome and firefox. Now for whatever reason it decides to not display the images in Internet Explorer. I have no idea what the hell happened, no one has access to change anything but me I don't know how to fix it. This is our busy season (tax returns) :smith:

Make sure you're sending the right headers, would be my first guess. Maybe a newer version of IE can't handle a header properly. Post some code if you want more help.

poxin
Nov 16, 2003

Why yes... I am full of stars!
Edit: I updated my theme which in turn updated timthumb. Solved the problem :)

poxin fucked around with this message at 04:26 on Feb 11, 2012

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
We have an Adobe Flex text editor for viewing internal messages. Sometimes, randomly, it does not fully display. The background for it shows up in the MXML but the editor does not. Some debugging has led me to find out that, sometimes, the session is disappearing. I don't yet know if this is linked, since it doesn't tell me who it's happening to, but it's my only guess at the moment.

The code has this curiosity in it:
code:
session_id($_POST['sessid']);
@session_unset();
@session_destroy();
session_start();
if (count($_SESSION['flex']) > 0) { ...
It's that checking if anything is in the $_SESSION that fails. It only happens like .1% of the time. So, my question is: Does anyone know why this page (That's the top of the page, by the way - this is a PHP script called by the flex editor caller) would set the ID to the passed session ID, and then destroy and recreate the session? Why not just call session_start() like all the other pages on the site do?

And, would session_unset() and session_destroy() cause notices if there were no session, hence the error suppression?

Golbez fucked around with this message at 19:00 on Feb 13, 2012

simcole
Sep 13, 2003
PATHETIC STALKER
Learning some php over the weekend.. started adapting some code I found online to expand upon it. The page won't even load and it validates on the validator.

code:
<!doctype html>
<html>
<head>
<title>Client Login Portal</title>
<meta charset="utf-8" />
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>

<?php 
 // Connects to your Database 
 mysql_connect("site.com", "site_admin", "password") or die(mysql_error()); 
 mysql_select_db("test") or die(mysql_error()); 

 //This code runs if the form has been submitted
 if (isset($_POST['submit'])) { 

 //This makes sure they did not leave any fields blank

 if( !isset( $_POST['username'] ) || !isset( $_POST['pass'] ) || !isset( $_POST['pass2'] || !isset( $_POST['email'] ) ){
    die("Please fill in all the fields.");
}

 // checks if the username is in use
 	if (!get_magic_quotes_gpc()) {
 		$_POST['username'] = addslashes($_POST['username']);
 	}

 $usercheck = $_POST['username'];

 $check = mysql_query("SELECT username FROM members WHERE username = '$usercheck'");//
 
 // check for unique email address
 $uniquemail = mysql_query("SELECT email FROM members WHERE email = 'email'");//

or die(mysql_error());

 $check2 = mysql_num_rows($check);

 //if the name exists it gives an error
 if ($check2 != 0) {
 		die('Sorry, the username '.$_POST['username'].' or '.$_POST['email'].'is already in use.');
 				}
 // this makes sure both passwords entered match
 	if ($_POST['pass'] != $_POST['pass2']) {
 		die('Your passwords did not match. ');
 	}

 	// here we encrypt the password and add slashes if needed
 	$_POST['pass'] = md5($_POST['pass']);
 	if (!get_magic_quotes_gpc())
	{
 		$_POST['pass'] = addslashes($_POST['pass']);
 		$_POST['username'] = addslashes($_POST['username']);
 	}

 // now we insert it into the database
 	$insert = "INSERT INTO members (username, password, email)
 			VALUES ('".$_POST['username']."', '".$_POST['pass']."', '".$_POST['email']."')";
 	$add_member = mysql_query($insert);
 	?>
 
 <h1>Registered</h1>

 <p>Thank you, you have registered - you may now login.</p>

  <?php 
 } 
 else 
 {	
 ?>
 <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

 <table border="1">

 <tr><td>Username:</td><td>

 <input type="text" name="username" maxlength="65">

 </td></tr>

 <tr><td>Password:</td><td>

 <input type="password" name="pass" maxlength="65">

 </td></tr>

 <tr><td>Confirm Password:</td><td>

 <input type="password" name="pass2" maxlength="65">

 </td></tr>
 
 <tr><td>Email Address:</td><td>

 <input type="text" name="email" maxlength="65">

 </td></tr>

 <tr><th colspan=2><input type="submit" name="submit" 
value="Register"></th></tr> </table>

 </form>


 <?php

 }
 ?> 
 
 </body>
 </html>

Any ideas why? I put those 2 // next to those semi colon's because I don't think they belong but wasn't sure.

Impotence
Nov 8, 2010
Lipstick Apathy
Please don't use any of that (-- as in, that whole thing needs to go in the trashcan. Don't bother "fixing it up").
You're vulnerable to every single vulnerability that literally exists. MD5 isn't "encryption" and it's fairly worthless.

Impotence fucked around with this message at 05:50 on Feb 14, 2012

simcole
Sep 13, 2003
PATHETIC STALKER

Biowarfare posted:

Please don't use any of that (-- as in, that whole thing needs to go in the trashcan. Don't bother "fixing it up").
You're vulnerable to every single vulnerability that literally exists. MD5 isn't "encryption" and it's fairly worthless.

Awesome. Is there an up to date example/tutorial to follow. I've coded before and it's easy to addon later, but I need some basic functionality now.

Ninja Dan
Jun 28, 2005

Barn door's open!
Hello, I have a question that I'm sure is pretty simple but after scouring the PHP manual I have not been able to figure it out. Basically, I'm trying to create multidimensional arrays with named keys instead of numbers. As a practice exercise I'm trying to create a league standings board like you might see on a sports site. I want to have an array for $teams and then assign each team a key inside of the array and then create arrays for players and stats, then for each player create an array for there stats and so an so forth. I imagine this could be done better with a database but I'm still learning my php basics.

Here is my best attempt so far, followed by the output:

code:
//Here we have two teams starting out.
$team[] = array( 'DAL' => '');
$team[] = array( 'LAL' => '');


//Since we can't direcly create arrays within arrays we are taking
each $team and adding an array for stats. (Hopefully.)
foreach ($team as $key => $value) {
	$value = array('stats' => '');
}
Results:

code:
Array
(
    [0] => Array
        (
            [DAL] => 
        )

    [1] => Array
        (
            [LAL] => 
        )

)
I guess my next question now that I sit and think about it is how do I store the arrays? Eventually I want to be able to have users input the team and stats for each team without hard programming it in php. I guess at that point I would need a database? Some direction would be much appreciated, I've been trying to learn PHP out of a book and haven't had anyone knowledgeable to bounce ideas off of.

Any advice is greatly appreciated.

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'm confused by what you're looking for, so I'll go with the absolute most basic: It's very possible to have named keys, and it's easy to make arrays within arrays. Like so:

$array = array('foo' => array('shazbot' => 'a', 'snert' => 'b'), 'bar' => array('lol' => 'dongs'));

Edit: And as for why your foreach loop isn't updating: when it runs, foreach creates a copy of the array, so you are not editing the actual array. If you want to do it that way (and I'm not sure I recommend this), you need to pass it by reference, like so:
foreach ($team AS $key => &$value)

That way, when you edit $value, it actually edits the place in the memory where $value is (that is, the original $team), instead of the temporary copy created by foreach.

Golbez fucked around with this message at 07:13 on Feb 14, 2012

Ninja Dan
Jun 28, 2005

Barn door's open!
Basically I want to build an array that looks like this:
code:
Array
(
    [DAL] => Array
        (
            [DAL] => Array
                         (
                             [STATS] => Array (
                                      [PTS] => 25
                                      [WIN] => 45
                                      [LOSS] => 65 )
        )
        )

    [DAL] => Array
        (
            [LAL] => Array
                         (
                             [STATS] => Array (
                                      [PTS] => 25
                                      [WIN] => 45
                                      [LOSS] => 65 )
        )

)
And then be able to display it in a table like this [except much larger, with more teams and stats]:

code:

         Team          | PTS | WIN | LOSS |
Dallas Mavericks (DAL)   35    55     45
L.A. Lakers      (LAL)   25    45     65

The last paragraph was mainly talking about the end goals of the project which would allow the user to build the board from a crude web form and retaining the data.

Xik
Mar 10, 2011

Dinosaur Gum
If you wanted the simplest solution you could just use an array of Team objects.

You would have your Team class with properties like Name, Points, Wins, Losses and whatever else you want, then create objects and iterate over an array of them.

This Team class is for demonstration only, if you aren't familiar with OOP and concepts like scope, you should probably look into it. The PHP 101 topic on OOP is pretty average but should give you an idea. I'm sure if you ask in here there will be some recommendations for material on OOP.

code:
class Team
{
    public $name;
    public $points;
    public $wins;
    public $losses;
}
Create your objects and add it to an array of teams, then you can iterate over them and print the result (or populate a table in your case). You can also use a form to allow people to add teams (remember to escape input.)

code:
$teams = array();

$team = new Team();
$team->name = "Dallas Mavericks";
$team->points = 35;
$team->wins = 55;
$team->losses = 45;

// Add the team to the array
$teams[] = $team;

// Create another team
$team = new Team();
$team->name = "L.A. Lakers";
$team->points = 25;
$team->wins = 45;
$team->losses = 65;

// Then add that one also
$teams[] = $team;

// To demonstrate your teams in a table
// Dont do this at home
echo "<table border=1><thead><tr><th>Team</th><th>Points</th><th>Wins</th><th>Losses</th></thead><tbody>";
foreach ($teams as $team) {	
    echo "<tr><td>" . $team->name . "</td>";
    echo "<td>" . $team->points . "</td>";
    echo "<td>" . $team->wins . "</td>";
    echo "<td>" . $team->losses . "</td></tr>";	
}
echo "</tbody></table>";

// If you would like to visualize the array
echo "<h3>Array of Teams:</h3>";
var_dump($teams);

Output:



e: If you wanted to add players, create a Player class then do the same thing with players. In the Team class have an array of Players that belong to that team, then when you iterate over the team with a foreach you can nest another foreach to iterate over each player in the team etc. Sorry if this wasn't what you were after, but I think you were trying to take an unnecessarily complicated route by trying to jam all this information into multidimensional arrays.

If you want to take it even further, look at a small framework which will map database tables to objects for you and separate your logic and view. I know it can seem overwhelming (especially if you are just starting with the language, even more so if this is your first programming language) which is why I didn't mention it from the start.

Xik fucked around with this message at 12:15 on Feb 14, 2012

Hammerite
Mar 9, 2007

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

Ninja Dan posted:

Any advice is greatly appreciated.

Without wanting to give advice on how you should architect the system you are building, I think I can try to advise a little on how arrays work.

Basically an array in PHP is an associative array, meaning the keys are strings, so you have things like

array('butt' => 'poop', 'nose' => 'boogers');

but for many applications you have no need of descriptive labels for array elements, so arrays with numeric keys (starting at 0 and counting upwards) are common.

When you use the $existing_array[] = ...; syntax, you are telling PHP to add a new element to $existing_array and that the key for that new element should follow on from the maximum key currently found in the array. I'm sure there are rules for how the new key is determined, but that's basically it. So if $teams is an empty array, when you do

$teams[] = array(...);

you are adding a new element to $teams, whose key will be 0, and whose value will be the new array.

So you could get by with something like

code:
$teams = array(
    'DAL' => array('name' => 'Dallas Mavericks', 'points' => 25, 'wins' => 45, 'losses' => 65),
    'LAL' => array('name' => 'L.A. Lakers'     , 'points' => 25, 'wins' => 45, 'losses' => 65)
);
but whether this is in any way maintainable is another matter.

If you want to eventually have an interactive application where users can request stored information about teams then you are going to need to use a database. You then need to tackle the problem of fetching the data from the database into your application. However you decide that you want the data represented in your application, there is a way to assemble the data from the database in that form, but some ways of doing it will be less hassle than others.

Hammerite
Mar 9, 2007

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

simcole posted:

Learning some php over the weekend.. started adapting some code I found online to expand upon it. The page won't even load and it validates on the validator.

code:
<!doctype html>
<html>
<head>
<title>Client Login Portal</title>
<meta charset="utf-8" />
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>

<?php 
 // Connects to your Database 
 mysql_connect("site.com", "site_admin", "password") or die(mysql_error()); 
 mysql_select_db("test") or die(mysql_error()); 

 //This code runs if the form has been submitted
 if (isset($_POST['submit'])) { 

 //This makes sure they did not leave any fields blank

 if( !isset( $_POST['username'] ) || !isset( $_POST['pass'] ) || !isset( $_POST['pass2'] || !isset( $_POST['email'] ) ){
    die("Please fill in all the fields.");
}

 // checks if the username is in use
 	if (!get_magic_quotes_gpc()) {
 		$_POST['username'] = addslashes($_POST['username']);
 	}

 $usercheck = $_POST['username'];

 $check = mysql_query("SELECT username FROM members WHERE username = '$usercheck'");//
 
 // check for unique email address
 $uniquemail = mysql_query("SELECT email FROM members WHERE email = 'email'");//

or die(mysql_error());

 $check2 = mysql_num_rows($check);

 //if the name exists it gives an error
 if ($check2 != 0) {
 		die('Sorry, the username '.$_POST['username'].' or '.$_POST['email'].'is already in use.');
 				}
 // this makes sure both passwords entered match
 	if ($_POST['pass'] != $_POST['pass2']) {
 		die('Your passwords did not match. ');
 	}

 	// here we encrypt the password and add slashes if needed
 	$_POST['pass'] = md5($_POST['pass']);
 	if (!get_magic_quotes_gpc())
	{
 		$_POST['pass'] = addslashes($_POST['pass']);
 		$_POST['username'] = addslashes($_POST['username']);
 	}

 // now we insert it into the database
 	$insert = "INSERT INTO members (username, password, email)
 			VALUES ('".$_POST['username']."', '".$_POST['pass']."', '".$_POST['email']."')";
 	$add_member = mysql_query($insert);
 	?>
 
 <h1>Registered</h1>

 <p>Thank you, you have registered - you may now login.</p>

  <?php 
 } 
 else 
 {	
 ?>
 <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

 <table border="1">

 <tr><td>Username:</td><td>

 <input type="text" name="username" maxlength="65">

 </td></tr>

 <tr><td>Password:</td><td>

 <input type="password" name="pass" maxlength="65">

 </td></tr>

 <tr><td>Confirm Password:</td><td>

 <input type="password" name="pass2" maxlength="65">

 </td></tr>
 
 <tr><td>Email Address:</td><td>

 <input type="text" name="email" maxlength="65">

 </td></tr>

 <tr><th colspan=2><input type="submit" name="submit" 
value="Register"></th></tr> </table>

 </form>


 <?php

 }
 ?> 
 
 </body>
 </html>

Any ideas why? I put those 2 // next to those semi colon's because I don't think they belong but wasn't sure.

I don't want to go into detail about every fault that can be found in this code, but one specific fault is that addslashes() is not sufficient to escape data for a database query. At a bare minimum you need to use an escaping method that is tailored to the specific database connection that you are working with.

The main comment that applies to this code is that it's clunky, hard to read and you don't want to be writing a whole site like this.* If you want to build more than a "quick and dirty" script then as a bare minimum you need to organise common functionality that will be used throughout your application into classes and/or functions. If you want to build a big site then consider learning a framework. People will recommend frameworks I'm sure.

* As an example, you really don't want to be building a big old site and have every page filled with stuff like if (get_magic_quotes_gpc()) again and again. Another observation is that you want to be able to separate the HTML output of your page from the business logic of your application where you can, which the code you posted doesn't really achieve.

(The reason why I'm assuming you want to build a sizeable application is because your example code seems to be for a login page, or something similar, which seems to imply a large site. If you're just learning, my assumption might not be accurate.)

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Golbez posted:

The code has this curiosity in it:
code:
session_id($_POST['sessid']);
@session_unset();
@session_destroy();
session_start();
if (count($_SESSION['flex']) > 0) { ...
And, would session_unset() and session_destroy() cause notices if there were no session, hence the error suppression?
session_unset() is a relic from the early PHP4 days when register_globals was the default. It is entirely useless in any code that does not use register_globals.

session_destroy() is effectively a no-op unless the session already exists. Calling it without an existing session is entirely unnecessary at best and may cause undefined behavior at worst. Worse, calling it when you've defined the session id but haven't loaded the data is simply insane.

They both may be throwing notices about the bogus conditions. You can safely delete session_unset. You can modify the call to session_destroy to act only when a session currently exists.

code:
$old_session_id = session_id($_POST['sessid']);
if($old_session_id != $_POST['sessid'])
    session_destroy();
session_start();
if (count($_SESSION['flex']) > 0) { ...
There's a worse problem, of course. This code is blindly trusting a form input to load someone's session. It's a textbook session hijacking vulnerability.

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
Good point on that. Can you think of any reason why it would be setting the ID, then recreating the session, instead of just, y'know, starting a session?

Impotence
Nov 8, 2010
Lipstick Apathy

Hammerite posted:

magic quotes

http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2012-0831
Last revised:02/13/2012


:v:

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

Golbez posted:

Good point on that. Can you think of any reason why it would be setting the ID, then recreating the session, instead of just, y'know, starting a session?

Total guess here but it feels like a half-assed attempt at load balancing/outdated session management.

ZanderZ
Apr 7, 2011

by T. Mascis
Does anyone host with Fatcow? I'm having the toughest time trying to understand this guide on how to copy and paste the php.ini script.
http://www.fatcow.com/knowledgebase/beta/article.bml?ArticleID=1290&type=How%20To#Nugget_1374

My document root is...
/home/users/web/b24322/moo.username

Notice the "moo" in "moo.username" The tutorial says that the abbreviation for Fatcow is supposed to be "pr" but for me, it's "moo." So I assume I'm supposed to put "moo" in place of "pr" whilst following the guide.

Here's what I did...
1) Created a new folder called "cgi-bin"
2) Nested a folder called "temp" inside of cgi-bin.
3) Created a document titled "php.ini"
4) Copied and pasted php.ini from the link provided in the guide.
5) Changed the "sessions.save path =" line to read
session.save_path = /home/users/web/b24322/moo.username/cgi-bin/tmp

Obviously the tutorial says to put "pr.username" instead of "moo.username" but I assume that since I see "moo.username" in the document root category of the server information page, that's what I'm supposed to put. I've already tried it with "pr.username" and it didn't work either.

Anyway, once I get all that done, I go to the "PHP Scripting" page and try to set the version, but it won't bring up a list of versions. The drop down menu is just blank.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

ZanderZ posted:

Does anyone host with Fatcow? I'm having the toughest time trying to understand this guide on how to copy and paste the php.ini script.

They have a phone number for support as well as live chat, I would suggest trying that since you are paying them money.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Golbez posted:

Good point on that. Can you think of any reason why it would be setting the ID, then recreating the session, instead of just, y'know, starting a session?

Given that it's Flex and therefore probably a Flash front-end, it's very possible that Flash doesn't pass through the user's cookies properly, but it can read them and thus pass it along.

every
Apr 24, 2008

This is more of an htaccess / apache question, but I couldn't find a more appropriate thread, so here goes:

I'm using a little Wordpress plugin that adds watermarks to images in the uploads directory by including an htaccess file that does this:

AddHandler watermarked .jpg
AddHandler watermarked .jpeg
AddHandler watermarked .gif
AddHandler watermarked .png

However, the website I'm working on has a partners page in which the watermarks shouldn't appear. Every other image in the uploads directory needs to have the watermark, and that's working fine.

What I'd like to do is something like this:

if(!$isPartnerPage){
AddHandler watermarked .jpg
AddHandler watermarked .jpeg
AddHandler watermarked .gif
AddHandler watermarked .png
}

But obviously .htaccess isn't PHP. Could anyone suggest a good way of doing what I'm trying to do? The alternative would be to have those particular files that shouldn't be watermarked not uploaded into the uploads directory, but that might make things more complicated and confusing.

Thanks for any help!

MaberMK
Feb 1, 2008

BFFs

every posted:

This is more of an htaccess / apache question, but I couldn't find a more appropriate thread, so here goes:

I'm using a little Wordpress plugin that adds watermarks to images in the uploads directory by including an htaccess file that does this:

AddHandler watermarked .jpg
AddHandler watermarked .jpeg
AddHandler watermarked .gif
AddHandler watermarked .png

However, the website I'm working on has a partners page in which the watermarks shouldn't appear. Every other image in the uploads directory needs to have the watermark, and that's working fine.

What I'd like to do is something like this:

if(!$isPartnerPage){
AddHandler watermarked .jpg
AddHandler watermarked .jpeg
AddHandler watermarked .gif
AddHandler watermarked .png
}

But obviously .htaccess isn't PHP. Could anyone suggest a good way of doing what I'm trying to do? The alternative would be to have those particular files that shouldn't be watermarked not uploaded into the uploads directory, but that might make things more complicated and confusing.

Thanks for any help!

Make some watermarked images. Make some not-watermarked images. Put the watermarked images everywhere you need them and put the not-watermarked images where you need them. Add a rewrite rule to deny on the not-watermarked images for an invalid referrer (basically any referrer but the partners page) and you're done.

revmoo
May 25, 2006

#basta
Anyone know of a way of sorting a multidimensional array by one of the sub-values? I'd prefer keeping the root keys intact(assoc) but rearrange the actual order of the array. I figure I can come up with a way to do it myself but there might be an existing function that can do it.

Hammerite
Mar 9, 2007

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

revmoo posted:

Anyone know of a way of sorting a multidimensional array by one of the sub-values? I'd prefer keeping the root keys intact(assoc) but rearrange the actual order of the array. I figure I can come up with a way to do it myself but there might be an existing function that can do it.

I could be wrong (PHP has a staggering number of functions for manipulating arrays, with little in the way of naming conventions) but I don't think there is a core library function to do this. But it is easy enough to make it happen using uasort(). (You need uasort() rather than usort() because you want to preserve the array keys.)

Suppose you have an array $myArray of arrays and each of the sub-arrays has a key 'myKey' whose value is an integer, and you want to sort the sub-arrays into increasing order based on the values under 'myKey'. You can do this like so:

code:
function sortOnMyKey ($x, $y) {
    if ($x['myKey'] == $y['myKey']) {
        return 0;
    } else if ($x['myKey'] > $y['myKey']) {
        return 1;
    } else {
        return -1;
    }
}

uasort($myArray, 'sortOnMyKey');
Actually, I don't know if that sorts the sub-arrays into increasing or decreasing order and I can't be bothered to test, but I hope it's obvious how to change it if necessary :)

revmoo
May 25, 2006

#basta
How do $x and $y get passed into that? Also I think that would be a prime spot to use an anonymous function, did you write it without for to be clear or some other reason?

I ended up solving the problem by rethinking it. I assigned a weight subkey and increment/decrement the weight with a few functions and then sort the entire thing by enumerating the weights into an array and matching up keys in a big nested loop that re-sorts the final multi-d array by the weight values.

Works, but I've probably reinvented some sorting algorithm.

Hammerite
Mar 9, 2007

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

revmoo posted:

How do $x and $y get passed into that? Also I think that would be a prime spot to use an anonymous function, did you write it without for to be clear or some other reason?

uasort() expects its second argument to be a function usable for sorting. It expects the function to be one that takes two parameters, and returns the values -1, 1 and 0 (hopefully in a consistent way). uasort() takes care of actually calling the function. It does so internally, passing in the array elements of the array to be sorted as the $x and $y values. The user does not need to tell it how to do this, just supply a sorting function that behaves in the appropriate way.

I don't recall which version of PHP you have to be running in order to be able to use anonymous functions, so to be clear of that consideration I didn't bother.

revmoo
May 25, 2006

#basta
Really good info, thanks!

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.
PHP5.4 has been released: http://www.php.net/archive/2012.php#id2012-03-01-1

Has a lot of great features that make it more like a "real" language. I know I'll use the poo poo out of short arrays, easier array dereferencing, and being able to call methods on a newly build class:

php:
<?
$stuff = (new Something)->doStuff();?>
Also, claims of being a hell of a lot faster and memory efficient. Expect web hosting companies to be fully upgraded by 2018.

Adbot
ADBOT LOVES YOU

Yay
Aug 4, 2007

musclecoder posted:

PHP5.4 has been released: http://www.php.net/archive/2012.php#id2012-03-01-1
Including a bunch of unexpected test failures, and slightly less code coverage. Hooray!

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