Archive for May 2011

order by in php with mysql

connection.inc.php :

<?php
$host='localhost';
$user_name='root';
$password='';
@$con = mysql_connect("$host","$user_name","$password");
if ($con)
 {echo '<br>host coonected<br>';}
else
  {
  die('Could not connect ');
  }
?>

order_by_table.php :

<?php

require 'connection.inc.php';

if (mysql_select_db('test'))
if($result=mysql_query("select * from test order by name",$con))
  {
     echo "<br><table><tr><td>sno</td><td>name</td></tr>";
    while($data = mysql_fetch_array($result))
  {
  echo "<tr><td>".$data['sno'] . "</td><td>" .$data['name']."</td></tr>";
  }
  echo "</table><br>data selected<br>";
  }
else
  {
  echo '<br>data not selected :'.mysql_error().'<br>';
  }

mysql_close($con);
?>

run " order_by_table.php "

output :


host coonected

snoname
2human
2human

data selected


Mina Halim Hanna - مينا حليم حنا


Samples of my work


• http://www.jesusloves-you.com/ PHP ( Codeigniter )
http://freecopts.net/ PHP ( Codeigniter )
• http://www.boswrkz.com/ PHP ( Codeigniter ) 
http://www.nader3m.com/ PHP ( Codeigniter )  
• http://www.alomdolagy.com/ PHP ( Codeigniter )

3ajelhost.com

•  http://3ajelhost.com/                         ( Codeigniter )
•  http://3ajel.3ajelhost.info/yanbu         ( Codeigniter )
•  http://3ajel.3ajelhost.info/watches/     ( Codeigniter )
•  http://3ajel.3ajelhost.info/techno/       ( Codeigniter )
•  http://3ajel.3ajelhost.info/student/       ( Codeigniter )
•  http://3ajel.3ajelhost.info/lap/             ( Codeigniter )
•   http://3ajel.3ajelhost.info/hij/             ( Codeigniter )
•   http://3ajel.3ajelhost.info/elmasdar/    ( Codeigniter )
•   http://3ajel.3ajelhost.info/a3ras/         ( Codeigniter )
•   http://www.alshaerf.com/site/            ( Codeigniter )
•   http://www.shoaelshark.com/            ( Codeigniter )
•   http://online-academic.com/              ( Codeigniter )

Creative-eg.com

• http://creativemediahouse.net/ar PHP
• http://creativemediahouse.net/en PHP

http://www.creative-eg.us/all/templ/ PHP

http://www.holwelsham.com/holw/en/index-1.php PHP 
http://www.familypharmacia-eg.com/ PHP
http://www.excel-marble.com/en/ PHP
http://www.sts8.com PHP
http://orient-eg.com/en PHP
http://orient-eg.com/ar PHP 
http://eacd-eg.com/test/eacd/ PHP
http://www.alfagroupegypt.com/test/alfa/ PHP


http://kolaljmal.com PHP
http://learnx.info PHP
https://cdbsa.com PHP

http://askemarat.com PHP
http://alahadelah.com PHP
http://ayaat.us PHP
http://eskan.com.sa PHP
http://j-alturki.com  PHP
http://alrajhi-sa.com/ PHP
http://www.almehmalperfumes.com PHP
http://creative-eg.us/all/lhr/ PHP 
http://arabisques.com PHP
http://q8-iphone.com/q8/  PHP  

http://sh-zaid.com PHP
http://heteen.net PHP
http://faarbi.com PHP
http://superweb-me.com/ PHP
•  http://agarhashim.com/ PHP
•  http://liwan-aqar.com/ PHP
•  http://www.dfjuice.com PHP 


http://creative-eg.us/all/advan PHP
http://creative-eg.us/all/astrahat PHP
http://creative-eg.us/all/golden PHP
http://creative-eg.us/all/webhouse/ PHP  
http://creative-eg.us/all/beauty PHP
http://creative-eg.us/all/fruit PHP
http://creative-eg.us/all/ahadela PHP 
http://www.creative-eg.us/all/rahma PHP
http://creative-eg.us/all/gam3ya/ PHP
http://creative-eg.us/all/aljmzawi PHP
http://creative-eg.us/all/beza PHP 
http://creative-eg.us/all/mosque PHP
http://creative-eg.us/all/ayat PHP
http://creative-eg.us/all/gowhara PHP
http://creative-eg.us/all/golden PHP
http://creative-eg.us/all/media PHP
http://creative-eg.us/all/ask PHP
http://creative-eg.us/all/turky PHP
http://creative-eg.us/all/bazar PHP
http://creative-eg.us/all/arabisc PHP
http://creative-eg.us/all/3tor PHP
http://creative-eg.us/all/liwan PHP
http://creative-eg.us/all/eskan PHP
http://creative-eg.us/all/mobile PHP
http://creative-eg.us/all/hashem PHP
http://creative-eg.us/all/iraq PHP
http://creative-eg.us/all/kids PHP
http://creative-eg.us/all/7omat PHP
http://creative-eg.us/all/quait PHP
http://creative-eg.us/all/batoot PHP
http://creative-eg.us/all/q8cars PHP
http://creative-eg.us/all/hteen PHP
http://creative-eg.us/all/bawasel PHP
http://creative-eg.us/all/webname PHP



