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

I'm working on a PHP RESTful app taking zip files, unpacking them, storing them somewhere.

I have a problem where php://input is always NULL.

I'm using a short script that's parsing multipart-form/data content when in a 'PUT' query and it works fine everywhere except when I'm including it within another particular script, where suddenly everything fails.

I still get the normal $_SERVER['CONTENT_LENGTH'] and whatnot, php://input never returns anything there.

The results are also the same when using a normal upload (not multipart).

I'm testing everything with these queries:
code:
curl -X PUT http://mysandbox.com/widget/partial/ -F zip=@testagain.zip
curl -X PUT http://mysandbox.com/widget/partial/ --data-binary @testagain.zip
What's the kind of contextual stuff what would cause these problems?

EDIT: forgot a very important detail:
the script which includes the file happens to already read php://input. Is it supposed to be possible to be accessed only once?

MononcQc fucked around with this message at 20:36 on Feb 16, 2009

Adbot
ADBOT LOVES YOU

KuruMonkey
Jul 23, 2004
I just want to be clear up front; I'm not looking to start a fight here...

Zorilla posted:

I'm surprised anyone has to ask. Look at Jo3sh's code, then look at mine. Which is easier to look at?

Well, at that level of (minimal) complexity to the php value injection, yours is a little easier on the eye.

But...

strings didn't need to be built like this:
php:
<?
echo "<tag attribute=\"value\" attribute=\"$value\" />";
?>
when this is possible:
php:
<?
echo "<tag attribute='value' attribute='".$value."' />";
?>
which will, incidentally, color code the variable for you.

Zorilla posted:

[*]You're probably not tabbing the output or using line breaks at the end of each string, so you end up with poo poo like <table><tr><td>Poop</td><td><table><tr><td>Holy poo poo a table within a table</td></tr></table></td></tr></table> when you view source.

True, but then if I'm debugging the markup, I'll be doing it either in the PHP, in which case who cares. Or I'll be debugging in firebug, which indents for you; so who cares? And lastly; for production markup, I want it minified anyway, so... well, you get the picture.

Zorilla posted:

Someone may want to edit the layout in the future and it's a real bitch to do that if everything is an echo statement.

I guess this comes down to whether its a PHP file that has to output some HTML, or if its an HTML file that needs some PHP injecting; I'll tend to stick with the look and feel of the majority language of a file.

Then again; if I have a block that needs to do some conditional markup, I prefer it to be in 'PHP mode'. And again (again) I have a lot of code that is in the form of classes that return the relevant markup for their content/state - so a lot of that is code that will need
code:
<?php echo $var->render($options); ?>
all over the place, which I find worse, aesthetically.

And then I get to peruse code like this;
php:
<?php if ($canEdit || $this->params->get('show_title') || $this->params->get('show_pdf_icon') ||
$this->params->get('show_print_icon') || $this->params->get('show_email_icon')) : ?>
<table class="contentpaneopen<?php echo $this->params->get'pageclass_sfx' ); ?>">
<tr>
    <?php if ($this->params->get('show_title')) : ?>
    <td class="contentheading<?php echo $this->params->get'pageclass_sfx' ); ?>" width="100%">
        <?php if ($this->params->get('link_titles') && $this->article->readmore_link != '') : ?>
        <a href="<?php echo $this->article->readmore_link?>" class="contentpagetitle
<?php echo $this->params->get'pageclass_sfx' ); ?>">
            <?php echo $this->escape($this->article->title); ?></a>
        <?php else : ?>
            <?php echo $this->escape($this->article->title); ?>
        <?php endif; ?>
    </td>
    <?php endif; ?>
    <?php if (!$this->print) : ?>
        <?php if ($this->params->get('show_pdf_icon')) : ?>
        <td align="right" width="100%" class="buttonheading">
        <?php echo JHTML::_('icon.pdf',  $this->article$this->params$this->access); ?>
        </td>
        <?php endif; ?>

And I cannot see the sense in that. (thats a Joomla view, by the way).
Honestly; that would be far easier if it were built the PHP-centric style; I know because I've written overrides for it, and oh god does it benefit from a refactoring.

What I guess I can't understand is a need to post 'Oh god you used echo; what the christ?' ever; its a question of taste, surely?

Though you answered my question I guess; no real reason one way is right and the other wrong.

KuruMonkey fucked around with this message at 23:17 on Feb 16, 2009

