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

SmirkingJack posted:

Here's a time saving tip that can obviously be applied anywhere, but I first started using it with PHP's website. If you use Firefox then navigate over to php.net, right click on the search box and add a keyword of 'php' to the search. Now whenever you need to look up a function hit Ctrl+L (or otherwise get the focus on the address bar), type 'php <<function name>>' and there you are. It also works great if you don't remember the exact name but can come close, which is how I found imagecreatefromjpeg() from createfromjpeg().

Another way to do it in Firefox is to go to Bookmarks > Organize bookmarks. Click 'New Bookmark', set the name you want, and paste the URL of a search query in there. replace the query words by '%s'. So 'http://ca3.php.net/manual-lookup.php?pattern=myfunction' --> 'http://ca3.php.net/manual-lookup.php?pattern=%s'. Then add the keyword you want to type in. The advantage is minimal, but in search engines like google you can specify the language (hl=en,fr, etc) or some other parameters that way.

Opera works in a similar manner. Go to Tools > Preferences (ctrl+F12), press the 'search' tab. You can edit those that are there or enter new ones the same way firefox does (%s).

Sorry for the derail.

Adbot
ADBOT LOVES YOU

MononcQc
May 29, 2007

fletcher posted:

Thanks for all the replies guys, very helpful and appreciated.

Another question, is it a bad idea to use an existing php function name as the name of a method in a class? Like if I want to use $obj->delete(), wasn't sure if that's frowned upon.
Well, if it's anything that can be confusing to someone else looking over your code, I'd say it's not a good idea. In this case, it's 99% sure to spark some confusion, so I'd go against it just because of that.

MononcQc
May 29, 2007

DaTroof posted:

I disagree. One of the benefits of using classes is the ability to use simple, descriptive member names that won't collide with the same name in other contexts. If $obj->delete() is an appropriate name for what the function does, I'd use it. The fact that it's obviously an object member instead of a global function should eliminate any confusion.

I just hate it when the syntax highlight goes crazy on it and highlights it as a built-in function, which then confuses me. I can tend to be distracted, so I make what's necessary to reduce my mistakes and make it easier to read for me :shobon:

MononcQc
May 29, 2007

duz posted:

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

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

echo <<<EOF

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

EOF;

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

MononcQc
May 29, 2007

Not really sure this belongs here or the python thread, but whatever.

I'm learning python on the sides and I'm noticing some stuff.

