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
MrMoo
Sep 14, 2000

duz posted:

Commonly request scripts These have been checked for security
r1ch has an image uploading script

Does anyone bother altering HTTP status codes for errors? Taking R1CH's upload script for example:

php:
<?
header('HTTP/1.1 503 Service Unavailable');
die ("...");
...
header('HTTP/1.1 400 Bad Request');
$error = "Upload failed, please check the filename and try again.";
...
header('HTTP/1.1 413 Request Entity Too Large');
$error = "File size exceeded, maximum allowed file is {$config['max_size']}...
...
header('HTTP/1.1 500 Internal Server Error');
$error = "Internal error, unable to open uploaded file.";
?>
The 415 error is supposed to be in regard to client not server support, otherwise this one too:
php:
<?
header('HTTP/1.1 415 Unsupported Media Type');
$error = "Unknown file format, only JPEG, PNG and GIF files are allowed.";
?>
If the script didn't try to workaround previous uploaded files with the same name:
php:
<?
header('HTTP/1.1 409 Conflict');
$error = 'File already uploaded';
?>
If you can ban or delete entries you could use this:
php:
<?
header('HTTP/1.1 410 Gone');
$error = 'File has been removed';
?>
Or using the additional 200 codes when things go well:
php:
<?
header('HTTP/1.1 201 Created');
?>
<p>Your file was uploaded successfully.</p>
...
?>
For 202 it could be used with say a Waffle Images URL load, i.e. submit a form with an URL to load an image from, the server returns "202 Accepted" with an hanging-Ajax (Comet) display for progress reporting.

Is this only really useful if a program is going to interact with a webservice so they don't have to scrape?

In the meantime, enjoy a set of icons representing HTTP status codes on Flickr:

http://www.flickr.com/photos/apelad/sets/72157594388426362/

Adbot
ADBOT LOVES YOU

MrMoo
Sep 14, 2000

Lankiveil posted:

Yes, I use some obscure status codes (402 and 405, for instance) for things like malformed requests or unsupported requests.

I just tried a 502 and PHP trimmed off the entity content, so if it's the same with many of the other codes it's pretty much impossible to use them for direct browser facing resources.

(edit) also 504 munged, and to quite a problem 413 is munged too. 500 and other 4xx codes seem to go through.

MrMoo fucked around with this message at 08:07 on Nov 28, 2008

MrMoo
Sep 14, 2000

bleh posted:

I get "u?op ?p?sdn s? s???" am i missing some encoding I have to specify or something?
You're using MSIE by any chance? Make sure you mark the document as UTF-8 encoding, MSIE defaults to whatever ISO locale your desktop is.

MrMoo
Sep 14, 2000

cannibustacap posted:

Cool, is there a difference between two periods and three?
Three periods is Microsoft-only for the parent of the parent directory.

(edit) introduced in Windows '95 apparently.

MrMoo fucked around with this message at 02:57 on Dec 13, 2008

MrMoo
Sep 14, 2000

Munky_Magic posted:

For example, if I wanted to store the string <div id="foo">, php automatically converts the string to <div id=\"foo\"> ie. with the escape characters.

Where does it do this, with the deprecated magic quotes?

MrMoo
Sep 14, 2000

fletcher posted:

How might I write the user id # relevant to my webapp to the apache log?

There's a few mod_sql variants that should be able to handle this for you.

MrMoo
Sep 14, 2000

Sir Davey posted:

I'm actually wondering if I'm not better off doing the complicated filtering with PHP.

It's the database job to process the data, PHP to stick it in a template. Also consider stored procedures for extra processing in the database.

MrMoo
Sep 14, 2000

chocojosh posted:

I think though that using a proper templating system would be the best way to go.
PHP is a proper template system it all depends how you feed the data to the template, so for your example you could do this:
php:
<?
/* controller */
$data = array( array( value => "1", label => getString("none") ),
               array( value => "2", label => getString("small") ),
               array( value => "3", label => getString("small") )
              );
foreach ($data as &$datum) {
  $datum["selected"] = $datum["value"] == $var;
}
...
?>
php:
<?
/* view */
?>
<div>
<?
foreach ($data as &$datum) {
?>
<option value="<?=$datum["value"]?>"<?=$datum["selected"]?" selected":""?>>
  <?=$datum["label"]?>
</option>
<?
}
?>
</div>

