Wednesday, February 9, 2011

How to extract a file extension in PHP ?

This is a question you can read everywhere on the web with various answers :

$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);
$exts = split("[/\\.]", $filename);
$n = count($exts)-1;
$ext = $exts[$n];

etc.

However, there is always "the best way" and it should be on stackoverflow.

  • pathinfo - http://uk.php.net/manual/en/function.pathinfo.php

    An example...

    $path_info = pathinfo('/foo/bar/baz.bill');
    
    echo $path_info['extension']; // "bill"
    
    vaske : This one is "the best way"
  • People from other scripting languages always think theirs is better because they have a built in function to do that and not PHP (I am looking at pythonistas right now :-)).

    In fact, it does exist, but few people know it. Meet pathinfo :

    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    

    This is fast, efficient, reliable and built in. Pathinfo can give you others info, such as canonical path, regarding to the constant you pass to it.

    Enjoy

    J-P : Why didn't you just put the answer in the question!?
    e-satis : Because it's written is the overflow FAQ do it this way.
    Mark Biek : I wish I could vote this up twice. I can't tell you how much code I've been able to replace using pathinfo
    e-satis : So do I. That's why I put it here !
    From e-satis
  • E-satis response is the correct way to determine the file extension.

    Alternatively, instead of relying on a files extension, you could use the fileinfo (http://us2.php.net/fileinfo) to determine the files MIME type.

    Here's a simplified example of processing an image uploaded by a user:

    // Code assumes necessary extensions are installed and a successful file upload has already occurred
    
    // Create a FileInfo object
    $finfo = new FileInfo(null, '/path/to/magic/file');
    
    // Determine the MIME type of the uploaded file
    switch ($finfo->file($_FILES['image']['tmp_name'], FILEINFO_MIME) {
        case 'image/jpg':
            $im = imagecreatefromjpeg($_FILES['image']['tmp_name']);
        break;
    
        case 'image/png':
            $im = imagecreatefrompng($_FILES['image']['tmp_name']);
        break;
    
        case 'image/gif':
            $im = imagecreatefromgif($_FILES['image']['tmp_name']);
        break;
    }
    
    From Toxygene

How do I resize my panels when resizing the main form in a winforms application?

If the user of my winforms application resizes the main form, I want the 2 panels to stretch out also, along with the child controls.

How can I achieve this?

  • Play around with the Dock and Anchor properties of your panels.

  • You can use the TableLayoutPanel and set column width at x% each this way you will have the screen split in 2. The TableLayoutPanel must be Dock to fill all the form or Anchor.

    The TableLayoutPanel can contain other panel. OR you can use simply your panel and use Anchor (click the panel and go in the Properties panel of VS).

    From Daok
  • If the user of my winforms application resizes the main form, I want the 2 panels to stretch out also, along with the child controls.

    You're the ideal use case for TableLayoutPanel (MSDN). If you were only scaling the panels, Dock and Anchor would be appropriate. But since you want your controls to scale well, you're pretty much in an AutoLayout world, and likely the TableLayoutPanel. (I'm a huge fan of this, by the way, although overuse can have a negative performance impact on laying out your controls.)

    Some helpful links on using it to configure your layout to scale:

    MusiGenesis : Argh. I write software for Windows Mobile devices, and once again I just had the experience of learning about a cool .NET feature that isn't in the Compact Framework.
    John Rudy : For future visitors of this answer: I just noticed a link to my blog in this answer, and have now removed it, as I shut the blog down many months ago. I apologize for the inconvenience.
    From John Rudy
  • See following:
    http://urenjoy.blogspot.com/2008/11/make-resolution-independent-windows-app.html

    From Brij

Why is getenv('REMOTE_ADDR') giving me a blank IP address?

This PHP code...

207    if (getenv(HTTP_X_FORWARDED_FOR)) {
208        $ip   = getenv('HTTP_X_FORWARD_FOR');
209        $host = gethostbyaddr($ip);
210    } else {
211        $ip   = getenv('REMOTE_ADDR');
212        $host = gethostbyaddr($ip);
213    }

Throws this warning...

Warning: gethostbyaddr() [function.gethostbyaddr]: Address is not in a.b.c.d form in C:\inetpub...\filename.php on line 212

It seems that $ip is blank.

  • Why don't you use

    $_SERVER['REMOTE_ADDR']
    

    and

    $_SERVER['HTTP_X_FORWARDED_FOR']
    
  • on php.net it says the follwing:

    The function 'getenv' does not work if your Server API is ASAPI (IIS). So, try to don't use getenv('REMOTE_ADDR'), but $_SERVER["REMOTE_ADDR"].

    Did you maybe try to do it with $_SERVER?

    From fly.floh
  • First of all, getenv() takes a string as parameter. On line 207, you should use:

    getenv('HTTP_X_FORWARDED_FOR')
    

    ...instead of:

    getenv(HTTP_X_FORWARDED_FOR)
    

    Secondly, accessing these variables through $_SERVER is a more reliable solution, as getenv() tends to display different behaviour on different platforms.

    Also, these variables will probably not work if you are running this script through CLI.

    Try a var_dump($ip); and see what the variable contains.

  • A better solution has already been given. But still:

    getenv('HTTP_X_FORWARD_FOR');
    

    should be

    getenv('HTTP_X_FORWARDED_FOR');
    

    Yeah... sometimes computers want to have strings they understand ;-)

    From easyDaMan

what is the best xhtml-css editor with emmbeded browser (under GPL) in your opinion?

what is the best xhtml-css editor with emmbeded browser (under GPL) in your opinion? note: must be work under linux os.

  • Quanta Plus.

  • Eclipse (with the web tools project) should be able to handle this, although it may be more heavy weight than you need. As far as I know the browser included is based on Mozilla.

    Peter Boughton : Eclipse is EPL, which is not GPL-compatible. Although it might be the questioner just wants any Free Software / Open Source license, rather than specifically GPL.
    From slashnick
  • I was pleasantly surprised by Netbeans and after trying a bunch of others. Web browser and web server baked in just the way you like :)

    Mark Tomlin : I agree with everything you just said. However, Netbeans also feels some what heavy. I don't know if it's just me, but it does not feel as snappy as notepad. And, at the end of the day, ever text editor should be as fast as notepad or it's just not doing it's job well enough.
  • Aptana ... well, some people really like it, other people really dislike it.

    It's certainly capable of doing what you want though, so only way to be sure which category you'll fit into is to give it a try.

  • Aptana Studio is the best in my opinion, it's based on Eclipse and subsequently Java, so it will run on pretty much anything and has "Design" views supporting Firefox, Opera and Safari on OS X and Windows, I assume it does other browsers as well if they are installed.

    It does CSS, XHTML, JavaScript + AJAX, PHP etc. It's very comprehensive and has some very useful predictive functions. It may be a little bulky if you like a minimalist development interface. In saying that though, I like a minimalist development interface and I love Aptana Studio!

    From Matt
  • Free Komodo edit is best for this http://www.activestate.com/komodo_edit/features/

    It shows preview using Firefox engine.

    alt text

Complex profiles in maven

I've been looking at profiles in maven for selecting different sets of dependencies. This is fine when you want to build say a debug build differently from a release build. My problem is that I want to do a fair bit more than this. For my application (Mobile Java app where J2ME is just one target among many) there may be a large number of possible combinations of variations on a build.

Using some made-up command line syntax to illustrate what I'd like to see, I'd imagine typing in something like

mvn -Pmidp,debug,local-resources

What Maven does in this case is to build three different builds. What I want to do is use those three (Or more, or less) switches to affect just one build. So I'd get a MIDP-targetting debug build with 'local resources' (Whatever that might mean to me - I'm sure you can imagine better examples).