Basically, python will use a bunch of elifs instead of switches/cases (as far as the tutorial told me, and I hope it's right). This means there's no nead for 'break;', but it acts the same.

However, I noticed that PHP doesn't require the break; to be syntactically right.

So I could do:

php:
<?
$x = 1;

switch($x){
case 1: 
    echo "woo";
case 2: 
    echo "haa";
    break;
}
//this echoes 'woohaa'
?>
PHP's got a bad rep as a language for many different aspects. Is it PHP that's loving up, or python that's missing an aspect of switches with ifs and elifs?

(I also found http://simonwillison.net/2004/May/7/switch/, but it doesn't say much about the possibility to move from statement to statement like I did in PHP)

edit: fixed linking

MononcQc fucked around with this message at 16:35 on Apr 21, 2008

MononcQc
May 29, 2007

noonches posted:

I'm pretty sure PHP is working "correctly", as it were, and python is wrong. You can exclude the break in just about any language and it acts the same as your PHP example, as far as I remember.

Alright, good to know, and also surprising it's not everything > PHP on this issue, like it seems to be about code-related things according to posts I read here.

MononcQc
May 29, 2007

drcru posted:

Gotcha.

Now for another question I haven't seen in awhile...

How should I store passwords in MySQL? The only way I know of is to MD5 it with a salt. How would a security conscious goon do it?

Use SHA-1. Otherwise, salting it is pretty much the right thing to do.

MononcQc
May 29, 2007

Bonus posted:

My PHP is really rusty and I ran into this problem when building a site for something I'm making. I have an associative array with strings as the keys and they point to arrays:
php:
<?
$contents = array
    ( 'introduction' => array( ...
    , 'starting-out' => array( ...
    , 'types-and-typeclasses' => array( ...
    , 'syntax-in-functions' => array( ...
    , 'higher-order-functions' => array ( ...
    , ...
    )
?>
What I want is a function that will take a key and return the key before it and after it. So if I call it like prevnext("types-and-typeclasses"), I want to get two strings back, namely ["starting-out", "syntax-in-functions"]. I implemented this function already but it looks very inelegant. Basically I use a while loop and the next function to traverse the array and then when I find the element I want, I gently caress around with calling prev once, storing the string, then next twice, storing the string, going back once with prev and then returning those two strings. It seems awfully hackish.
Not sure if this is what you're looking for, quick and dirty:

php:
<?
#based on the array you described
function getPrevNext($dict, $current_key) {
    $keys = array_keys($dict);
    $num_key = array_search($current_key, $keys);
    return array('prev'=>$keys[$num_key-1], 'next'=>$keys[$num_key+1]);
}

print_r(getPrevNext($contents,'types-and-typeclasses'));

?>
outputs:
code:
Array
(
    [prev] => starting-out
    [next] => syntax-in-functions
)
If there's no previous or next entry, it should set the corresponding return value in the array to NULL
edit: fixed poo poo. didn't test properly and if there was no key corresponding, would return the firt one as next.

This one will throw an exception if the key doesn't exist:
php:
<?
function getPrevNext($dict, $current_key) {
    try {
        $keys = array_keys($dict);
        $num_key = array_search($current_key, $keys);
        if($num_key===False)
          throw new Exception ("key '{$current_key}' not in array");
        return array('prev'=>$keys[$num_key-1], 'next'=>$keys[$num_key+1]);
    }
    catch(Exception $e) {
        echo $e;
    }
}
?>

MononcQc fucked around with this message at 16:07 on Aug 30, 2008

MononcQc
May 29, 2007

windwaker posted:

Ah, good idea, I hadn't thought about that (though I don't know if said red X will appear if the "image" is display:none'd).
Opera isn't supposed to load images in display:none; so if you want good stat accuracy, I guess you have to do something else.

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

MononcQc
May 29, 2007

Zorilla posted:

Also, there's no reason to die() the script after setting the HTTP header. PHP knows to stop it right there on its own.

No it doesn't. It will keep processing and just send the header when it's done.
Try this:
php:
<?php
header('location: http://google.com');
fopen('file.txt','w'); // if you need file.txt, it will be overwritten
?>

If the permissions are set right in your php folder, you'll now have a 'file.txt' in your directory.

To make it better:
php:
<?php
header('location: http://google.com');
exit;
fopen('file.txt','w'); // The script died before this.
?>

Now there should be no file added.

MononcQc
May 29, 2007

hexadecimal posted:

Let's say I have a list of variables I would like to pass to my php script, such as http://someurl?a=2&b=3. What if I want to pass a string "a=2&b=3" as a single variable? like http://someurl?args="a=2&b=3". How can I do this? I tried quotes already and they don't work. Is there some particular escape character I can use or something?
use %26 for &: http://someurl?a=2%26b=3
see http://ca3.php.net/manual/en/function.urlencode.php

MononcQc
May 29, 2007

Hammerite posted:

What I meant is, is it any faster at all at reading and interpreting the file? But I take it from your answer that no, it is not any faster. Thanks!

The biggest speed upgrades you can have when including a file many times is to not include it many times. Usually, you'll use statements like require_once("file.php");, which are pretty slow compared to imports in many other languages. A way to bypass this is to use a defined constant once a file is loaded and check it before including it again. This makes ugly code though, and in most cases is not worth it at all. I do not recommend it.

I may not have everyone's approval on this, but optimizing the server-side code is rarely what you need to do to speedup your website.
Overall, you'll get a bigger speedup for the client making sure everything is gzipped and using a cache than optimizing trivial things like file imports. As a general rule, downloading images, css and/or javascript files is longer than the processing needed server-side.

Otherwise, the only big bottlenecks which really have a noticeable effect are operating on large amounts of data (image rendering, nested loop on large datasets, bad written templating engines without caching ever, etc) and SQL queries (look at indexes and whatnot, also use caches if possible).

MononcQc
May 29, 2007

Ferg posted:

What about passing by reference when necessary? I'm currently working on a project that was shooting back enough data to crash FirePHP, so I was thinking if I passed things around by reference (since most of it is references to constant data anyways) it might help improve performance.
If you use large arrays or objects, passing by reference will certainly have its advantages if you can make sure you won't modify data when you shouldn't. It's going to give some savings on processing time and memory usage for sure. To some extent, this is more about design than optimization.

What kind of data do you have? why does it need to be moved around? It may be that the design of the solution is not right, rather than the moving data necessary.

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

MononcQc
May 29, 2007

cannibustacap posted:

By the way, what do you guys think of the $_SESSION variable? Does that work when a user has cookies disabled? Are there certain instances when you do not want to use $_SESSION?

On PHP 5.2.3 (I believe)

$_SESSION still uses cookies unless you explicitely have it put the SID in the url. What PHP does is kind of abstract away the need to manage the SID, Time to live and where to put the data (and more) and instead stores it all for you in static files. That static file is associated with the session ID which has been stored in the cookie or the url.

They're nice if you don't know how cookies and session management work, but if you have the time to do it, you'd be better off learning how to do it by hand and managing it all in a database. You gain more control on what you do and can use the data outside of PHP if it's what you want (ie.: compile stats, distribute sessions over many servers, etc).

MononcQc
May 29, 2007

milieu posted:

Sweet! That works perfectly, thanks! I have no idea what the line you commented is for, I copied it from somewhere else. It works though so whatever!

The original dev most likely tried to see if the text was longer than en empty string (0 character).

This is not a really nice way to do it. There are many more ways to test this nicely:

php:
<?
if ($node->field_images[$i]['view'] !== '')  // cleaner and stricter
if (!empty($node->field_images[$i]['view'])) // shows what you mean better than > ''
if ($node->field_images[$i]['view'])         // overall cleanest IMO
?>
The last one is the cleanest one. That's because PHP will evaluate an empty string,0,false, an empty array and something that is NULL to FALSE and anything else to TRUE. This means if there's content in your entry, it will show it.

I suggest you go to php.net and read the documentation there. It's concise, won't show too much to stop you from 'getting things done', and while PHP's certainly not the best you could do to learn, it'll at least be better than copy/pasting stuff at random hoping it works.

EDIT: also note that 'print' is rather rarely used. read http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40 for the difference with 'echo'

MononcQc fucked around with this message at 20:16 on Apr 21, 2009

Adbot
ADBOT LOVES YOU

MononcQc
May 29, 2007

Begby posted:

This is interesting

http://bugs.php.net/bug.php?id=48139

How much of a moron do you have to be not to be able to use PHP with MySQL on windows?
Install any WAMP stack and you're good to go. The guy is on windows and there are plenty of stacks available; I can't even comprehend how he can't get it to load dlls when it should be done without touching the config.

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