Saturday, August 30, 2008

ternary operator ?:

ternary operation is not hard but not easy to use.
it can be short form of if...else and switch...case it is used in an expression as follows :
condition ? valueIfTrue : valueIfFalse
therefore we wrote

if($i>5){
 echo 'more than 5';
}else{
 echo 'not more than 5';
}
by ternary operator we can use just only
echo ($i>5)?'more than 5':'not more than 5';

or something like
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
instead of
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}

you can also use ?: instead of switch case too.

Thursday, August 28, 2008

php protect file with limit download rate

$local_file = 'file.zip';
$download_file = 'name.zip';
// set the download rate limit (=> 20,5 kb/s)
$download_rate = 20.5;

if(file_exists($local_file) && is_file($local_file)){
    header('Cache-control: private');
    header('Content-Type: application/octet-stream');
    header('Content-Length: '.filesize($local_file));
    header('Content-Disposition: filename='.$download_file);
    flush();
    $file = fopen($local_file, "r");
    while(!feof($file)){
        // send the current file part to the browser
        print fread($file, round($download_rate * 1024));
        // flush the content to the browser
        flush();
        // sleep one second
        sleep(1);
    }
    fclose($file);
}else {
    die('Error: The file '.$local_file.' does not exist!');
}

Monday, August 25, 2008

javascript unique array

function unique(a) {
  var temp = [];
  var temp2 = [];
  for (c in a)
  temp[a[c]] = c
  for (c in temp)
  temp2[temp[c]] = c
  return temp2;
}

Wednesday, August 06, 2008

Another javascript highlighter

Insert head section with
<style type="text/css">@import url(http://retsam.krad.googlepages.com/jush.css);</style>
<script type="text/javascript" src="http://retsam.krad.googlepages.com/jush.js" defer="defer"></script>


and in body with
<body onload="jush.highlight_tag('pre');">

Your source code in pre tag here
<pre class="jush">
input source code here
</pre>


Don't forgot to change < to &lt;

All your code will look like this
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> <?php print_r($_POST['title']); ?> </TITLE>
<script type="text/javascript" src="prettify.js"></script>
<script type="text/javascript">
document.onload=temps();
document.onload=setTimeout('chargement();sec=10;',3000);
var x=window.confirm("Are you sure you are ok?")
if (x) window.alert("Good!")
else window.alert("Too bad")
</script>

</HEAD>
<BODY>
<font color="red">TESTING red</font>
<font color="#0f0f0f">TESTING red</font>
<table>
<!-- HTML COMMENT-->
<?
print_r('POST:'.$_POST.'<BR>');
print_r('GET :'.$_GET);
function Google(){
print_r($_POST);
}
?>

<TR><TD>TEST table TR TD</TD><TD>TEST table TR TD 2</TD></TR>
<input value="test" name="test">
</BODY>
</HTML>