Rectangle 27 166

Read the docs about built-in PHP function readfile

$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url); // do the double-download-dance (dirty but worky)

Also make sure to add proper content type based on your file application/zip, application/pdf etc. - but only if you do not want to trigger the save-as dialog.

I mean if its other than .exe file than only .Else this should work fine.

How to force file download with PHP - Stack Overflow

php file download
Rectangle 27 167

Read the docs about built-in PHP function readfile

$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url); // do the double-download-dance (dirty but worky)

Also make sure to add proper content type based on your file application/zip, application/pdf etc. - but only if you do not want to trigger the save-as dialog.

I mean if its other than .exe file than only .Else this should work fine.

How to force file download with PHP - Stack Overflow

php file download
Rectangle 27 389

Update: Rewritten to incorporate suggestions from John Millikin and da5id. This solution is written in PHP, but should be easily adapted to other languages.

Update 2: Incorporating comments from Nick Johnson that the original .htaccess regex can cause problems with files like json-1.3.js. Solution is to only rewrite if there are exactly 10 digits at the end. (Because 10 digits covers all timestamps from 9/9/2001 to 11/20/2286.)

First, we use the following rewrite rule in .htaccess:

RewriteEngine on
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]

Now, we write the following PHP function:

/**
 *  Given a file, i.e. /css/base.css, replaces it with a string containing the
 *  file's mtime, i.e. /css/base.1221534296.css.
 *  
 *  @param $file  The file to be loaded.  Must be an absolute path (i.e.
 *                starting with slash).
 */
function auto_version($file)
{
  if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file))
    return $file;

  $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);
  return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
}

Now, wherever you include your CSS, change it from this:

<link rel="stylesheet" href="/css/base.css" type="text/css" />
<link rel="stylesheet" href="<?php echo auto_version('/css/base.css'); ?>" type="text/css" />

This way, you never have to modify the link tag again, and the user will always see the latest CSS. The browser will be able to cache the CSS file, but when you make any changes to your CSS the browser will see this as a new URL, so it won't use the cached copy.

This can also work with images, favicons, and JavaScript. Basically anything that is not dynamically generated.

Thats basicly what is done on the site I work for.

My own static content server does exactly the same, except I use a parameter for versioning (base.css?v=1221534296) rather than a filename change (base.1221534296.css). I suspect your way may be a little bit more efficient though. Very cool.

I see a problem with this, that it accesses the filesystem many times - exactly - number of links * number of requests/sec... that may or may not be a problem for you.

Is the first file_exists check really necessary? filemtime will return false on failure, so why not just assign the filemtime value to a variable and check if it's false before renaming the file? That would cut down on one unnecessary file operation which would really add up.

javascript - How to force browser to reload cached CSS/JS files? - Sta...

javascript css caching auto-versioning
Rectangle 27 389

Update: Rewritten to incorporate suggestions from John Millikin and da5id. This solution is written in PHP, but should be easily adapted to other languages.

Update 2: Incorporating comments from Nick Johnson that the original .htaccess regex can cause problems with files like json-1.3.js. Solution is to only rewrite if there are exactly 10 digits at the end. (Because 10 digits covers all timestamps from 9/9/2001 to 11/20/2286.)

First, we use the following rewrite rule in .htaccess:

RewriteEngine on
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]

Now, we write the following PHP function:

/**
 *  Given a file, i.e. /css/base.css, replaces it with a string containing the
 *  file's mtime, i.e. /css/base.1221534296.css.
 *  
 *  @param $file  The file to be loaded.  Must be an absolute path (i.e.
 *                starting with slash).
 */
function auto_version($file)
{
  if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file))
    return $file;

  $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);
  return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
}

Now, wherever you include your CSS, change it from this:

<link rel="stylesheet" href="/css/base.css" type="text/css" />
<link rel="stylesheet" href="<?php echo auto_version('/css/base.css'); ?>" type="text/css" />

This way, you never have to modify the link tag again, and the user will always see the latest CSS. The browser will be able to cache the CSS file, but when you make any changes to your CSS the browser will see this as a new URL, so it won't use the cached copy.

This can also work with images, favicons, and JavaScript. Basically anything that is not dynamically generated.

Thats basicly what is done on the site I work for.

My own static content server does exactly the same, except I use a parameter for versioning (base.css?v=1221534296) rather than a filename change (base.1221534296.css). I suspect your way may be a little bit more efficient though. Very cool.

I see a problem with this, that it accesses the filesystem many times - exactly - number of links * number of requests/sec... that may or may not be a problem for you.