b0lt
Apr 29, 2005

KuruMonkey posted:

And then I get to peruse code like this;
php:
<?php if ($canEdit || $this->params->get('show_title') || $this->params->get('show_pdf_icon') ||
$this->params->get('show_print_icon') || $this->params->get('show_email_icon')) : ?>
<table class="contentpaneopen<?php echo $this->params->get'pageclass_sfx' ); ?>">
<tr>
    <?php if ($this->params->get('show_title')) : ?>
    <td class="contentheading<?php echo $this->params->get'pageclass_sfx' ); ?>" width="100%">
        <?php if ($this->params->get('link_titles') && $this->article->readmore_link != '') : ?>
        <a href="<?php echo $this->article->readmore_link?>" class="contentpagetitle
<?php echo $this->params->get'pageclass_sfx' ); ?>">
            <?php echo $this->escape($this->article->title); ?></a>
        <?php else : ?>
            <?php echo $this->escape($this->article->title); ?>
        <?php endif; ?>
    </td>
    <?php endif; ?>
    <?php if (!$this->print) : ?>
        <?php if ($this->params->get('show_pdf_icon')) : ?>
        <td align="right" width="100%" class="buttonheading">
        <?php echo JHTML::_('icon.pdf',  $this->article$this->params$this->access); ?>
        </td>
        <?php endif; ?>

And I cannot see the sense in that. (thats a Joomla view, by the way).
Honestly; that would be far easier if it were built the PHP-centric style; I know because I've written overrides for it, and oh god does it benefit from a refactoring.

What I guess I can't understand is a need to post 'Oh god you used echo; what the christ?' ever; its a question of taste, surely?

Though you answered my question I guess; no real reason one way is right and the other wrong.

Yeah, that's just an enormous clusterfuck. I like building the HTML using string concatenation for something like that, and then echoing it at the end. It's much easier to parse that way for me.

Zorilla
Mar 23, 2005

GOING APE SPIT

KuruMonkey posted:

(thats a Joomla view, by the way).

Yeah, that's when things get a little hairy, though I really don't see how using echo statements does anything but exacerbate this problem. I'm not sure your example is very fair since it exaggerates the problem by cramming a lot into a small space. No wonder you can't read it. It gets a lot better if you tabs things sanely:
php:
<?php
if (
    $canEdit ||
    $this->params->get('show_title') ||
    $this->params->get('show_pdf_icon') ||
    $this->params->get('show_print_icon') ||
    $this->params->get('show_email_icon')
    ) {
?>
<table class="contentpaneopen<?=$this->params->get'pageclass_sfx' )?>">
    <tr>
<?php
    if ($this->params->get('show_title')) {
?>
        <td class="contentheading<?=$this->params->get'pageclass_sfx' )?>" width="100%">
<?php
        if ($this->params->get('link_titles') && $this->article->readmore_link != '') {
?>
            <a href="<?=$this->article->readmore_link?>" class="contentpagetitle<?=$this->params->get'pageclass_sfx' )?>">
                <?=$this->escape($this->article->title)?>
            </a>
<?php
        } else {
?>
            <?=$this->escape($this->article->title)?>
<?php
        }
?>
        </td>
<?php
    }
 ?>
<?php
    if (!$this->print && $this->params->get('show_pdf_icon') {
?>
        <td align="right" width="100%" class="buttonheading">
            <?=JHTML::_('icon.pdf',  $this->article$this->params$this->access)?>
        </td>
<?php
    }
?>
</table>
<?php
}
?>

There. Now I have a pretty good idea what's going on with just a glance. Notice how I'm putting each <?php and ?> on a new line. This way, the indentation for PHP and HTML stay independent of one another. I really recommend doing it this way for documents this large. Tabs never end up in the right spot if you don't.

I build and edit WordPress templates all the time, and this is about as complex as it gets. The few times I've messed with Joomla were no different. If things get any more complicated than this, you really should consider splitting up the views into multiple templates as its layout is probably far too dynamic for just one. Also consider preparing variables into cleaner objects/arrays first that get used in the view portion of the code (I know this usually isn't an option in CMSes like this where things like $this->params->get('link_titles') have known meanings to designers and $output["title"] may not).

If you are totally against PHP templating for certain situations, I still recommend exploring heredoc for outputting large blocks of HTML with little clutter. I think it still lets you inject variables into them like echo "words word $string words"; would, so it's still somewhat suitable for templating.

