Category Archives: PHP - Page 3

String concatenation in PHP

This can be done many ways in PHP. I’m here going to show my two preferred ways:

My personal favorite:

echo string1, string2, string3

Example:

$score = 5;
echo "You scored ", $score, " points!";

Will print:

You scored 5 points!

Using print and dot syntax:

print string1.string2.string3

Example:

$score = 7;
print "You scored ".$score." points!";

Will print:

You scored 7 points!

I try to use the first syntax as much as possible because I believe that it is easier to read in code. Trying to keep it simple

Get the visitors IP

Getting the IP of you visitors is an easy task in PHP. You find the information in the $_SERVER array:

print "Your IP is ".$_SERVER['REMOTE_ADDR']."";

This will show your public IP adress.
Every now and then I need to check my own public IP so I put this very simple page togheter: Check your IP

Simple password generator

Due to a lack of creativity in my passwords I decided to make a small and simple password generator. This is as simple as it gets. It looks terrible but works like a charm 🙂

if you want to see/try it you can find it here: Simple Password Generator

Here is the code:


$letters = array('a','b','c','d','e','f','g','h','i','j','k','l','m',
                 'n','o','p','q','r','s','t','u','v','x','y','z');

$capitals = array('A','B','C','D','E','F','G','H','I','J','K','L','M',
                 'N','O','P','Q','R','S','T','U','V','X','Y','Z');

$numbers = array(1,2,3,4,5,6,7,8,9,0);

$specials = array('-','_','!','@','%','€','&','?','+','*','/');

if(isset($_POST['create']) && is_numeric($_POST['characters'])){
    $chars = array();
    $password = array();

    if(isset($_POST['letters'])){
        $chars = array_merge($chars, $letters);
    }
    if(isset($_POST['capitals'])){
        $chars = array_merge($chars, $capitals);
    }
    if(isset($_POST['numbers'])){
        $chars = array_merge($chars, $numbers);
    }
    if(isset($_POST['special'])){
        $chars = array_merge($chars, $specials);
    }
    
    $characters = $_POST['characters'];
    
    for($i = 0;$i < $characters;$i++){
        array_push($password, $chars[rand(0,count($chars, true))]);
    }

    $pass = implode("",$password);

}
?>

The following assumptions apply:
create is the name of the submit button of the form
characters is the value from the textfield containing the number of characters for the password
letters is a checkboxvalue telling the program to use the letters array
numbers is a checkboxvalue telling the program to use the numbers array
special is a checkboxvalue telling the program to use the special characters array
$pass variable contains the newly created password

NOTE: This code is not ment for public use since it obviously lacks many error checking and anti hacking features

Testet in PHP v5.3.3