4smart.net

http://www.gooolonline.com/m - Mobile website _ PHP from scratch
http://www.gooolonline.com/ - PHP
http://www.gooolonline.com/rss.php - XML , PHP
http://gooolonline.com/ - PHP , AJAX the Java last 6 articles
http://www.4photos.net/old/rss1.php - XML , PHP
http://www.q8sns.com/ - Magic 4smart CMS
http://www.feqhweb.com/ - Magic 4smart CMS
http://www.alfarouq.org/f/ - Magic 4smart CMS
http://www.mudarib.biz/ - PHP
http://www.ussclub.com/ - PHP
http://www.scoopchart.com/ - PHP
http://www.drabigh.com/ - PHP
http://aikido-ae.com/ - PHP

Special Work

www.ehow.com - Parsing it using PHP and REGEX
www.cbc.com - Parsing it using PHP and REGEX
www.118.com - Parsing it using PHP and REGEX
www.cbc.ca - Parsing it using PHP and REGEX
www.picsearch.com - Parsing it using PHP and REGEX
-> write the keyword to search in the form and it will pick up all the pics in small and in large size with it's width,height,colored or not and animated or not with paging
www.sxc.hu -> return the small and medium pics from the site - Parsing it using PHP and REGEX
www.wikihow.com - Parsing it using PHP and REGEX
www.youtube.com -> return the pic and flv and the flash player from the search keyword and converting FLV to MP3 using FFMPEG library
• Login -> Ajax Login like hotmail login
• Ajax Calendar -> PHP calendar : from scratch without using any formula or any thing from the internet
• Auto Suggest -> Ajax Suggestion
• Bible Viewer -> Ajax Bible viewer
• PHP Hosting people in rooms manager - PHP
• Control panel for data entry team in 4smart.net PHP , AJAX , Javascript

Mine work - from more than 4 years

http://stmaria.brinkster.net – ASP Classic
http://almanahry.brinkster.net – ASP Classic

Yahoo Mail : mn_halim@yahoo.com
Hot Mail : mn_halim@hotmail.com

Thanks in advance
Mina Halim Hanna
PHP web Developer
مينا حليم حنا
مبرمج ومطور بى اتش بى

Login Page

<!-- Save Page as login.php -->
<?php


error_reporting(0);  
include("config.php"); 


$username=$_POST['txtUsername'];
$password=base64_encode($_POST['txtPassword']);  // Password is encrypted with base64_encode() 


?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Login</title>
<link href="css/style.css" type="text/css" rel="stylesheet" />
</head>
<?php
if(isset($_POST['btnLogin']) && ($_POST['btnLogin']=="Login"))
{
$strError=array();    // Array variable $strError is created to display error messages
if(empty($username))
{
$strError[] .="<li>Please Enter Valid Username</li>";
}
if(empty($password))
   {
       $strError[] .="<li>Please Enter Valid Password</li>";
   }

$select = mysql_query("SELECT * FROM tbl_admin WHERE 
username = '".$username."'
AND 
password = '".$password."'"
);

$count = mysql_num_rows($select);

if($count > 0)
{
header('Location: welcome.php');
}
else if((!empty($username)) && (!empty($password)))
{
$strError[] .="<li>Invalid Username or Password</li>";
}
}
?>
<body>
<form name="frmLogin" id="frmLoginId" method="post" action="" target="" enctype="multipart/form-data">
<div id="login">
<div id="loginheading">Login
</div>
<div id="errormsg">
<?php 
foreach($strError as $key => $val)
{
echo $val;
}
?>
</div>
<div id="logintitle">Username : 
</div>
<div id="loginfield"><input type="text" name="txtUsername" id="txtUsernameId" value="<?php echo $username; ?>" size="20" />
</div>
<div id="logintitle">Password : 
</div>
<div id="loginfield"><input type="password" name="txtPassword" id="txtPasswordId" value="" size="20" />
</div>
<div class="logincontent"><input type="checkbox" name="" value=""> Remember Me <a href="registration.php" style="margin-left:7px; text-decoration:none;"> Sign Up! </a><a href="" style="margin-left:7px; text-decoration:none;"> Forget Password? </a>
</div>
<div id="submitbtn"><input type="image" name="btnLogin" value="Login" border="0" src="images/login.png" width="70" height="30" />
</div>
</div>
</form>
</body>
</html>