Is the first file_exists check really necessary? filemtime will return false on failure, so why not just assign the filemtime value to a variable and check if it's false before renaming the file? That would cut down on one unnecessary file operation which would really add up.

javascript - How to force browser to reload cached CSS/JS files? - Sta...

javascript css caching auto-versioning
Rectangle 27 389

Update: Rewritten to incorporate suggestions from John Millikin and da5id. This solution is written in PHP, but should be easily adapted to other languages.

Update 2: Incorporating comments from Nick Johnson that the original .htaccess regex can cause problems with files like json-1.3.js. Solution is to only rewrite if there are exactly 10 digits at the end. (Because 10 digits covers all timestamps from 9/9/2001 to 11/20/2286.)

First, we use the following rewrite rule in .htaccess:

RewriteEngine on
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]

Now, we write the following PHP function:

/**
 *  Given a file, i.e. /css/base.css, replaces it with a string containing the
 *  file's mtime, i.e. /css/base.1221534296.css.
 *  
 *  @param $file  The file to be loaded.  Must be an absolute path (i.e.
 *                starting with slash).
 */
function auto_version($file)
{
  if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file))
    return $file;

  $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);
  return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
}

Now, wherever you include your CSS, change it from this:

<link rel="stylesheet" href="/css/base.css" type="text/css" />
<link rel="stylesheet" href="<?php echo auto_version('/css/base.css'); ?>" type="text/css" />

This way, you never have to modify the link tag again, and the user will always see the latest CSS. The browser will be able to cache the CSS file, but when you make any changes to your CSS the browser will see this as a new URL, so it won't use the cached copy.

This can also work with images, favicons, and JavaScript. Basically anything that is not dynamically generated.

Thats basicly what is done on the site I work for.

My own static content server does exactly the same, except I use a parameter for versioning (base.css?v=1221534296) rather than a filename change (base.1221534296.css). I suspect your way may be a little bit more efficient though. Very cool.

I see a problem with this, that it accesses the filesystem many times - exactly - number of links * number of requests/sec... that may or may not be a problem for you.

Is the first file_exists check really necessary? filemtime will return false on failure, so why not just assign the filemtime value to a variable and check if it's false before renaming the file? That would cut down on one unnecessary file operation which would really add up.

javascript - How to force browser to reload cached CSS/JS files? - Sta...

javascript css caching auto-versioning
Rectangle 27 387

Update: Rewritten to incorporate suggestions from John Millikin and da5id. This solution is written in PHP, but should be easily adapted to other languages.

Update 2: Incorporating comments from Nick Johnson that the original .htaccess regex can cause problems with files like json-1.3.js. Solution is to only rewrite if there are exactly 10 digits at the end. (Because 10 digits covers all timestamps from 9/9/2001 to 11/20/2286.)

First, we use the following rewrite rule in .htaccess:

RewriteEngine on
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]

Now, we write the following PHP function:

/**
 *  Given a file, i.e. /css/base.css, replaces it with a string containing the
 *  file's mtime, i.e. /css/base.1221534296.css.
 *  
 *  @param $file  The file to be loaded.  Must be an absolute path (i.e.
 *                starting with slash).
 */
function auto_version($file)
{
  if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file))
    return $file;

  $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);
  return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
}

Now, wherever you include your CSS, change it from this:

<link rel="stylesheet" href="/css/base.css" type="text/css" />
<link rel="stylesheet" href="<?php echo auto_version('/css/base.css'); ?>" type="text/css" />

This way, you never have to modify the link tag again, and the user will always see the latest CSS. The browser will be able to cache the CSS file, but when you make any changes to your CSS the browser will see this as a new URL, so it won't use the cached copy.

This can also work with images, favicons, and JavaScript. Basically anything that is not dynamically generated.

Thats basicly what is done on the site I work for.

My own static content server does exactly the same, except I use a parameter for versioning (base.css?v=1221534296) rather than a filename change (base.1221534296.css). I suspect your way may be a little bit more efficient though. Very cool.

I see a problem with this, that it accesses the filesystem many times - exactly - number of links * number of requests/sec... that may or may not be a problem for you.

Is the first file_exists check really necessary? filemtime will return false on failure, so why not just assign the filemtime value to a variable and check if it's false before renaming the file? That would cut down on one unnecessary file operation which would really add up.

javascript - How to force browser to reload cached CSS/JS files? - Sta...

javascript css caching auto-versioning
Rectangle 27 387