MrMoo
Sep 14, 2000

waffle iron posted:

From what I remember, the OO stuff in PHP4 is a little slower than straight up procedural programming, but then again objects in PHP4 suck. In early versions of PHP5 there was more overhead for objects, but they were 1st class OO. At this point PHP5 has matured quite a bit and hardware is fast enough so it really should make a difference on performance.

If you are using PHP for performance on execution rather than development something is already rather wrong.

MrMoo
Sep 14, 2000

PainBreak posted:

php:
<?php
$entry 'fa98a0';
$lines file('list.txt'FILE_IGNORE_NEW_LINES);
foreach ($lines as $line)
{
if ($line==$entry)
{
echo "It's A Dupe!";
}
}
?>


Fixed it for you.

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

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:

MrMoo
Sep 14, 2000

Halo_4am posted:

Can anybody take a shot at explaining how to detect if the image uploaded is png/gif/tiff and act accordingly?
code:
list($src_w, $src_h, $src_type) = getimagesize ($src);

switch ($src_type) {
case IMAGETYPE_JPEG:	$original = imagecreatefromjpeg ($src); break;
...
default: throw new Exception ("Image type $type is unsupported.");
}
Using ImageMagick is easier:

code:
$im = new Imagick();
try {
  $im->readImage($file_name);
} catch (ImagickException $e) {
  throw new Exception(_('Invalid or corrupted image file, please try uploading another image.'));
}

MrMoo fucked around with this message at 04:23 on Mar 2, 2009

MrMoo
Sep 14, 2000

fletcher posted:

Is there a clean way to build a string of html (in the template) and either assign it as a javascript variable or just print it based on some condition?

That's generally what AJAX is for.

MrMoo
Sep 14, 2000

fletcher posted:

Why make the extra request if I'm rendering other things just like it already there in the template though?

Nobody cares, whichever is the easiest to implement and look after is the correct answer.

MrMoo
Sep 14, 2000

Golbez posted:

why PDO?

Less chunky than Pear::DB_DataObject and reasonable parameter and exception handling? PDO::FETCH_CLASS is very convenient too.

MrMoo
Sep 14, 2000

standard posted:

Does anyone know of a nice image serving type script?

For public or private use? I wrote one after a request sometime before, I recently updated it for some speed tweaking after Google published their performance article:

http://junko.hk/junko-php-latest.tbz2

Supports i18n, Gears, loading from URL, thumbnails, etc.

MrMoo
Sep 14, 2000

Probably needs it's own thread, but anyone found or created anything useful for OpenID?

I'm looking for a PHP equivalent of this site as setup by Google to demonstrate fancy pants OpenID login:


It's a JSP and Java Servlet combination and the magic is probably happening below. It takes the domain of an entered email address and magically conjures up the OpenID Identity URL.

code:
    // if the user typed am email address, ignore the user part
    openid = openid.replaceFirst(".*@", "");

    // we assume that the user typed an identifier for an IdP, not for a user
    IdpIdentifier openId = new IdpIdentifier(openid);

    AuthRequestHelper helper = consumerHelper.getAuthRequestHelper(
        openId, returnToUrl.toString());
http://code.google.com/p/step2/sour...ginServlet.java

I'm looking at the PHP-OpenID library that's bundled in Debian but it's rather obtuse on quick inspection, the demo is certainly not so useful,

http://openidenabled.com/php-openid/trunk/examples/consumer/

You need to enter "https://www.google.com/accounts/o8/" for Google as the Identity URL, but this wouldn't work for Yahoo!, Facebook or whatever other popular OpenID systems are out there.

MrMoo
Sep 14, 2000

fletcher posted:

This may be a dumb question, but what is to stop me from putting a fake login on some site that claims to be an "OpenID login" and just stealing a bunch of OpenID credentials?

The OpenID server provides a unique ID bound to that provider so cannot imitate another provider.

I found some more PHP code that has a basic hard coded array of domains to Identity URLs, but there should be some method for automatic "federated" discovery.

http://perplexed.co.uk/867_openid.htm

