1. How do I get a user's IP address?
<?
$domain = GetHostByName ( $REMOTE_ADDR );
?>
2.
How do I insert javascript in php code?
<?
echo "<script language=\"JavaScript\">\n" ;
echo "alert(" javascript from php ");\n" ;
echo "</script>" ;
?>
3.
How do I generate a random number from php?
To generate a random number between 0 and 100 do this:
srand((double)microtime()*1000000);
echo rand(0,100);
4.
How do I check whether a string contains HTML?
There are two ways you can do it, one is using a regular expression the other is comparing strings.
First the regular expression approach:
if (preg_match("/([\<])([^\>]{1,})*([\>])/i", $string)) {
echo "string contains html";
}
And here is the other approach:
if(strlen($string) != strlen(strip_tags($string)){
echo "string contains HTML";
}
5.
How do I find out weather a number is odd or even?
$i = 10;
if ( $i&1 )
{
echo "$i is odd";
}
else
{
echo "$i is even";
}
6.
How do I set the browser timeout?
If your script is too complex to finish within the standard 30 seconds you can set a new value with the function:
set_time_limit(900);
this sets the timeout too 900 seconds / 15 minutes.
7. How do I get the Filename out of a directory name?
Use strrpos - same as strpos but in reverse. Find the last occurence of '/' then move forward one position and then substr from that position onwards to the end of the string.
<?php echo substr($url,strrpos($url,'/')+1); ?>
8. How do I remove all characters from within curly brackets or square brackets?
Use preg_replace and regular expressions. The examples below remove everything in a string that is within curly braces or square brackets.
echo preg_replace(" (\[.*?\])",'',"King Kong [2005]");
echo preg_replace(" (\(.*?\))",'',"King Kong (Amazing Box Set)");
9. How can I remove a trailing character in a string, remove last occurence of a character?
Use the SUBSTR command:
$strWithoutLastChar = substr("abcdef", 0, -1);
This will return "abcde"