Update: Rewritten to incorporate suggestions from John Millikin and da5id. This solution is written in PHP, but should be easily adapted to other languages.

Update 2: Incorporating comments from Nick Johnson that the original .htaccess regex can cause problems with files like json-1.3.js. Solution is to only rewrite if there are exactly 10 digits at the end. (Because 10 digits covers all timestamps from 9/9/2001 to 11/20/2286.)

First, we use the following rewrite rule in .htaccess:

RewriteEngine on
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]

Now, we write the following PHP function:

/**
 *  Given a file, i.e. /css/base.css, replaces it with a string containing the
 *  file's mtime, i.e. /css/base.1221534296.css.
 *  
 *  @param $file  The file to be loaded.  Must be an absolute path (i.e.
 *                starting with slash).
 */
function auto_version($file)
{
  if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file))
    return $file;

  $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);
  return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
}

Now, wherever you include your CSS, change it from this:

<link rel="stylesheet" href="/css/base.css" type="text/css" />
<link rel="stylesheet" href="<?php echo auto_version('/css/base.css'); ?>" type="text/css" />

This way, you never have to modify the link tag again, and the user will always see the latest CSS. The browser will be able to cache the CSS file, but when you make any changes to your CSS the browser will see this as a new URL, so it won't use the cached copy.

This can also work with images, favicons, and JavaScript. Basically anything that is not dynamically generated.

Thats basicly what is done on the site I work for.

My own static content server does exactly the same, except I use a parameter for versioning (base.css?v=1221534296) rather than a filename change (base.1221534296.css). I suspect your way may be a little bit more efficient though. Very cool.

I see a problem with this, that it accesses the filesystem many times - exactly - number of links * number of requests/sec... that may or may not be a problem for you.

Is the first file_exists check really necessary? filemtime will return false on failure, so why not just assign the filemtime value to a variable and check if it's false before renaming the file? That would cut down on one unnecessary file operation which would really add up.

javascript - How to force browser to reload cached CSS/JS files? - Sta...

javascript css caching auto-versioning
Rectangle 27 191

Using this PHP function mysql_escape_string() you can get a good prevention in a fast way.

mysql_escape_string Escapes a string for use in a mysql_query

wHERE 1=1   or  LIMIT 1
SELECT * FROM users WHERE name = '".mysql_escape_string($name_from_html_form)."' LIMIT 1

WHERE 1=1 or LIMIT 1 does you no good if they inject ');DROP TABLE users;-- . It's beyond me why people just don't use parameterized ("prepared") statements for this and be done with it.

mysql_real_escape_string()

mysql_real_escape_string is now deprecated, so its no longer a viable option. It will be removed from PHP in the future. Its best to move onto what the PHP or MySQL folks recommend.

mysql - How can I prevent SQL injection in PHP? - Stack Overflow

php mysql sql security sql-injection
Rectangle 27 175

Using this PHP function mysql_escape_string() you can get a good prevention in a fast way.

mysql_escape_string Escapes a string for use in a mysql_query

wHERE 1=1   or  LIMIT 1
SELECT * FROM users WHERE name = '".mysql_escape_string($name_from_html_form)."' LIMIT 1

mysql - How can I prevent SQL injection in PHP? - Stack Overflow

php mysql sql security sql-injection
Rectangle 27 183

Using this PHP function mysql_escape_string() you can get a good prevention in a fast way.

mysql_escape_string Escapes a string for use in a mysql_query

wHERE 1=1   or  LIMIT 1
SELECT * FROM users WHERE name = '".mysql_escape_string($name_from_html_form)."' LIMIT 1

mysql - How can I prevent SQL injection in PHP? - Stack Overflow

php mysql sql security sql-injection
Rectangle 27 176

Using this PHP function mysql_escape_string() you can get a good prevention in a fast way.

mysql_escape_string Escapes a string for use in a mysql_query

wHERE 1=1   or  LIMIT 1
SELECT * FROM users WHERE name = '".mysql_escape_string($name_from_html_form)."' LIMIT 1

mysql - How can I prevent SQL injection in PHP? - Stack Overflow

php mysql sql security sql-injection
Rectangle 27 175

Using this PHP function mysql_escape_string() you can get a good prevention in a fast way.

mysql_escape_string Escapes a string for use in a mysql_query

wHERE 1=1   or  LIMIT 1
SELECT * FROM users WHERE name = '".mysql_escape_string($name_from_html_form)."' LIMIT 1

mysql - How can I prevent SQL injection in PHP? - Stack Overflow

php mysql sql security sql-injection
Rectangle 27 175