code:
Array
(
    [@gmail.com] => https://www.google.com/accounts/o8/id
    [@googlemail.com] => https://www.google.com/accounts/o8/id
    [@yahoo.co.uk] => http://open.login.yahooapis.com/openid20/www.yahoo.com/xrds
    [@yahoo.com] => http://open.login.yahooapis.com/openid20/www.yahoo.com/xrds
    [@aol.com] => http://openid.aol.com/{username}
    [@aol.co.uk] => http://openid.aol.com/{username}
)

MrMoo
Sep 14, 2000

Some progress on this, I have a discovery mechanism setup patched to XRDS-Simple. The mechanism is called host-meta, patch:


To SVN of Diso/XRDS-Simple:


Then code for the Idp Discovery can run like this:

code:
<?php

require_once 'XRDS.php';
require_once 'XRDS/Discovery.php';

$domain = 'miru.hk';

$disco = new XRDS_Discovery();
$disco->discovery_methods = array('XRDS_Discovery_Host_Meta');
$xrds = $disco->discover('https://www.google.com/accounts/o8/.well-known/host-meta?hd=' . $domain);

$xrd = $xrds->xrd[0];
$identityUri = $xrd->service[1]->uri[0]->uri;

if (0 == strcmp($xrd->canonicalId, $domain)) {
	echo "identity uri: $identityUri\n\n";
} else {
	echo "discovery failed.\n\n";
}

?>
For non-Google domains the script should pull direct from http://example.com/.well-known/host-meta, with which Yahoo! this returns an XRD which I'm not sure what to do with as it's for user discovery.

code:
<XRD>
<Host>yahoo.com</Host>
<Link>
<Title>WebFinger</Title>
<Rel>http://webfinger.info/rel/service</Rel>
<Rel>describedby</Rel>
<URITemplate>http://webfinger.yahooapis.com/?id={%id}</URITemplate>
</Link>
</XRD>

MrMoo fucked around with this message at 09:42 on Sep 21, 2009

MrMoo
Sep 14, 2000

FeloniousDrunk posted:

Here's a link to a log.

How can you mess up gb2312? iconv has oodles of aliases already setup for each encoding, e.g. utf8, UTF8, UTF-8, etc.

MrMoo
Sep 14, 2000

FeloniousDrunk posted:

Are you suggesting using iconv before mbstring? Because I could do that too; mbstring just seemed more 'mature' at first glance, mostly because I could actually get a list of its supported encodings.

Actually I'd try recode first considering the source material. The other modules are more strict on character set names.

Run recode -l on the command line for supported sets and aliases.

MrMoo
Sep 14, 2000

I can't imagine it's going that difficult to build under MinGW32?

Lighty seems to have a native port via MinGW32 and bundles it's own version of spawn-fcgi, is that any good?

MrMoo
Sep 14, 2000

haywire posted:

Surely if your session is invalid you should most likely kill the script and tell the client to gently caress off, whilst deleting the session? Or just do the latter.

Just re-initialize the session and redirect to the homepage.

MrMoo
Sep 14, 2000

Mr Viper posted:

it takes 2 seconds a mail()

Sounds like you are not queuing mail in the MTA, or the MTA is remote to the script host. You need to configure a local MTA to spool out for later delivery.

MrMoo
Sep 14, 2000

It's a bit messy with proxies, it's generally not a good idea to use the IP if you would like anyone in a big company to access such a site.

You could put a LIMIT on the DELETE FROM SQL.

MrMoo fucked around with this message at 03:59 on Dec 22, 2009

MrMoo
Sep 14, 2000

haywire posted:

LIMIT was intentionally removed - a handy way of getting rid of duped sessions if they exist for some reason - sids should be unique.

Useful when deleting all existing sessions in create_session() but not so when deleting a single session in destroy_session(), although you might want to allow multiple sessions anyway.

REMOTE_ADDR is the address of the last proxy a client is using, if they have multiple proxies the session might bounce between different IP addresses. HTTP_X_FORWARDED_FOR might be set to the clients actual address, or even 127.0.0.1 for various reasons (security through obscurity is popular). With a Squid & HAVP sandwich it can end up a list of addresses, mine shows: "10.6.15.69, 127.0.0.1".

MrMoo
Sep 14, 2000