The only way I can think of doing this would be to have lots and lots of profiles which becomes quite problematic. In my example, I'd have

-Pmidp-debug-localresources
-Pmidp-release-localresources
-Pmidp-debug-remoteresources
-Pmidp-release-remoteresources
...

Each with its own frustratingly similar set of dependencies and build tag.

I'm not sure I've explained my problem well enough, but I can re-write the question to clarify it if comments are left.

UPDATE:

The question isn't actually valid since I'd made a false assumption about the way maven works.

-Pmidp,debug,local-resources

does not do 3 builds. It in fact enables those 3 profiles on one build, which was ironically what I was looking for in the first place.

  • The Maven way is to create a lot of artifacts with less complexity. I'd say your best bet is to abstract the common parts of each build into a separate artifact, then create a project for each build that defines the build specific parts. This will leave you with a lot of projects, but each will be much simpler.

    izb : I have that, but it's the selection of a specific part within a superpart that has me stumped, particularly when I want to choose between a large set of possible small parts, each doing some small thing, and each possibly a variant of another.

Cookies and Objects

I'm having trouble figuring out how to access a cookie from a compiled object. I'm trying to make a compiled (DLL) object that will check the users cookie and then compare that to a database to confirm they have the correct access.

I can pass in the cookie info fine and the component will work, but I'm trying to have the component check the users cookie as well. I'm not even sure what object to use. I've been searching all weekend and I've seen references to httprequest, httpcookie, cookie, and cookiecollection.