Zorilla fucked around with this message at 01:12 on Feb 17, 2009

niralisse
Sep 14, 2003
custom text: never ending story

MononcQc posted:


EDIT: forgot a very important detail:
the script which includes the file happens to already read php://input. Is it supposed to be possible to be accessed only once?

Well that would do it. rewind() the file pointer you opened against php://input.

KuruMonkey
Jul 23, 2004

Zorilla posted:

If things get any more complicated than this, you really should consider splitting up the views into multiple templates as its layout is probably far too dynamic for just one.

That wasn't MY joomla view! Jesus.

zorilla posted:

If you are totally against PHP templating for certain situations, I still recommend

I have a solution that works. I wasn't the one yelling 'arg!' at people for using echo. I've made a considered (professional) decision about how and when I think its time to go to echo statements and string concatenation.

I'm not looking to change for any reason that resolves to 'person X thinks it looks better'. I was asking if there was a functional/optimisation reason to do things the other way I wasn't aware of.

If there ain't one, I'll keep on truckin'

Edit; I wonder if its that my background is programming->websites not websites->programming? Is yours the opposite? Or is that irrelevant? I'm just thinking that coming from "cout >> blah >> blah >>endl;" for hundreds of lines might color what is 'readable' for output code, or rather that lines upon lines of printf("%s\n", name); is just what I'm used to / expect :)

KuruMonkey fucked around with this message at 01:52 on Feb 17, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

KuruMonkey posted:

I'm not looking to change for any reason that resolves to 'person X thinks it looks better'. I was asking if there was a functional/optimisation reason to do things the other way I wasn't aware of.

If there ain't one, I'll keep on truckin'
That's kind of why I broke out into a bullet list of reasons why I think it's better. It's my opinion that how the code looks has everything to do with practicality and readability.

For me, separating the control logic and the view as much as possible is pretty important. However, I've seen instances where forms or sections of pages get assigned to variables and then get used in simplistic templates. This sounds closer to the approach you prefer and is also reasonable.

Definitely not looking for a flame war, but I was curious to see why somebody would use code constructs designed to output text line-by-line for entire pages for reasons other than inexperience, carelessness, or worse, malice.

KuruMonkey posted:

Edit; I wonder if its that my background is programming->websites not websites->programming? Is yours the opposite? Or is that irrelevant? I'm just thinking that coming from "cout >> blah >> blah >>endl;" for hundreds of lines might color what is 'readable' for output code, or rather that lines upon lines of printf("%s\n", name); is just what I'm used to / expect
It could be- I can see why some habits would have to be relearned if you're suddenly dealing with whole HTML pages instead of a few lines at a time written to a console. Since this is PHP, I rely heavily on the templating system, but even if I were to move on to Python or something else with no built-in template system, templates are usually still the answer because somebody will have ported Smarty (or similar) to whatever you're using.

Zorilla fucked around with this message at 02:26 on Feb 17, 2009

KuruMonkey
Jul 23, 2004
I wrote a long post here, and the internet swallowed it.

Imagine it was both prosaic and poetic, and stirred deep emotions.

Of course in reality it can be re-created thus; "Thats cool, bud."

MrMoo
Sep 14, 2000

I would line up the braces and remove some of the clutter, but depends on the rest of the code. Of course you could play with the layout for ever, my preference for templates is more content less code.

php:
<?
$article       = $this->article;
$params        = $this->params;

$has_title     = $params->get( 'show_title' );
$has_pdf_icon  = $this->print ? false : $params->get( 'show_pdf_icon' );
$has_more      = $params->get( 'link_titles' ) && !isempty($article->readmore_link);

$pageclass_sfx = $params->get( 'pageclass_sfx' );
$article_title = $this->escape($article->title)
$readmore_link = $article->readmore_link;

if ($canEdit)
{
?>
<table class="contentpaneopen<?=$pageclass_sfx?>">
    <tr>
<?
    if ($has_title)
    {
?>
        <td class="contentheading<?=$pageclass_sfx?>" width="100%">
<?
        if ($has_more)
        {
?>
                <a href="<?=$readmore_link?>" class="contentpagetitle<?=$pageclass_sfx?>">
<?
        }

        echo $article->title;

        if ($has_more)
        {
?>
            </a>
<?
        }
?>
        </td>
<?
    }

    if ($has_pdf_icon)
    {
?>
        <td align="right" width="100%" class="buttonheading">
            <?=JHTML::_('icon.pdf',  $article$params$this->access)?>
            </td>
<?
    }
?>
    </tr>
</table>
<?
}
?>