Using this PHP function mysql_escape_string() you can get a good prevention in a fast way.

mysql_escape_string Escapes a string for use in a mysql_query

wHERE 1=1   or  LIMIT 1
SELECT * FROM users WHERE name = '".mysql_escape_string($name_from_html_form)."' LIMIT 1

mysql - How can I prevent SQL injection in PHP? - Stack Overflow

php mysql sql security sql-injection
Rectangle 27 174

Using this PHP function mysql_escape_string() you can get a good prevention in a fast way.

Using this PHP function mysql_escape_string() you can get a good prevention in a fast way.

SELECT * FROM users WHERE name = '".mysql_escape_string($name_from_html_form)."'

mysql_escape_string — Escapes a string for use in a mysql_query

mysql_escape_string Escapes a string for use in a mysql_query

wHERE 1=1   or  LIMIT 1
wHERE 1=1   or  LIMIT 1
SELECT * FROM users WHERE name = '".mysql_escape_string($name_from_html_form)."' LIMIT 1
SELECT * FROM users WHERE name = '".mysql_escape_string($name_from_html_form)."' LIMIT 1

WHERE 1=1 or LIMIT 1 does you no good if they inject ');DROP TABLE users;-- . It's beyond me why people just don't use parameterized ("prepared") statements for this and be done with it.

mysql_real_escape_string()

mysql_real_escape_string is now deprecated, so its no longer a viable option. It will be removed from PHP in the future. Its best to move onto what the PHP or MySQL folks recommend.

mysql - How can I prevent SQL injection in PHP? - Stack Overflow

php mysql sql security sql-injection
Rectangle 27 174

Using this PHP function mysql_escape_string() you can get a good prevention in a fast way.

mysql_escape_string Escapes a string for use in a mysql_query

wHERE 1=1   or  LIMIT 1
SELECT * FROM users WHERE name = '".mysql_escape_string($name_from_html_form)."' LIMIT 1

mysql - How can I prevent SQL injection in PHP? - Stack Overflow

php mysql sql security sql-injection
Rectangle 27 51

There is also the built in PHP function cal_days_in_month()?

"This function will return the number of days in the month of year for the specified calendar." http://php.net/manual/en/function.cal-days-in-month.

echo cal_days_in_month(CAL_GREGORIAN, 11, 2009); 
// = 30

This answer is much simpler and appropriate than the use of strtoTime. I don't see any downsides. To the top you go.

php - How to find the last day of the month from date? - Stack Overflo...

php date
Rectangle 27 51

There is also the built in PHP function cal_days_in_month()?

"This function will return the number of days in the month of year for the specified calendar." http://php.net/manual/en/function.cal-days-in-month.

echo cal_days_in_month(CAL_GREGORIAN, 11, 2009); 
// = 30

This answer is much simpler and appropriate than the use of strtoTime. I don't see any downsides. To the top you go.

php - How to find the last day of the month from date? - Stack Overflo...

php date
Rectangle 27 54

a) the method/function only reads the array argument

a) the method/function only reads the array argument => implicit (internal) reference b) the method/function modifies the array argument => value c) the method/function array argument is explicitly marked as a reference (with an ampersand) => explicit (user-land) reference

Or this: - non-ampersand array param: passed by reference; the writing operations alter a new copy of the array, copy which is created on the first write; - ampersand array param: passed by reference; the writing operations alter the original array.

Remember - PHP does a value-copy the moment you write to the non-ampersand array param. That's what copy-on-write means. I'd love to show you the C source of this behaviour, but it's scary in there. Better use xdebug_debug_zval().

Pascal MARTIN was right. Kosta Kontos was even more so.

Whenever people talk of references (or pointers, for that matter), they usually end up in a logomachy (just look at this thread!). PHP being a venerable language, I thought I should add up to the confusion (even though this a summary of the above answers). Because, although two people can be right at the same time, you're better off just cracking their heads together into one answer.

As you will see, the whole by-value/by-reference thing is very much related to what exactly are you doing with that array in your method/function scope: reading it or modifying it?

The manual says this (emphasis mine):

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition

hey, if you want to CHANGE the value in a function, consider that PHP's doing "pass-by-value"

There's another case that they don't mention, though: what if I don't change anything - just read? What if you pass an array to a method which doesn't explicitly marks a reference, and we don't change that array in the function scope? Aka:

<?php
function printArray($array) {}
$x = array(1);
printArray($x);