I can look up cookie values on the page itself using Request.Cookies("inet")("user_id") but this doesn't work in the component.

  • Objects (App_Code/ compiled dlls) can only access Request via the static HttpContext.Current object

    HttpCookie cookie = HttpContext.Current.Request.Cookies["CookieName"];
    

    (If it's not called from a web app, HttpContext.Current is null, so you may want to check for that when running in unit testing) (If this isn't App_Code, you'll need to reference System.Web)

    From martin
  • If the component is a separate DLL from your web app you'd need to pass in a reference to the Request object.

    That said why not just read/check the cookie value in your ASP.NET code before calling into your DLL. It's not such a good idea to have your business logic coupled to your web tier like this.

    From Kev

How do I use the new SVN merge-tracking?

In my existing (Pre-SVN 1.5) merge strategy, we create a copy of the Trunk (called BasePoint) at the moment of branch-creation for referencing later during the merge.

When we need to merge a branch back into the trunk, we perform 2 operations.

  1. Merge from BasePoint to LatestTrunk (Trunk has likely moved on since the original branch) into Working copy of Branch and then commit.

    At this point we typically check that the merge into the branch has not damaged anything

  2. Merge from LatestTrunk to LatestBranch back into Working copy of trunk and then commit.

Documentation suggests that I use the new reintegrate merge on the Trunk and Merge from the Branch.

Do I need to merge from the trunk into the dev branch first or is this included in the new reintegrate option?

To put it another way, does the new merge --reintegrate functionality represent 'each of my previous merges' or 'the whole operation' ?

(FWIW I am using TortoiseSVN 1.5.1)

  • I believe reintegrate does not actually do the two operations, but instead is used to merge back into trunk from an updated branch. You will still need to do the first set of merge/commit operations to update the branch first.

    Here is a link to the Subversion Book. It is possible to get this book in dead tree format.

    From the link, it sounds like using --reintegrate handles some weird cases, probably like merge usually does compared to just using straight patches (read the section "Why Not Use Patches Instead?").

  • The short answer is, You still have to do both steps.

    The SVN book explains the process for merging as:

    1. svn merge http://trunk/path while in a branch working copy
    2. svn merge --reintegrate http://branch/path while in a trunk working copy

    Notice the lack of revision numbers. This probably doesn't feel like a huge win. The new coolness is the ability to re-run the merge as you are coding in your branch, allowing you to keep the branch up to date with changes in trunk (without recording revision numbers by hand!). SVN keeps track of what needs to be merged in from trunk and what changes are unique to the branch. When you are done with the branch, --reintegrate uses that data to automatically merge only the branch changes back to trunk.

    From Nate Green
  • A good blog post about merging problems in svn (and what reintegrate does) is here.

    From teki