ZAMPP installation

In our previous tutorial we saw how to install Vertrigo web server, today I will describe how to install XAMPP web server in your local computer. XAMPP is a very powerful software that provides integrated PHP environment. To create PHP environment we need Apache, PHP, MySQL but XAMPP consolidate those three things. So follow the following steps to install ZAMPP in your computer as a server.  

ZAMPP Installation Procedure

I divided the installation procedure into three steps.

Step 1: 
We can install ZAMPP in two ways, one is manually and second one is through installer. In this section we try to install XAMPP manually. To do this, at first you need to download ZAMPP from ZAMPP DOWNLOAD.

Step 2: 

After downloading the file, extract the downloaded file. After extracting the file you need to choose where you want to install XAMPP such that I want to install ZAMPP in D folder. So put your extracted file in D folder. Double click on Setup_xampp.bat. Now click on xampp-control.exe, a window will open. From this window you need to start Apache and MySQL.
 
Your work is done. Now it is time to put http://localhost/ in your browser.

Step 3:
It is another way to install ZAMPP. In step 2 we install ZAMPP in D folder but if you want to install ZAMPP in c drive then follow the following steps.

In this installation setup_xampp.bat file is not necessary. You can directly install it by clicking on the xamp-control.exe file. After installation, a XAMPP icon will appear in your desktop. When you Click on this icon, a window will appear. From this window you need to start Apache and MySQL. By this time, we have created PHP environment, now you can start our PHP tutorials.

change array size using array_pad() in php

<?php

$num=array(1,2,3,4,5,6,7,8,9,10);
echo '<b>array before grow elements :</b>';
foreach($num as $num1)
{
echo ' '.$num1;
}
echo '<br><br>';

$num = array_pad($num, 20,'a') ; //only additionally adding elements have 'a' value

// $num = array_pad($num, 20,'') ; additionally adding elements have empty

echo '<b>array after grow elements :</b>';
foreach($num as $num1)
{
echo ' '.$num1;
}


?>


output :

array before grow elements : 1 2 3 4 5 6 7 8 9 10

array after grow elements : 1 2 3 4 5 6 7 8 9 10 a a a a a a a a a a

 note :

1) just modify  " $num = array_pad($num, 20,'a') ;  " as "  $num = array_pad($num, 20,'') ; "  for empty
2) that means array index raise but with empty values

update in php with mysql

connection.inc.php :

<?php
$host='localhost';
$user_name='root';
$password='';
@$con = mysql_connect("$host","$user_name","$password");
if ($con)
 {echo '<br>host coonected<br>';}
else
  {
  die('Could not connect ');
  }
?>

update_table.php :

<?php

require 'connection.inc.php';

if (mysql_select_db('test'))
if(mysql_query("update test set name='humans'where sno=1",$con))
  {
    $result=mysql_query("select * from test where name='humans'",$con);
     echo "<br><table><tr><td>sno</td><td>name</td></tr>";
    while($data = mysql_fetch_array($result))
  {
  echo "<tr><td>".$data['sno'] . "</td><td>" .$data['name']."</td></tr>";
  }
  echo "</table><br>data updated<br>";
  }
else
  {
  echo '<br>data not updated :'.mysql_error().'<br>';
  }

mysql_close($con);
?>

run " update_table.php "

output:


host coonected

snoname

data updated

Control Structures in PHP: ELSE

Often you'd want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what else is for. else extends an if statement to execute a statement in case the expression in the if statement evaluates to FALSE. For example, the following code would display a is bigger than b if $a is bigger than $b, and a is NOT bigger than b otherwise:

<?php

if ($a > $b) {

echo "a is bigger than b";

} else {

echo "a is NOT bigger than b";

}

?>

The else statement is only executed if the if expression evaluated to FALSE, and if there were any elseif expressions - only if they evaluated to FALSE as well (see elseif).

PHP form