The same big and serious programmers, when they get even more serious, they talk about "memory optimizations" in regards to references. So does PHP. Because PHP is a dynamic, loosely typed language, that uses copy-on-write and reference counting, that's why.

It wouldn't be ideal to pass HUGE arrays to various functions, and PHP to make copies of them (that's what "pass-by-value" does, after all):

<?php

// filling an array with 10000 elements of int 1
// let's say it grabs 3 mb from you RAM
$x = array_fill(0, 10000, 1); 

// pass by value, right? RIGHT?
function readArray($arr) { // <-- a new symbol (variable) gets created here
    echo count($arr); // let's just read the array
}

readArray($x);

Well now, if this actually was pass-by-value, we'd have some 3mb+ RAM gone, because there are two copies of that array, right?

Wrong. As long as we don't change the $arr variable, that's a reference, memory-wise. You just don't see it. That's why PHP mentions user-land references when talking about &$someVar, to distinguish between internal and explicit (with ampersand) ones.

when an array is passed as an argument to a method or function is it passed by reference?

I came up with three (yeah, three) cases: a) the method/function only reads the array argument b) the method/function modifies the array argument c) the method/function array argument is explicitly marked as a reference (with an ampersand)

Firstly, let's see how much memory that array actually eats (run here):

<?php
$start_memory = memory_get_usage();
$x = array_fill(0, 10000, 1);
echo memory_get_usage() - $start_memory; // 1331840

Now let's make a function which only reads the said array as an argument and we'll see how much memory the reading logic takes:

Wanna guess? I get 80! See for yourself. This is the part that the PHP manual omits. If the $arr param was actually passed-by-value, you'd see something similar to 1331840 bytes. It seems that $arr behaves like a reference, doesn't it? That's because it is a references - an internal one.

Now, let's write to that param, instead of reading from it:

Again, see for yourself, but, for me, that's pretty close to being 1331840. So in this case, the array is actually being copied to $arr.

Now let's see how much memory a write operation to an explicit reference takes (run here) - note the ampersand in the function signature:

<?php

function printUsedMemory(&$arr) // <----- explicit, user-land, pass-by-reference
{
    $start_memory = memory_get_usage();

    $arr[0] = 1; // WRITE!

    echo memory_get_usage() - $start_memory; // let's see the memory used whilst reading
}

$x = array_fill(0, 10000, 1);
printUsedMemory($x);

My bet is that you get 200 max! So this eats approximately as much memory as reading from a non-ampersand param.

Saved me a couple of hours in debug of a memory leak!

Kosta Kontos: This is such an important question that you should mark this as the accepted answer. That said, @nevvermind: Great essay, but please include a top TL;DR section.

@AVIDeveloper - I've named it "Conclusions", but I guess that doesn't stand too well with you acronym-hungry people. :P

@nevvermind: I'm not an acronym groopy, the main diff is that Conclusions appear usually at the end of an article, while TL;DR appears as the first line for those who just need to short answer instead of going through a lengthy analysis. Your research is good and this is not criticism, just my $00.02.

You're right. I've put the conclusions at the top. But I'd still like people to stop being lazy in read the whole thing, before reaching to any conclusion. Scrolling is too easy for us to bother changing the order of things.

Are arrays in PHP passed by value or by reference? - Stack Overflow

php arrays reference pass-by-reference pass-by-value
Rectangle 27 25

Primarily, the reason I didn't mention threads in my answer is because the OP mentioned that they are building a web application. Using threads in PHP under Apache can be dangerous and one really needs to think about what they're doing. But, if this works for him, then great!

@ColinMorelli could you explain a little bit more about the dangerous please? I'm thinking of using threds too but like to consider them.

Asynchronous Function Call in PHP - Stack Overflow

php asynchronous network-programming
Rectangle 27 105

You can use debug_backtrace().

<?php

function epic( $a, $b )
{
    fail( $a . ' ' . $b );
}

function fail( $string )
{
    $backtrace = debug_backtrace();

    print_r( $backtrace );
}

epic( 'Hello', 'World' );
Array
(
    [0] => Array
        (
            [file] => /Users/romac/Desktop/test.php
            [line] => 5
            [function] => fail
            [args] => Array
                (
                    [0] => Hello World
                )

        )

    [1] => Array
        (
            [file] => /Users/romac/Desktop/test.php
            [line] => 15
            [function] => epic
            [args] => Array
                (
                    [0] => Hello
                    [1] => World
                )

        )

)

First time I found debug_backtrace() what a superb function. I'll be using this one!

php: determine where function was called from - Stack Overflow

php function-calls