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
MononcQc
May 29, 2007

Safety Shaun posted:

I have a huge table of articles I've posted on one of my personal sites and each entry has a tags field as such

art_id, art_name, art_cont, art_tags
1, "title of article 1", "content of article 1", "hello, wooop, omnomnom"
2, "title of article 2, "content of article 2", "jello shots, canabis, gaysex"
3, "title of article 3, "content of article 3", "jello shots, canabis, robin hood"
4, "title of article 4, "content of article 4", "canabis, woop, something else, craigslist"

How would I create an array of all the tags, ordered by any more commonly used ones first? Would I implode them all into a tags array, order by somthing then use an array function to remove dupes? or is there some mythical magical MySQL command that'll accomplish this for me?

Suggestion: you should have a table possibly just for tags, then an intermediary table matching art with tags:
art: art_id, art_name, art_cont
tags: tag_id, tag_name
art_tags: at_id, art_id, tag_id

That way, you do not need to do any processing when retrieving tags (just implode them when parsing the form where they are added: parse once, not every time you select). Count, group by, order by. And you have your list.

This is a much more flexible way to structure data and operate on it. This also lets you extend tags (add a description, an image, etc.) without loving up the art table.

Ask yourself "Can I have art without tags?" If you say yes, then tags should probably be in another table.

MononcQc fucked around with this message at 23:50 on Oct 2, 2008

Adbot
ADBOT LOVES YOU

jasonbar
Apr 30, 2005
Apr 29, 2005

MononcQc posted:

:words:
This. If each tag has a row in a separate table, you can use mysql GROUP and COUNT(). See the second example on that page. If you order by your count, you should be good to go.

Lunatic
Apr 6, 2004
Im putting together a php CLI daemon thing and im implementing child processes.

I have a parent process that will loop through and create a set of child processes (the number dependant on a config file). Once they're all set up, each child process then goes off and does it's thing.

Now, at the moment, I have the parent process doing a simple sleep(10) where it will have some logic in the future. At the same time if the child process dies, i.e. due to the SOAP call failing/throwing an exception, it seems to interrupt the sleep(10). Is this normal/expected? I would have thought the parent process would wait until the end of the sleep before dealing with the SIGCHLD signal. Is there any way of preventing it?

Ned
May 23, 2002

by Hand Knit

Zorilla posted:

Is there a good way to gracefully reject file uploads that are too large? Limits are usually controlled through php.ini or other files that compliment it such as .htaccess, which means PHP is the one throwing a fit when something is too big.

I want to display a user-friendly error if somebody tries to upload gargantuan, unresized images from their 14 MP camera to a website. My guess is that there is some sort of error you could check for on postback, but Google comes back absolutely dry when I look up information on this. Any ideas?

I think you should set it with html.
<input type="hidden" name="MAX_FILE_SIZE" value="500" />

Aturaten posted:

Is there any way to get a DIVs size using PHP? I really need to find this out soon, this image gallery is killing me.

PHP has no idea of knowing what the page actually looks like in the browser or DOM. jQuery is your friend here.

MrEnigma
Aug 30, 2004

Moo!

Ned posted:

PHP has no idea of knowing what the page actually looks like in the browser or DOM. jQuery is your friend here.