In this tutorial we will know how to create PHP forms. To understand this tutorial you need to have basic idea about HTML form. Typically for collecting information from users we use PHP form. Many kinds of form we use to collect user information such as login form, registration form. PHP form start with <form> tag and ends with </form> tag. See the example below how PHP form works.


<form action="landing_page.php" method="post">
FirstName:<input type="text" name="first_name" /><br />
LastName:<input type="text" name="last_name" /><br />
<input type="submit" value="submit" />
</form>

We usually use two parts in PHP form. The first part is action, and the second part is method. In the action part we use action page links. And in the method part we use method name such as $_GET or $_POST method. This method describes how we collect information from users.You can get more information about PHP $GET and $_POST from our tutorial section. 

Control Structures in PHP: WHILE

while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:

   

while (expr)

statement

The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.

Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax:

    

while (expr):

statement

...

endwhile;

The following examples are identical, and both print the numbers 1 through 10:


 

/* example 1 */

$i = 1;

while ($i <= 10) {

echo $i++; /* the printed value would be

$i before the increment

(post-increment) */

}


/* example 2 */

$i = 1;

while ($i <= 10):

echo $i;

$i++;

endwhile;

?>

header() in php


<?php
header('location:'.'http://http://some-php-programs.blogspot.com/');

?>


output :

automatically http://some-php-programs.blogspot.com/ opened




======================================================


<?php
$webpage='http://some-php-programs.blogspot.com/';
header('location:'.$webpage);

?>

output :
automatically http://some-php-programs.blogspot.com/ opened

Capítulo 17: Manejo de Mail en PHP

Conexión a un server IMAP o POP3:

mail_handler=imap_open(string_mbox,user,password);

Donde mbox es de la forma:
{IP:PORT}MailBox

Ejemplos:

$mail=imap_open(“{190.190.190.190:143}INBOX”,”user”,”pass”);

Conexión a la carpeta INBOX de un servidor IMAP (puerto 143)

$mail=imap_open(“{190.190.190.190:110}”,”user”,”pass”);

Conexión a la carpeta raíz de un servidor POP3 (puerto 110)

Una vez establecida la conexión la función devuelve un handler que se utiliza en el resto de las funciones para acceder a las carpetas y mails dentro de las mismas.

Ejemplo:

$mbox = imap_open ("{your.imap.host:143}", "username", "password");
echo "

Mailboxes

\n";
$folders = imap_listmailbox ($mbox, "{your.imap.host:143}", "*");
if ($folders == false) {
echo "Call failed
\n";
} else {
while (list ($key, $val) = each ($folders)) {
echo $val."
\n";
}
}
echo "

Headers in INBOX

\n";
$headers = imap_headers ($mbox);
if ($headers == false) {
echo "Call failed
\n";
} else {
while (list ($key,$val) = each ($headers)) {
echo $val."
\n";
}
}
imap_close($mbox);

Una vez terminada la conexión se usa:

imap_close(mail_handler);

Manejo de MailBoxes:

int=imap_createmailbox (mail_handler string_mbox)

String mbox debe estar codificado con imap_utf7_encode() y el formato del string es el mismo que en imap_open.

Ejemplo:

