Category: PHP

Get The IP Address Of A Visitor Through PHP

12 November, 2008 | PHP | No comments

I have talked previously about getting an IP address of a visitor with PHP. The failing in using the value of $_SERVER['REMOTE_ADDR'] is that if the visitor is using a proxy then you will get the proxy IP address and not the visitors real IP address.

This function works by going through any variables in the $_SERVER array that might exist that would contain information to do with IP addresses. If they are all empty then the function finally looks at $_SERVER['REMOTE_ADDR'] value and returns this as a default.

function getRealIpAddr(){
 if ( !empty($_SERVER['HTTP_CLIENT_IP']) ) {
  //check ip from share internet
  $ip = $_SERVER['HTTP_CLIENT_IP'];
 } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
  //to check ip is pass from proxy
  $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
 } else {
  $ip = $_SERVER['REMOTE_ADDR'];
 }
 return $ip;
}

To run this function just call it.

echo getRealIpAddr();

This function was originally found here.

Moving Files In PHP

11 November, 2008 | PHP | No comments

I have been asked a couple of times recently if PHP has a function that will move a file, so I thought I would put the solution here.

PHP has a function called rename() which can be used to rename a file, but because of the way it works it can be used to move files. Let’s say that you wanted to rename a file called test.txt to test_back.txt, this can be accomplished by doing the following.

rename("test.txt", "test_back.txt");

However, if you want to move the file from one directory to another you can do the following.

rename("test.txt", "backups/test_back.txt");

The return value of rename() is boolean that tells you if the rename was successful or not, this can be used to error check like this.

if ( !rename("test.txt", "backups/test_back.txt") ) {
 // rename not successful, try another way
}

Be aware that if you try the following:

rename("test.txt", "test.txt");

The function will return true.

To rename a directory you should do the following:

rename("directory/directoryold","directory/directorynew");

Note the absence of the trailing slash on the directory name, PHP will give an error if this slash is added.

Recursive chmod Function In PHP

10 November, 2008 | PHP | No comments

File permissions are important, especially if you want to let a user agent view a file. If the file doesn’t have the correct permissions then it will not be accessed and could cause your script to fail. To get around this you might want to use the following function. It uses the PHP function chmod(), which sets permissions, but it does this recursively from wherever you set it off from.

function chmod_R($path, $filemode) {
 if ( !is_dir($path) ) {
  return chmod($path, $filemode);
 }
 $dh = opendir($path);
 while ( $file = readdir($dh) ) {
  if ( $file != '.' && $file != '..' ) {
   $fullpath = $path.'/'.$file;
   if( !is_dir($fullpath) ) {
    if ( !chmod($fullpath, $filemode) ){
     return false;
    }
   } else {
    if ( !chmod_R($fullpath, $filemode) ) {
     return false;
    }
   }
  }
 }
 
 closedir($dh);
 
 if ( chmod($path, $filemode) ) {
  return true;
 } else {
  return false;
 }
}

This is especially useful for some scripts that create or copy files as these files might be created without the correct permissions. You can call this function by giving it a directory and an octal value for the preferences. Note that the octal value is important. If you want to give the files the permission of 775 then you must use 0775. The following is an example of this function in action, it had been given the current directory that the script resides in to run from.

chmod_R(dirname(__FILE__),0775);

Everything under this directory, including the script file, will be set to 0775, which is standard for most purposes.

Swap Values Without Temporary Varaibles In PHP

28 October, 2008 | PHP | No comments

I have talked about swapping values without a temporary third variable before, but there is another way to do this which doesn’t make the code unreadable. This is by using the list() function in the following way.

$a = 1;
$b = 2;
list($a,$b) = array($b,$a);

This swaps the two values over. The good thing about this function is that you can swap any number of values over without the need to create lots of confusing temporary variables or using complicated looking bitwise operators. Take 4 variables.

$a = 1;
$b = 2;
$c = 3;
$d = 4;

These values can be entirely swapped using the list() function in the following way.

list($a,$b,$c,$d) = array($d,$c,$b,$a);

It should be noted that this code isn’t faster than using temporary variables and so should only really be used to make it clear what is going on.

Quickly Run Any PHP Code Through A Form

15 October, 2008 | PHP | No comments

NOTE: This bit of code is potentially very dangerous and should NOT be uploaded to your web host. I only use this function on my localhost to quickly check that a snippet of code works.

If you want to quickly run some PHP code, and don’t want to have to go through creating a file just to see the outcome of a simple calculation is then this snippet might be of some use to you.

It works by taking the contents of the textarea and creating a file with the filename of 'tempcodefile.php', which contains that code. The created file is then included in order to run the code, the output of which is displayed at the top of the screen.

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<html>
<head>
<title>PHP Tester</title>
</head>
<body>
<?php
 if (isset($_POST["code"])) {
  $code = $_POST["code"];
  $file = fopen('tempcodefile.php', 'w');
  fwrite($file, $code);
  require_once('tempcodefile.php');
 } else {
  $code = "";
 }
?>
<form action='<?php echo $_SERVER["PHP_SELF"]; ?>' method='post'>
<div style='text-align:center'>
<textarea rows="30" cols="150" name="code"><?php echo $code; ?></textarea>
<br />
<input type="submit" value="Run" />
</div>
</form>
</body>
</html>

To run this code enter some PHP code (including the <?php and > PHP brackets) into the text box and click on the run button.

<?php echo 1+1; ?>

The first time the form is run a file will be created containing this code, and the output "2" will be printed at the top of the screen. Error reporting is turned on and errors are displayed at the start of the script so if you enter something that doesn’t work it will tell you about it.

This script is useful if you just want to run something quickly, but beware that if you upload this to your web server you are at risk of someone running some code that will delete all the files on your site.