PHP actually has an object for manipulating the DOM (http://us.php.net/dom). The catch is that you need to use output buffering, and you have to operate on it before you dump it out to the user.

There is also PHPquery (http://code.google.com/p/phpquery/) which is compatible with jQuery 1.3 API I believe.

Zorilla
Mar 23, 2005

GOING APE SPIT

Ned posted:

I think you should set it with html.
<input type="hidden" name="MAX_FILE_SIZE" value="500" />

Yeah, that's one approach. I didn't want the user to be able to lift the limit by tampering with post data, so I set the PHP-wide limit instead. I have things mostly working at this point, but uploading is still giving me some bizarre behavior every now and then that I need to sort out.

MrEnigma posted:

PHP actually has an object for manipulating the DOM (http://us.php.net/dom). The catch is that you need to use output buffering, and you have to operate on it before you dump it out to the user.

There is also PHPquery (http://code.google.com/p/phpquery/) which is compatible with jQuery 1.3 API I believe.

The first is mainly for parsing HTML/XML and phpQuery is just an easier way of messing with objects than the first method. Really, because a div's computed width is entirely up to the whim of the web browser used, his only option is to determine the width beforehand, then set it stlye="width: somevalue;", making sure the page's design allows the set width to reliably match the actual computed width.

I went back to Aturaten's post about this, and I guess he's doing an image gallery. Keep in mind that even Google's image search uses Javascript to line up the images based on your browser's size, not some server-side method. I would advise you to just use tables for this since it's one of the few totally appropriate uses for it in modern web design.

Zorilla fucked around with this message at 01:26 on Oct 4, 2008

Chopper
Feb 13, 2006

Zorilla posted:

I would advise you to just use tables for this since it's one of the few totally appropriate uses for it in modern web design.

This is something I don't get with "Web 2.0" design.

Everyone is so "OMG TABLESSS!!!" that they never use them. I've seem someone display tabular data using floated divs.

You aren't giving in by using tables for displaying data, you are only giving in if you use them for design purposes.

MrEnigma
Aug 30, 2004

Moo!

Chopper posted:

This is something I don't get with "Web 2.0" design.

Everyone is so "OMG TABLESSS!!!" that they never use them. I've seem someone display tabular data using floated divs.

You aren't giving in by using tables for displaying data, you are only giving in if you use them for design purposes.

While I completely agree with you about tables and actual data. I can see uses for doing non-tables for data....variable columns, moving stuff way around. Some sites that allow for a theme or something could have some advantage...but yeah...not usually.

vanjalolz
Oct 31, 2006

Ha Ha Ha HaHa Ha
Whats the best way to get the age of a file in days?

edit:
$now = strtodate("now");
$result = filemtime($file);
$diff = $now - $result;
$days = floor(($diff%2629743.83)/86400) ;

vanjalolz fucked around with this message at 06:09 on Oct 6, 2008

Murodese
Mar 6, 2007

Think you've got what it takes?
We're looking for fine Men & Women to help Protect the Australian Way of Life.

Become part of the Legend. Defence Jobs.

vanjalolz posted:

Whats the best way to get the age of a file in days?

http://au.php.net/manual/en/function.filemtime.php

e; :argh:

vanjalolz
Oct 31, 2006

Ha Ha Ha HaHa Ha

I assumed that it was returning the time as a date format, didn't realise it was just milliseconds.
Also, beaten!

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



vanjalolz posted:

Whats the best way to get the age of a file in days?

edit:
$now = strtodate("now");
$result = filemtime($file);
$diff = $now - $result;
$days = floor(($diff%2629743.83)/86400) ;

If you ask me, the best way doesn't rely as much on magic numbers:

php:
<?
$now = new DateTime();
$ft = new DateTime(date('c',filemtime($avast)));
$diff = intval($now->format('z')) - intval($ft->format('z')) //days this year
      + ((intval($now->format('Y')) - intval($ft->format('Y'))) * 365); //in other years
?>
And I guess you could make PHP tell you how may days there are in a year, but I'm going to cross my fingers that nothing changes that for a long time.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


MrEnigma posted:

I can see uses for doing non-tables for data....variable columns, moving stuff way around. Some sites that allow for a theme or something could have some advantage...but yeah...not usually.

Except you can do those things with tables as well.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Edit: double post :(

duz fucked around with this message at 19:03 on Oct 6, 2008

Standish
May 21, 2001

Munkeymon posted:

And I guess you could make PHP tell you how may days there are in a year, but I'm going to cross my fingers that nothing changes that for a long time.
Actually it changed this year.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Standish posted:

Actually it changed this year.

Good point. I guess you would have to go back and add up the days from every year unless you were expecting short file lifetimes. Or the PHP devs could make a propper time span object.

Edit: kind of ugly, but it works according to Python's datetime class.
php:
<?
$now = new DateTime();
$ft = new DateTime(date('c',filemtime($filePath)));
//days this year
$diff = intval($now->format('z')) - intval($ft->format('z'));
//days in other years
$ft = intval($ft->format('Y'));
for($i = (intval($now->format('Y'))-1); $i >= $ft; --$i)
{
    $now = new DateTime('Dec 31, '.$i);
    $diff += intval($now->format('z')) + 1;
}
?>

Munkeymon fucked around with this message at 22:15 on Oct 6, 2008

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

Munkeymon posted:

Good point. I guess you would have to go back and add up the days from every year unless you were expecting short file lifetimes. Or the PHP devs could make a propper time span object.

Edit: kind of ugly, but it works according to Python's datetime class.
php:
<?
$now = new DateTime();
$ft = new DateTime(date('c',filemtime($filePath)));
//days this year
$diff = intval($now->format('z')) - intval($ft->format('z'));
//days in other years
$ft = intval($ft->format('Y'));
for($i = (intval($now->format('Y'))-1); $i >= $ft; --$i)
{
    $now = new DateTime('Dec 31, '.$i);
    $diff += intval($now->format('z')) + 1;
}
?>


This should give the exact same result, unless I am missing something.
php:
<?
$secsInDay = 60 * 60 * 24;
$daysOld =  floor((Time() - filemtime($filePath)) / $secsInDay);
?>

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Begby posted:

This should give the exact same result, unless I am missing something.
php:
<?
$secsInDay = 60 * 60 * 24;
$daysOld =  floor((Time() - filemtime($filePath)) / $secsInDay);
?>

Not every day has that many seconds. http://en.wikipedia.org/wiki/Daylight_saving_time

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

Munkeymon posted:

Not every day has that many seconds. http://en.wikipedia.org/wiki/Daylight_saving_time

Oh sure man, get all exact on me why don't you....

I think this whole calendar thing is bullshit anyways, we should start over and just count days since Chuck Norris was born or something and get rid of the whole weeks, months and years thing. Its all so complex and confusing.

nbv4
Aug 21, 2002

by Duchess Gummybuns
I have a class that handles printing the DOCTYPE and headers, as well as the footer on each page. At the top of the class declaration, I have all these things defined like so:

php:
<?
class page {

    var $page;
    var $title;
    var $year;
    var $copyright;
    var $auth;
    var $style;
    var $auth_level;
    var $get_sec;
    var $get_sec_q;
        
    var $page_title;
    
    var $doctype = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">";
        
    $meta_header = <<<EOF

        <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" />
EOF;
            
    var $advert = "";    
?>
Its giving me an error on the line where I define the meta header. Apparently the "EOF" thing is not allowed in the class declaration top part. What other options do I have here that don't include going through each line to escape the quotation marks? The meta header is going to be expanded to about three times the size and I just think it's dumb to have to escape quotation marks like that.

the php website suggests "nowdoc", but I'm using PHP 5.2.X, and those are only allowed in 5.3 and greater. :(

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



nbv4 posted:

I have a class that handles printing the DOCTYPE and headers, as well as the footer on each page. At the top of the class declaration, I have all these things defined like so:

Its giving me an error on the line where I define the meta header. Apparently the "EOF" thing is not allowed in the class declaration top part. What other options do I have here that don't include going through each line to escape the quotation marks? The meta header is going to be expanded to about three times the size and I just think it's dumb to have to escape quotation marks like that.

the php website suggests "nowdoc", but I'm using PHP 5.2.X, and those are only allowed in 5.3 and greater. :(

Use single quotes to delimit the strings?
php:
<?
var $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
$meta_header = '

    <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" />
';
?>

Zorilla
Mar 23, 2005

GOING APE SPIT

Munkeymon posted:

Use single quotes to delimit the strings?

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();

?>

Sharktopus
Aug 9, 2006

I'm using cakephp and sending this data to the save() function
code:
Array
(
    [Project] => Array
        (
            [name] => Testproj2
            [id] => 1
        )
 
    [User] => Array
        (
            [id] => Array
                (
                    [0] => 1
                    [1] => 2
                )
 
        )
 
)
Project is updating, but User should be populating a projects_users table which keeps track of the HABTM relationship, however nothing is getting done to the projects_users table. According to the documentation, I'm doing everything correctly. Has anyone here successfully gotten a HABTM to update using cakephp?

edit: Also, I've been asking around the cakephp channel on freenode for about a day and nobody there has even aknoleged that I have asked a question.

Sharktopus fucked around with this message at 05:55 on Oct 10, 2008

Stephen
Feb 6, 2004

Stoned

Sharktopus posted:

I'm using cakephp and sending this data to the save() function

Project is updating, but User should be populating a projects_users table which keeps track of the HABTM relationship, however nothing is getting done to the projects_users table. According to the documentation, I'm doing everything correctly. Has anyone here successfully gotten a HABTM to update using cakephp?

edit: Also, I've been asking around the cakephp channel on freenode for about a day and nobody there has even aknoleged that I have asked a question.

I can't answer your question, but I can tell you that I've spent days trying to figure out why their lovely model system isn't working properly. I ended up using $this->model->query(); more often than not just because I got sick and tired of writing ugly workarounds.

I recommend using a different framework (or none at all). I used CakePHP on three of my last projects and had no end of bugs trying to use their model system. Their documentation and community is absolutely terrible as well, barring a few exceptions.

sonic bed head
Dec 18, 2003

this is naturual, baby!
I have some questions about PHP CURL and cookies. If I want to post to a login page with a cookie I receive from first going to the login page, is the proper procedure to have two different CURL instances and save the first cookie in a cookiejar and send it again with the second CURL instance to the actual login form?

The situation is that I need to mimic logging onto a page that is made with Apache Struts that sets a JSESSIONID in a cookie. I need to first get the login page to get the JSESSIONID and then send the JSESSIONID with the request to the login form. Once I'm logged in, I just need to get a few words in a particular div, so that's no problem.

I currently try setting up one instance to fetch the login page and save the cookie to a file. then I close that curl instance and open another one to the actual login form that sends the cookie. The problem is that I keep getting the message that my session has expired. Is there some other way that I should be doing this?

Sharktopus
Aug 9, 2006

Stephen posted:

I can't answer your question, but I can tell you that I've spent days trying to figure out why their lovely model system isn't working properly. I ended up using $this->model->query(); more often than not just because I got sick and tired of writing ugly workarounds.

I recommend using a different framework (or none at all). I used CakePHP on three of my last projects and had no end of bugs trying to use their model system. Their documentation and community is absolutely terrible as well, barring a few exceptions.

I've taken your advice and switched to symfony and It's so, so much better than cakephp, and the community is very helpfull.

Roseo
Jun 1, 2000
Forum Veteran
Anyone have any suggestions for where I can read up on best practices for modularizing php pages? I'm in the process of taking an internal app out of the dark ages (It's coded entirely in tables and abysmal php)as I get free time, and there's a lot of code being duplicated all over the place, each doing the same thing but with slightly different behaviors. I'd like to set it up so that the code only is written in one place, to improve maintenence, but I'm a little fuzzy on what my options are when it comes to php as it's my first time using it.

It's terrible, the whole thing is written like:

code:

if ($address != "" && city != "") {
  echo "<td>"
  echo "<tr>"
  echo "Address: $address<br> City: $city"
  echo "</tr>"
  echo "</td>"
}

elseif ($address != "" && city == "") {
  echo "<td>"
  echo "<tr>"
  echo "Address: $address<br> City: none"
  echo "</tr>"
  echo "</td>"
}

elseif ($address == "" && city != "") {
  echo "<td>"
  echo "<tr>"
  echo "Address: none<br> City: $city"
  echo "</tr>"
  echo "</td>"
}

elseif ($address == "" && city == "") {
  echo "<td>"
  echo "<tr>"
  echo "Address: none<br> City: none"
  echo "</tr>"
  echo "</td>"
}
:barf:

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

jasonbar
Apr 30, 2005
Apr 29, 2005

Roseo posted:

:barf:

code:
<?php
$address = empty($address) ? "none" : $address;
$city = empty($city) ? "none" : $city;
echo "Address: $address<br />City: $city";
?>
You should really look into using some framework (I won't recommend one and the overhead / ramp up to getting started may or may not be worth it.) At the very least Smarty it up.

Edit: :colbert:

jasonbar fucked around with this message at 09:08 on Oct 11, 2008

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
As a newbie to PHP attempting to write a PHP/MySQL site related to a hobby, I am not sure whether something I want to do is secure. I want to put the details of the account used to change the database in a file called "commonthings.php", and then "include" that file at the top of most of the other PHP files on the site so that when I change the password I need do it in only one place. But I'm not sure whether it's actually secure. I am aware, from the book I'm learning from, that "included" files can be stored in a location that web users don't have access to, but I had a quick look in the interface my hosting provider provides to upload files and could not work out how to put files in the extra locations they specify for included files.

To give an example of code: (please note in several places I have split "echo" commands, or definitions of strings, that are a single command in the real programs into multiple commands here so that they do not break tables)

Here is commonthings.php in its entirety (but with the actual account details removed, naturally)

code:
<?php

$host="REMOVED";
$user="REMOVED";
$password="REMOVED";
$database="REMOVED";

$connecterrormessage = "Failed to connect to MySQL database. Suggest you try a second ";
$connecterrormessage .= "time. If the same error message appears again, try again later.";
$readerrormessage = "Failed to read from MySQL database. Suggest you try a second ";
$readerrormessage .= "time. If the same error message appears again, try again later.";
$writeerrormessage = "Failed to write to MySQL database. Suggest you try a second ";
$writeerrormessage .= "time. If the same error message appears again, try again later.";
$unexpectederrormessage = "Reading from MySQL database produced an unexpected result. ";
$unexpectederrormessage .= "Suggest you try a second time. ";
$unexpectederrormessage .= "If the same error message appears again, contact Administrator.";

session_start();

?>
The user is not intended to actually visit commonthings.php, but I have checked that if I point my browser there I just see a blank page. I guess the main concern is whether a knowledgeable user could find out what text the php file actually contains (which of course would be a concern whether I use this method, or just have the account details at the top of every file). Here is an example of a page that uses commonthings.php: (it is the page that allows a user to login to his account and then be automatically redirected back to the main page of the application, as you can probably tell by looking at it.)

code:
<?php
include("commonthings.php");

if ( isset($_POST[Name]) or isset($_POST[Password]) ) {
    $cxn = mysqli_connect($host,$user,$password,$database) or die ($connecterrormessage);
    if ( get_magic_quotes_gpc() ) {
        $EscapedName     = @$_POST[Name];
        $EscapedPassword = @$_POST[Password];
    } else {
        $EscapedName     = mysqli_real_escape_string($cxn,@$_POST[Name]);
        $EscapedPassword = mysqli_real_escape_string($cxn,@$_POST[Password]);
    }
    $qr = "SELECT UserID, Password, DenyAccess, UserValidated ";
    $qr .= "FROM User WHERE Name = '$EscapedName'";
    $QueryResult = mysqli_query ($cxn,$qr) or die($readerrormessage);
    if ( mysqli_num_rows($QueryResult) == 0 ) {
        $_SESSION[LoggedIn] = 0;
        $ErrorCode = 1;
    } else if ( mysqli_num_rows($QueryResult) > 1 ) {
        $_SESSION[LoggedIn] = 0;
        $ErrorCode = 3;
    } else {
        extract( mysqli_fetch_assoc( $QueryResult ) );
        if ( $DenyAccess ) {
            $_SESSION[LoggedIn] = 0;
            $ErrorCode = 4;
        } else if ( !$UserValidated ) {
            $_SESSION[LoggedIn] = 0;
            $ErrorCode = 5;
        } else if ( $Password == $EscapedPassword ) {
            $_SESSION[LoggedIn]   = 1;
            $_SESSION[MyUserID]   = $UserID;
            $_SESSION[MyUserName] = $EscapedName;
        } else {
            $_SESSION[LoggedIn] = 0;
            $ErrorCode = 2;
        }
    }
} else {
    $ErrorCode = 0;
}

echo "<html><head><title>Log In</title>";

if ( @$_SESSION[LoggedIn] ) {
    echo "<script type=\"text/javascript\"><!--\nfunction delayer(){\nwindow.location =";
    echo "\"index.php\"\n}\n//-->\n</script>\n</head><body onLoad=\"setTimeout('delayer()', ";
    echo "2000)\">You are logged in as {$_SESSION[MyUserName]}. This page will redirect";
    echo " to the Main Page in 2 seconds. (If you do not have JavaScript enabled for ";
    echo "this site, this will not happen; <a href=\"index.php\">click here</a> instead ";
    echo "to return to the Main Page.)</body></html>";
} else {
    echo "<body>";
    switch ( $ErrorCode ) {
    case 1: echo "Failed to find user named {$EscapedName} in the database.<p>"; break;
    case 2: echo "Incorrect password for user {$EscapedName}.<p>"; break;
    case 3: echo "There is more than one user named {$EscapedName} in the database. This ";
            echo "is not supposed to happen. Please contact Administrator.<p>"; break;
    case 4: echo "Cannot login: an Administrator ";
            echo "has denied you access to your account.<p>"; break;
    case 5: echo "Cannot login: Your account is not validated yet. Please check your emails ";
            echo "and follow the instructions in the validation email you were sent.";
            echo " Accounts that are not validated within two weeks are deleted automatically.";
            echo " You may visit <a href=\"resendvalemail.php\">this page</a> to reattempt";
            echo " sending the email.<p>"; break;
    }
    include("logintool.php");
    EchoLoginForm();
    echo "</body></html>";
}
?>
Is this secure? If not is there anything that can easily be done to make it secure?

The account whose details are provided by commonthings.php has SELECT, DELETE, INSERT and UPDATE privileges.

Hammerite fucked around with this message at 14:06 on Oct 11, 2008

Roseo
Jun 1, 2000
Forum Veteran

jasonbar posted:

code:
<?php
$address = empty($address) ? "none" : $address;
$city = empty($city) ? "none" : $city;
echo "Address: $address<br />City: $city";
?>
You should really look into using some framework (I won't recommend one and the overhead / ramp up to getting started may or may not be worth it.) At the very least Smarty it up.

Edit: :colbert:

Yeah, that code's pretty much what I did. No point keeping all the things that're the same between the two states in the variable when all I want is the address or "none".

I'll look into a framework. Are they usually easy to integrate into existing sites or is it better to make the site up from scratch if you use one?

Roseo fucked around with this message at 14:48 on Oct 11, 2008

jasonbar
Apr 30, 2005
Apr 29, 2005

Roseo posted:

Yeah, that code's pretty much what I did. No point keeping all the things that're the same between the two states in the variable when all I want is the address or "none".

I'll look into a framework. Are they usually easy to integrate into existing sites or is it better to make the site up from scratch if you use one?

Based on what you posted previously, start from scratch.

jasonbar
Apr 30, 2005
Apr 29, 2005

Hammerite posted:

Is this secure? If not is there anything that can easily be done to make it secure?

Relating to only the secureness of the file inclusion, there is nothing inherently insecure about it. You should really keep commonthings.php outside of the webroot so that there is no chance of anyone actually getting it through their browser.

I was recently contracted to fix a lawyers website because "it was showing all of the code." Turns out they had a new system admin who moved everything over to a new server and never setup PHP. Their entire config file with all of their auth. info was available in plaintext. Not cool.

Zorilla
Mar 23, 2005

GOING APE SPIT

jasonbar posted:

Relating to only the secureness of the file inclusion, you should be fairly safe. You should really keep commonthings.php outside of the webroot so that there is no chance of anyone actually getting it through their browser.

If this isn't an option, you could also put something at the top of the script to check to see if basename($_SERVER["SCRIPT_FILENAME"]) is equal to "commonthings.php" and stop the script right there if it is (though having other files with the same name breaks this). Or you could define a constant in each child page like ALLOWACCESS and check it in commonthings.php. Most CMSes do one of these two things.

This doesn't protect against server admins being idiots, but you've got other problems if your PHP keeps showing.

Zorilla fucked around with this message at 21:08 on Oct 11, 2008

sonic bed head
Dec 18, 2003

this is naturual, baby!

jasonbar posted:

Relating to only the secureness of the file inclusion, there is nothing inherently insecure about it. You should really keep commonthings.php outside of the webroot so that there is no chance of anyone actually getting it through their browser.

I was recently contracted to fix a lawyers website because "it was showing all of the code." Turns out they had a new system admin who moved everything over to a new server and never setup PHP. Their entire config file with all of their auth. info was available in plaintext. Not cool.

I have a question about this. How does that really happen? I thought that if a php server is asked to serve a .php file, it would always interpret it before it sends the response to the client. If that's the case, as long as the config stuff isn't being echoed, how could the browser show the plaintext?

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker

sonic bed head posted:

I have a question about this. How does that really happen? I thought that if a php server is asked to serve a .php file, it would always interpret it before it sends the response to the client. If that's the case, as long as the config stuff isn't being echoed, how could the browser show the plaintext?

Php files are treated as plaintext if the server isn't setup to handle them.

Zorilla
Mar 23, 2005

GOING APE SPIT

sonic bed head posted:

I have a question about this. How does that really happen? I thought that if a php server is asked to serve a .php file, it would always interpret it before it sends the response to the client. If that's the case, as long as the config stuff isn't being echoed, how could the browser show the plaintext?

If PHP isn't configured, the web server interprets it as text/plain and just sends off the script without processing it. (beaten)

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

duck monster posted:

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.

Not necessarily. PHP stacks output buffers. But it still won't work for nbv4's purpose, because you can't break to output in the class declaration either.

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