$mbox = imap_open("{your.imap.host}","username","password",OP_HALFOPEN)
|| die("can't connect: ".imap_last_error());
$name1 = "phpnewbox";
$name2 = imap_utf7_encode("phpnewböx");
$newname = $name1;
echo "Newname will be '$name1'
\n";
# we will now create a new mailbox "phptestbox" in your inbox folder,
# check its status after creation and finaly remove it to restore
# your inbox to its initial state
if(@imap_createmailbox($mbox,imap_utf7_encode("{your.imap.host}INBOX.$newname"))) {
$status = @imap_status($mbox,"{your.imap.host}INBOX.$newname",SA_ALL);
if($status) {
print("your new mailbox '$name1' has the following status:
\n");
print("Messages: ". $status->messages )."
\n";
print("Recent: ". $status->recent )."
\n";
print("Unseen: ". $status->unseen )."
\n";
print("UIDnext: ". $status->uidnext )."
\n";
print("UIDvalidity:". $status->uidvalidity)."
\n";

if(imap_renamemailbox($mbox,"{your.imap.host}INBOX.$newname","{your.imap.host}INBOX.$name2")) {
echo "renamed new mailbox from '$name1' to '$name2'
\n";
$newname=$name2;
} else {
print "imap_renamemailbox on new mailbox failed: ".imap_last_error()."
\n";
}
} else {
print "imap_status on new mailbox failed: ".imap_last_error()."
\n";
}
if(@imap_deletemailbox($mbox,"{your.imap.host}INBOX.$newname")) {
print "new mailbox removed to restore initial state
\n";
} else {
print "imap_deletemailbox on new mailbox failed:
".implode("
\n",imap_errors())."
\n";
}
} else {
print "could not create new mailbox: ".implode("
\n",imap_errors())."
\n";
}
imap_close($mbox);

Devuelve true si pudo crear el mailbox o false en caso contrario.

int=imap_deletemailbox (mail_handler, string_mbox);

Elimina el mailbox indicado, el formato de mbox es el mismo que en imap_open.

int=imap_renamemailbox (mail_handler, string_old_mbox, string_new_mbox)

Permite renombrar un mailbox, el nombre del mailbox debe estar en el mismo formato que en imap_open.

obj_array=imap_getmailboxes (mail_stream, string_ref, string_pattern)

Devuelve un vector de objetos con información sobre los mailboxes

Los objetos que se encuentran en el vector tienen seteados los siguientes data_members:

· name – Nombre del mailbox (completo) encodeado, decodificar con imap_utf7_decode()
· delimiter – Delimitador usado para separar la jerarquía de mailboxes
· attributes – Es un bitmask que puede compararse con:
- LATT_NOINFERIORS (el mailbox no tiene subcarpetas)
- LATT_NOSELECT (es un mailbox no seleccionable)
- LATT_MARKED (mailbox marcado)
- LATT_UNMARKED (mailbox no marcado)

Ejemplo:

$mbox = imap_open("{your.imap.host}","username","password")
|| die("can't connect: ".imap_last_error());
$list = imap_getmailboxes($mbox,"{your.imap.host}","*");
if(is_array($list)) {
reset($list);
while (list($key, $val) = each($list))
{
print "($key) ";
print imap_utf7_decode($val->name).",";
print "'".$val->delimiter."',";
print $val->attributes."
\n";
}
} else
print "imap_getmailboxes failed: ".imap_last_error()."\n";
imap_close($mbox);
object=imap_status (mail_handler, string_mailbox, SA_ALL)

SA_ALL es una constante para recuperar toda la información sobre el mailbox, devuelve un objeto con los siguientes data members seteados:

· messages – número de mensajes en el mailbox
· recent – número de mensajes recientes en el mailbox
· unseen – número de mensajes no vistos en el mailbox

Ejemplo:

$mbox = imap_open("{your.imap.host}","username","password",OP_HALFOPEN)
|| die("can't connect: ".imap_last_error());
$status = imap_status($mbox,"{your.imap.host}INBOX",SA_ALL);
if($status) {
print("Messages: ". $status->messages )."
\n";
print("Recent: ". $status->recent )."
\n";
print("Unseen: ". $status->unseen )."
\n";
print("UIDnext: ". $status->uidnext )."
\n";
print("UIDvalidity:". $status->uidvalidity)."
\n";
} else
print "imap_status failed: ".imap_lasterror()."\n";
imap_close($mbox);

int imap_num_msg (mail_handler)

Devuelve el número de mensajes en el mailbox actual. (El abierto por el mail_handler)

int imap_num_recent (mail_handler)

Devuelve el número de mensajes recientes del mailbox correspondiente a mail_handler.

Manejo de mensajes:

object=imap_fetchstructure (mail_handler, int msg_number)

Devuelve un objeto con la estructura del mensaje recuperado:

Table 1. Returned Objects for imap_fetchstructure()

type Primary body type
encoding Body transfer encoding
ifsubtype True if there is a subtype string
subtype MIME subtype
ifdescription True if there is a description string
description Content description string
ifid True if there is an identification string
id Identification string
lines Number of lines
bytes Number of bytes
ifdisposition True if there is a disposition string
disposition Disposition string
ifdparameters True if the dparameters array exists
dparameters Disposition parameter array
ifparameters True if the parameters array exists
parameters MIME parameters array
parts Array of objects describing each message part

Cuando el mensaje es multipart “parts” es un vector donde cada elemento es un objeto con los siguientes datamembers:

· type
· encoding
· subtype
· description
· lines
· disposition

Luego según el trasnfer encoding (ver tabla 3) se puede usar la función de decodificación apropiada

Table 2. Primary body type

0 text
1 multipart
2 message
3 application
4 audio
5 image
6 video
7 other

Table 3. Transfer encodings

0 7BIT
1 8BIT
2 BINARY
3 BASE64
4 QUOTED-PRINTABLE
5 OTHER

Las funciones de decodificación provistas son:

string=imap_base64(string) convierte de base 64 a 8 bits
string=imap_8bit(string) convierte de 8 bits a quoted printable
string=imap_utf7_decode(string) convierte de 7 bits a 8 bits
string=imap_qprint(string) convierte de quoted printable a 8 bits
string=imap_binary(string) convierte de 8 bits a base64

El formato de salida “string” es 8 bits, si el formato de encoding es otro basta con usar la función apropiada.

string=imap_fetchbody (mail_handler, int msg_number, string part_number )

Recupera la parte indicada del body de un determinado mensaje. No realiza ningún tipo de decodificación.

array= imap_headers (mail_handlers)

Devuelve un vector de headers para el mailbox actual (cada header es un string y es un elemento del vector)

object=imap_rfc822_parse_headers(string headers)

Parsea un header de acuerdo a rfc822, devuelve un objeto con los siguientes data_members:

· remail
· date
· Date
· subject
· Subject
· in_reply_to
· message_id
· newsgroups
· followup_to
· references

string imap_body (mail_handler, int msg_number)

Devuelve el body de un determinado mensaje.

Envío de mail:

Enviar mail desde PHP es sencillo con la función:

bool= mail (string to, string subject, string message [, string additional_headers])

Ejemplo

mail("rasmus@lerdorf.on.ca", "My Subject", "Line 1\nLine 2\nLine 3");

Ejemplo 2. Envio de mail con encabezado.

mail("nobody@aol.com", "the subject", $message,
"From: webmaster@$SERVER_NAME\nReply-To: webmaster@$SERVER_NAME\nXMailer:
PHP/" . phpversion());

Workaround to CSS and JS cache woes

Here is a method I found of making it so the browser receives new CSS and Javascript files when they are changed on the server. It works by appending a timestamp parameter of when the file was last modified.


function urlmtime($url) {
$parsed_url = parse_url($url);
$path = $parsed_url['path'];
if ($path[0] == "/") {
$filename = $_SERVER['DOCUMENT_ROOT'] . "/" . $path;
} else {
$filename = $path;
}
if (!file_exists($filename)) {
// If not a file then use the current time
$lastModified = date('YmdHis');
} else {
$lastModified = date('YmdHis', filemtime($filename));
}
if (strpos($url, '?') === false) {
$url .= '?ts=' . $lastModified;
} else {
$url .= '&ts=' . $lastModified;
}
return $url;
}

function include_css($css_url, $media='all') {
// According to Yahoo, using link allows for progressive
// rendering in IE where as @import url($css_url) does not
echo '<link rel="stylesheet" type="text/css" media="' .
$media . '" href="' .
urlmtime($css_url) . '">'."\n";
}

function include_javascript($javascript_url) {
echo '<script type="text/javascript" src="' .
urlmtime($javascript_url) .
'"></script>'."\n";
}

php regular expressions start of line: Removing a substring from the start of a string

When using regular expressions with PHP one must take care of a few minute details.

For instance, today I received a request to debug an application.


$patterns[0] = "/^Top/";
$replacements[0] = 'bear';
$text=" Top/Top/Top/Business/Top/Accounting/Top";
$text = preg_replace($patterns, $replacements, $text);
echo $text . "\n\n";



Can you spot the problem?

Hint: running the above produces:

Top/Top/Top/Business/Top/Accounting/Top



Here is the solution: many people mistakenly interpret ^ as the start of the line when in fact it represents the start of the string.

Modifying the above regular expression to


$patterns[0] = "/^Top\//";
$replacements[0] = 'bear/';
$text="Top/Top/Top/Business/Top/Accounting/Top";
#$text = preg_replace("/^(Top\/)/", '__', $text);
$text = preg_replace($patterns, $replacements, $text);
echo $text;


produces:

# bear/Top/Top/Business/Top/Accounting/Top

which was the desired solution in this problem.

delete array elements with unset() in php

<?php

$num=array(1,2,3,4,5,6,7,8,9,10);
echo '<b>array before delete elements :</b>';
foreach($num as $num1)
{
echo ' '.$num1;
}
echo '<br><br>';

//delete array element

unset($num[3]);
unset($num[0],$num[1],$num[2]);
echo '<b>array after delete elements (1,2,3,4) :</b>';
foreach($num as $num1)
{
echo ' '.$num1;
}


?>

output :

array before delete elements : 1 2 3 4 5 6 7 8 9 10

array after delete elements (1,2,3,4) : 5 6 7 8 9 10