Don't forget for content with a lot of substitution to use the following:
php:
<?
echo <<<MOO
<td>$this $is $a $lot $of $substitutions $without $crazy $brackets $or $echos $everywhere</td>
MOO;
?>

MrMoo fucked around with this message at 03:31 on Feb 17, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT
Heh, so basically what I said already (except for Allman-style indentation)

MrMoo
Sep 14, 2000

Zorilla posted:

Heh, so basically what I said already (except for Allman-style indentation)

Yup, I just wanted to play with the code a bit.

:buddy::coffee:

b0lt
Apr 29, 2005
My problem with that style is the entire
php:
<?php
?> <?php ?>

<?php
?>
<?php
?>
cruft that gets splattered all over the code.

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH
php:
<?php
$article       $this->article;
$params        $this->params;

$has_title     $params->get'show_title' );
$has_pdf_icon  $this->print false $params->get'show_pdf_icon' );
$has_more      $params->get'link_titles' ) && !isempty($article->readmore_link);

$pageclass_sfx $params->get'pageclass_sfx' );
$article_title $this->escape($article->title)
$readmore_link $article->readmore_link;
?>

<?php if($canEdit): ?>
    <table class="contentpaneopen<?= $pageclass_sfx ?>">
        <tr>
            <?php if($has_title) : ?>
                <td class="contentheading<?= $pageclass_sfx ?>" width="100%">
                    <?php if($has_more) : ?><a href="<?= $readmore_link ?>" class="contentpagetitle<?= $pageclass_sfx ?>"><?= $article->title?></a>
                    <?php else : ?><?= $article->title?><?php endif; ?>
                </td>
            <?php endif; ?>
            <?php if($has_pdf_icon) : ?>
                <td align="right" width="100%" class="buttonheading">
                    <?= JHTML::_('icon.pdf',  $article$params$this->access?>
                </td>
            <?php endif; ?>
        </tr>
    </table>
<?php endif; ?>

:colbert:

supster fucked around with this message at 06:54 on Feb 17, 2009

KarmaticStylee
Apr 21, 2007

Aaaaaughibbrgubugbugrguburgle!
Is there anything wrong with heredoc <<<

Internet Headache
May 14, 2007

KarmaticStylee posted:

Is there anything wrong with heredoc <<<
No, it's even better performance than using multiple echo calls.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
My school uses a login form (student id # and a password) to get into the wifi on campus. It's a pain in the rear end because it doesn't remember your mac address after you login, so you have to reenter your credentials if you change rooms or lose signal. They were going to replace it but of course it's spring 2009 and it's not here.

I wrote a greasemonkey script to do it for me which made life a lot easier, but now I want a command line solution for a project I'm working on that needs constant wifi access (a rover that we want to drive across campus over the internet). I figured it would be easy enough to emulate the POST done by the form, but I can never get a successful response from it.

Here's the response (via Firebug):



Here's my code:

http://pastebin.com/m43c443d2

I've tried different combinations of urlencode(), htmlentities(), plain text, and with and without the escaped quotes around the cookie params. Can't get it to work!

Also, is there a better way to get the IP on a no webserver php install?

fletcher fucked around with this message at 01:46 on Feb 19, 2009

KarmaticStylee
Apr 21, 2007

Aaaaaughibbrgubugbugrguburgle!

Internet Headache posted:

No, it's even better performance than using multiple echo calls.

I thought so. Yet time and again I see people with multiple echo lines. :doh:

sonic bed head
Dec 18, 2003

this is naturual, baby!

fletcher posted:

My school uses a login form (student id # and a password) to get into the wifi on campus. It's a pain in the rear end because it doesn't remember your mac address after you login, so you have to reenter your credentials if you change rooms or lose signal. [url=http://media.https://www.thespartandaily.com/media/storage/paper852/news/2008/09/17/News/New-Campus.WiFi.Planned.For.2009-3435439.shtml]They were going to replace it[/url] but of course it's spring 2009 and it's not here.

I wrote a greasemonkey script to do it for me which made life a lot easier, but now I want a command line solution for a project I'm working on that needs constant wifi access (a rover that we want to drive across campus over the internet). I figured it would be easy enough to emulate the POST done by the form, but I can never get a successful response from it.

Here's the response (via Firebug):



Here's my code:

http://pastebin.com/m43c443d2

I've tried different combinations of urlencode(), htmlentities(), plain text, and with and without the escaped quotes around the cookie params. Can't get it to work!

Also, is there a better way to get the IP on a no webserver php install?

If this is a possibility for you, I think you should try using the HTTP Request PEAR extension. The syntax is a lot easier than curl and they have custom methods to add cookies. You don't have to write it as a long string, you can add them individually and the extension formats it all correctly.

http://pear.php.net/manual/en/package.http.http-request.cookie.php

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

sonic bed head posted:

If this is a possibility for you, I think you should try using the HTTP Request PEAR extension. The syntax is a lot easier than curl and they have custom methods to add cookies. You don't have to write it as a long string, you can add them individually and the extension formats it all correctly.

http://pear.php.net/manual/en/package.http.http-request.cookie.php

Thanks for the link, I'm liking this more than using cURL directly already.

Question: when it fails on if (!PEAR::isError($req->sendRequest())), how do you get the error message?

edit: oh, getMessage(). durrrr

fletcher fucked around with this message at 02:38 on Feb 19, 2009

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I'm getting the same response using HTTP_Request instead of cURL

http://pastebin.com/m42ca337f

fletcher fucked around with this message at 06:37 on Feb 19, 2009

sonic bed head
Dec 18, 2003

this is naturual, baby!

fletcher posted:

I'm getting the same response using HTTP_Request instead of cURL

http://pastebin.com/m42ca337f

How can they send the email address in the cookie along with the original email address? Are you sure that the values are correct? Do you have HTTP Live Headers firefox extension installed? You can check in there to see if you are posting the correct values exactly.

Halo_4am
Sep 25, 2003

Code Zombie
Search is busted and I ctrl+f'd the whole thread for 'checkbox' so I'm sorry if this was covered, but I missed it.

In a site I create checkboxes based on results from the database. I'm looking for a non-retarded way of pre-checking already selected checkboxes. Every method I can think of involves any of the following: two sql statements, searching the whole sql array for every checkbox, searching the whole POST variable array for every checkbox.

Is there a clean way of comparing/searching both arrays once? Then outputing the figured results to HTML?

Example Sql results stashed in $queryresults:
code:
Category
--------
dresses
weapons
russianbrides
taxassistance
Example array contents stashed in cleaned up POSTed variable $categories
code:
weapons
taxassistance
Example of desired html output:
code:
[ ]dresses
[x]weapons
[ ]russianbrides
[x]taxassistance
I know the necessary html and all, the example is just to better demonstrate what I'm looking to do by comparing the sql results and user input array one time.

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
if I'm understanding you correctly, you want to make the checkboxes an array. So the name of the checkbox input would be 'stuff[]'. That way, you can look at it as an array in PHP:

php:
<?
$stuff = $_POST['stuff']; // This is an array thanks to the [].
while ($row = mysql_fetch_assoc($queryresults) // Stepping through each row of the query results...
{
  echo "<input type=checkbox name=stuff[] value=$row['information']"; // Start writing the input
  foreach ($stuff as $foobar) // Stepping through each value of the array...
  {
    if ($row['information'] == $foobar) echo " checked"; // If they match, mark this one checked.
  }
  echo ">"; // Close the input
}
?>
The html is ugly but I hope you get the idea. I've never actually done this with checkboxes but I do it all the time with multi selects, so I'm guessing the same principle applies. A google search seemed to confirm that.

Golbez fucked around with this message at 02:53 on Feb 20, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT
Couldn't you just use in_array()

php:
<?php
$stuff $_POST['stuff'];
?>
<!-- start of form -->
<?php while ($row mysql_fetch_assoc($queryresults)) { ?>
    <input type="checkbox" name="stuff[]" value=<?php echo $row['information']; ?>"<?php if (in_array($row['information'], $stuff)) { ?> checked="checked"<?php ?> />
<?php ?>
<!-- end of form -->

Zorilla fucked around with this message at 03:18 on Feb 20, 2009

Halo_4am
Sep 25, 2003

Code Zombie

Golbez posted:

if I'm understanding you correctly, you want to make the checkboxes an array. So the name of the checkbox input would be 'stuff[]'. That way, you can look at it as an array in PHP:

php:
<?
// php wuz here?>
The html is ugly but I hope you get the idea. I've never actually done this with checkboxes but I do it all the time with multi selects, so I'm guessing the same principle applies. A google search seemed to confirm that.

That's exactly what I'm looking to do, and is currently how I'm doing it. My problem with the approach is that though it works... it seems terribly inefficient. The problem can be summed up by looking at just your comments (added my own for clarity of my view).

php:
<?
// Stepping through each row of the (100) query results...
  foreach (1 result of 100) 
    //check and see if matches anything in this array of (50) items
        // If match found, mark this one checked.
?>
It's effectively searching 50 items 100 different times. I know it works and is probably a very common solution, but it doesn't seem like it would scale very well.

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

Halo_4am posted:

That's exactly what I'm looking to do, and is currently how I'm doing it. My problem with the approach is that though it works... it seems terribly inefficient. The problem can be summed up by looking at just your comments (added my own for clarity of my view).

php:
<?
// Stepping through each row of the (100) query results...
  foreach (1 result of 100) 
    //check and see if matches anything in this array of (50) items
        // If match found, mark this one checked.
?>
It's effectively searching 50 items 100 different times. I know it works and is probably a very common solution, but it doesn't seem like it would scale very well.

Then Zorilla may have the solution for both of us, seems much more 'pure', but that's assuming in_array is more efficient than a foreach. Which I'd have to assume it is.

Zorilla
Mar 23, 2005

GOING APE SPIT

Golbez posted:

Then Zorilla may have the solution for both of us, seems much more 'pure', but that's assuming in_array is more efficient than a foreach. Which I'd have to assume it is.

People in this thread seem to be way too obsessed with the performance of small bits of code. By the time an application is big enough for optimizations to matter, the database will always, always, always be your performance bottleneck, not some loop or echo statement that could be 0.0000000018 seconds faster if done a certain way.

BriteNite
Feb 28, 2004

Halo_4am posted:

That's exactly what I'm looking to do, and is currently how I'm doing it. My problem with the approach is that though it works... it seems terribly inefficient. The problem can be summed up by looking at just your comments (added my own for clarity of my view).


Set the names of the keys in the POSTed arrays to match the data you're pulling out of the db and then do isset:

php:
<?php
$stuff $_POST['stuff']; // This is an array thanks to the [].
while ($row mysql_fetch_assoc($queryresults// Stepping through each row of the query results...
{
     ?>
     <input type=checkbox name="stuff[<?php echo htmentities($row['information'?>]" 
          value="1" <?php echo (isset($stuff[$row['information']] && $stuff[$row['information']] == 1) 
          ? 'checked="checked"' '' ?> />
     <?php
}
?>

Array dereferences by key are fast.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

sonic bed head posted:

How can they send the email address in the cookie along with the original email address? Are you sure that the values are correct? Do you have HTTP Live Headers firefox extension installed? You can check in there to see if you are posting the correct values exactly.

I think it sets the cookies in javascript when you submit the form. Any other ideas? I'm gonna check out HTTP Live Headers

Halo_4am
Sep 25, 2003

Code Zombie

Zorilla posted:

People in this thread seem to be way too obsessed with the performance of small bits of code. By the time an application is big enough for optimizations to matter, the database will always, always, always be your performance bottleneck, not some loop or echo statement that could be 0.0000000018 seconds faster if done a certain way.

In an unrelated project where I do no development work of any kind. I maintain a SQL database that is terabytes in size (it's being restructured to be more manageable), but due to hardware, query optimizations, and creative index work the average sql query can be measured in milliseconds. Unfortunately the piece of poo poo .net app in front of it consumes 512mb of ram PER USER. This is an 'enterprise grade' web application.

I know it's a rather extreme example, but the point is that optimizations where possible always count for something. Comparing arrays like this has to be fairly common, and so a slower method of doing it that is duplicated dozens of times, multiplied by thousands of users adds up.

That said:

Zorilla posted:

Couldn't you just use in_array()

Seems like a more streamlined way of going about it.

BriteNite posted:

Set the names of the keys in the POSTed arrays to match the data you're pulling out of the db and then do isset:

Array dereferences by key are fast.
Seems even better. Thank you, I'll give it a go.

Awkward
Sep 4, 2006
I am a .. shirt?

BriteNite posted:

Set the names of the keys in the POSTed arrays to match the data you're pulling out of the db and then do isset:

php:
<?php
$stuff $_POST['stuff']; // This is an array thanks to the [].
while ($row mysql_fetch_assoc($queryresults// Stepping through each row of the query results...
{
     ?>
     <input type=checkbox name="stuff[<?php echo htmentities($row['information'?>]" 
          value="1" <?php echo (isset($stuff[$row['information']] && $stuff[$row['information']] == 1) 
          ? 'checked="checked"' '' ?> />
     <?php
}
?>

Array dereferences by key are fast.
It's a little more succinct (and marginally faster) to use !empty($stuff[$row['information']]) -- this is true for most of the times people do things like "if isset($var) && $var"

Awkward fucked around with this message at 12:10 on Feb 20, 2009

Tots
Sep 3, 2007

:frogout:
This should be trivial for anyone with more programming experience than me. I have a script that asks a user for the name of a file, then displays each line of the file. I simply want to display a message if the file is not found. or exit("$file can't be found") won't work because I don't want that to be displayed by default. (It assumes NULL can't be found when the page is first loaded.)

php:
<?
        echo "<hr> Please specify which file to display";
        
        echo "<form action=\"index.php\" method=\"get\">";
        echo "Name of file: <input type:=\"text\" name=\"fileToOpen\" />";
        echo "<input type=\"submit\"/>";
        echo "</form>";
        
        $openMe = $_GET["fileToOpen"];
        
        $file = fopen("$openMe" , "r") or exit;
        
        echo "<center><table border=\"1\">";
        
        while (!feof($file))
        {
        echo "<tr><td>" . fgets($file) . "</td></tr>";
        }
        
        if (feof($file));
        {
        echo '</center></table> You have reached the end of the file<br />';
        }
        fclose($file);?>

Tots fucked around with this message at 19:07 on Feb 20, 2009

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Tots posted:

This should be trivial for anyone with more programming experience than me...

php:
<?
        
echo "<hr> Please specify which file to display";
echo "<form action=\"index.php\" method=\"get\">";
echo "Name of file: <input type:=\"text\" name=\"fileToOpen\" />";
echo "<input type=\"submit\"/>";
echo "</form>";

if(isset($_GET['fileToOpen'))
{        
 $openMe = $_GET["fileToOpen"];
 if( $file = fopen("$openMe" , "r") ) // holy security hole!
 {
   echo "<center><table border=\"1\">";
   while (!feof($file))
   {
    echo "<tr><td>" . fgets($file) . "</td></tr>";
   }
   echo '</center></table> You have reached the end of the file<br />';
  fclose($file);
 }
 else
 {
   echo "no file";
 }
}
?>
I'll leave it to you to figure out why the way you are handling the file open is a huge security problem and to fix it.

[edit]\/ Yes, that is is. you can enter '/etc/passwd' in your form or something else as nefarious.

Lumpy fucked around with this message at 20:20 on Feb 20, 2009

Tots
Sep 3, 2007

:frogout:
Ah yes, I suppose someone would be able to navigate to the root from there. Right now I'm just trying to figure out the basics, so I'm just throwing together random scripts. I don't plan on applying the above script to anything.

Is that the security problem you were talking about? If not then I'm not sure what it is. I'll try to think over a way to fix this, and if I can't I'll be back here. :)

Zorilla
Mar 23, 2005

GOING APE SPIT

Tots posted:

Is that the security problem you were talking about? If not then I'm not sure what it is. I'll try to think over a way to fix this, and if I can't I'll be back here. :)
The problem is that you've just built a front end for anybody on the internet to access files on your web server with the same permissions your web server user account/group has. Even if there were a way to limit access to just files inside the document root, there's still the possibility of being able to print out raw PHP scripts or other files with sensitive information like database usernames and passwords.

I'm not sure there's a good way to do exactly what you're doing. Any file management I've seen in PHP applications (such as WordPress) involves presenting you with a list of files and abstracting the input it expects back.

By abstracting, I mean that even if you're given just a checkbox or a delete button or something, those parts of the form never reference the name of a file directly because that can be tampered. Instead, it could be called something like "delete[]". If "delete[5]" gets checked, for instance, it's up to the program to figure out that the 5th checkbox is associated with file you intend to delete.

Edit: I got carried away and made an example (totally untested):
php:
<?php

$file_path dirname(__FILE__) . "/safe_directory";

if ( !file_exists($file_path) ) {
    $error "The path &quot;".$file_path."&quot; could not be found.";
} else if ( !is_writable($file_path) ) { // a bit unreliable in Windows. Consider downloadig the is_really_writable() script.
    $error "The path &quot;".$file_path."&quot; could not be opened for writing. Please check file permissions.";
} else {
    
    $file_list glob($file_path);

    if ( isset($_POST["submit"]) && is_array($_POST["delete"]) ) {
        for ($i 0;$i count($_POST["delete"]);$i++) {
            if ($_POST["delete"][$i] != "") {
                unlink($file_path."/".$file_list[$i]);
            }
        }
        $message "File(s) deleted.";
    }
    
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
<title>File Deleter</title>
<style type="text/css">
table {margin: 0 auto 1em;}
table td {border: 1px solid #000;}

.message, .error {padding: 10px;text-align: center;}
.message {background-color: #cdc;border: 1px solid #bca;}
.error {background-color: #fcc;border: 1px solid #faa;}
</style>
</head>
<body>

<?php
if ($error) {
?>
<p class="error"><?php echo $error?></p>

<?php
}

if ($message) {
?>
<p class="message"><?php echo $message?></p>

<?php
}

if (!$error) {
?>
<form name="files" action="<?php echo basename(__FILE__); ?>" method="post">
    <table>
<?php
    foreach ($file_list as $file) {
?>
        <tr>
            <td><?php echo $file?></td>
            <td>
                <input type="checkbox" name="delete[]" id="delete[]" value="Delete" />
                <label for="delete[]">Delete</label>
            </td>
        </tr>
<?php
    }
?>
        <tr>
            <td></td>
            <td><input type="submit" name="submit" value="Delete Selected" /></td>
        </tr>
    </table>
</form>
<?php
}
?>
</body>
</html>

Zorilla fucked around with this message at 23:37 on Feb 22, 2009

sonic bed head
Dec 18, 2003

this is naturual, baby!

fletcher posted:

I think it sets the cookies in javascript when you submit the form. Any other ideas? I'm gonna check out HTTP Live Headers

If this is all done over regular HTTP and not some fancy vpn certificate or something like that, there has to be a way for you to automate it. How did HTTP Live Headers work out?

Tots
Sep 3, 2007

:frogout:
Disclaimer: I am a retard.

Now that we've gotten that out of the way, can someone please help me wrap my head around this.

I'm using someone else's code to accomplish an extremely simple task, but I can't wrap my head around how it works.

All I want is a listing of files in a directory.

php:
<?php

    
if ($path opendir('/home/thetotsn/public_html/BunnyPics/')) {
    while (false !== ($file readdir($path))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";
        }
    }
    closedir($path);
}


?>

I don't understand why opendir() and readdir() are conditions the first (and only) time they appear in the code. How can you check something that hasn't been initialized in any way? In what I've read so far, I've seen that php is a weak language, but this still doesn't make sense. Is it declaring them at the same time it checks them?

Whatever, assuming that it declares them while it's checking them or whatever the gently caress, I tried to rewrite it, but it doesn't work and I don't know why.

php:
<?
opendir('/home/thetotsn/public_html/BunnyPics/');

while (false !== ($file = readdir('/home/thetotsn/public_html/BunnyPics/'))
    {
    echo "$file\n";
    }
closedir('/home/thetotsn/public_html/BunnyPics/');
?>
Can someone give me a hint?

spiritual bypass
Feb 19, 2008

Grimey Drawer
I'm not too sure about what you already wrote, but how about using the backtick (`) to execute a command and use its results? As in `ls /home/royallthefourth/porn`

Anyone see any problems with that approach?

Tots
Sep 3, 2007

:frogout:
Holy gently caress, my eyes have been opened.

I would still like to understand why my code doesn't work though.

Adbot
ADBOT LOVES YOU

Internet Headache
May 14, 2007
http://php.net/opendir
php:
<?
$dh = opendir('/home/thetotsn/public_html/BunnyPics/');

while (false !== ($file = readdir($dh))) {
    echo "$file\n";
}
closedir($dh);
?>
opendir() returns a directory handle (dh).

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