The1ManMoshPit posted:

Is there a way to return a large file from PHP that is more efficient on memory? Ideally, I'd like to have the file resident in memory no more than once, but I'm not sure if that's possible.

Edit: I tried using readfile_chunked as described in the comments here http://cn2.php.net/manual/en/function.readfile.php#48683 and it actually made the memory usage much, much worse.

Read chunking is the compatibility method of using fpassthru():

http://hk2.php.net/manual/en/function.fpassthru.php

MrMoo
Sep 14, 2000

armed2010 posted:

How would I code a dynamic list of this sort?

Which bit is the problem? I hope you have saved the items checked out with some unique id somewhere. Then to check-in you pull that list of items, iterate over them generating the HTML as necessary for your check boxes, etc.

php:
<?
foreach ($items as &$item)
{
?>
  <input type="checkbox" name="<?=$item->name;?>">
<?
}
?>

MrMoo
Sep 14, 2000

Begby left out one more option, using heredoc:

php:
<?
foreach ($items as &$item)
{
  echo<<<MOO
  <input type="checkbox" name="{$item->name}">
MOO;

}
?>

MrMoo
Sep 14, 2000

epswing posted:

I think php itself is a reasonably good templating engine.

It can also be a reasonable framework but people love to aimlessly re-invent poo poo that some how ends up inferior to the original. Meh.

MrMoo
Sep 14, 2000

cLin posted:

How do people deal with passing options thru the form considering each product might have a different option?

The first goal should be to have everything with a unique ID and see if your view can manage the collation of related IDs. If that is not sufficient you might want to consider something simply like a parent-ID reference, each option has a unique ID and you create a tree.

php:
<?
$cart->handle_product(array(
     'product-id'  => $_POST['prod_id'],
     'quantity'    => $_POST['quantity'],
     'price'       => $_POST['price'],
     'options'     => array(
          array(
               'option-id'   => $_POST['opt0_id'],
               ...
          ),
          array(
               'option-id'   => $_POST['opt1_id'],
               ...
          ))
...
));
?>
Try to avoid re-implementing a key-value database ontop of SQL like many shopping cart systems like to do.

MrMoo
Sep 14, 2000

crazypandaman posted:

To me this feels like a very inefficient way of serving the files.

Check out x-send-file, on new versions of Apache or Lighttpd.

http://john.guen.in/past/2007/4/17/send_files_faster_with_xsendfile/

MrMoo
Sep 14, 2000

Hammerite posted:

If so, well, I disagree and I have to confess to being a bit baffled at you thinking that.

You're just being a pedant on syntax, PDO allows you four different ways,

http://php.net/manual/en/pdostatement.execute.php

MrMoo
Sep 14, 2000

drcru posted:

Something "lighter."

But what are you looking for that is more than just PHP itself?

MrMoo
Sep 14, 2000

Pookster posted:

Using PHP in the templates is still quite verbose but it's only meant as a quick and simple solution.
The less verbose version I use, firstly inside a model,
php:
<?
$_ = array('some_var' => 'Hello World!');
include '../templates/my-template.php';
?>
and the template,
code:
<p><?=$_['some_var']?></p>
(edit) to use square brackets.

MrMoo fucked around with this message at 10:40 on Apr 27, 2010

MrMoo
Sep 14, 2000

Probably, mixing up gettext :eng99:

MrMoo
Sep 14, 2000

quote:

// quick & dirty injection protection
Quickest as easiest is to do a strncmp() on realpath().
php:
<?
$root_dir = '/home/clap/images/';
$target_dir = realpath("{$root_dir}/{$_POST['dir']}");
if (0 != strncmp ($target_dir, $root_dir, strlen($root_dir)))
{
...
}
?>
You should be using POST for any actions that modify anything.

MrMoo
Sep 14, 2000

drcru posted:

Has anyone come up with/found any way to implement a low footprint chat system with PHP? I'm running Apache 2 so probably no Comet.

Very low footprint, Facebook Live Stream:

http://developers.facebook.com/docs/reference/plugins/live-stream

Adbot
ADBOT LOVES YOU

MrMoo
Sep 14, 2000

Try the APE real time chat,

http://www.ape-project.org/demos/1/ape-real-time-chat.html

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