FRIHOSTFORUMSSEARCHFAQTOSBLOGSCOMPETITIONS
You are invited to Log in or Register a free Frihost Account!


PHP reading a line?





Diablosblizz
I was wondering if PHP was able to read a specific line from a .txt file and display it?

Example, I will be using the $logged[username] (from my member system) variable to get the users username and then access it on my server computer. So it will open up the file on the server computer and read what it says.

But, one problem. Here is an example:

Code:

[CHARACTER]
character-height = 0
character-posx = 3213
character-posy = 3423
character-rights = 3
character-ismember = 1
character-messages = 0
character-lastconnection = localhost
character-lastlogin = 20070624
character-energy = 100
character-gametime = 0
character-gamecount = 1800



I want it to read the 3 in "character-rights". Just the 3, nothing else.

Is this possible. I hope you understand me.

Thanks!
rohan2kool
Basically, php can't do this on it's own.. you need to do something called 'parsing'. It is basically converting a text stream in symbols which can be used while programming. The best approach would be to break the stream into lines. for ex:

Code:

$file = "file.txt";
$fh = fopen($filename, "r");
$datum = fread($fh, filesize($file));

$buffer = "";
$lines = array();
$x = 0;

for($i=0; $i<(strlen($datum) + 1); $i++) {
    if(($datum[$i] == '\n') || ($i == strlen($datum)) {
        $lines[$x] = $buffer;
        $buffer = "";
        $x++;
    }

    $buffer .= $datum[$i];
}


This will basically split it into lines as an array. Next, for each line you need to remove the whitespace, meaning convert:

Code:

character-right = 3;

OR

character-left      =           5;


to:

Code:

character-right=3;

OR

character-left=5;


Make a function for this (i'll post the code for this too later) and remove the whitespace from all the lines we just parsed.

Next, just search for the string 'character-rights' in each line. If any of the line returns true, then just substr the line like:

Code:

substr($line[$num], strlen('character-rights'), (strlen($line[num]) - strlen('character-rights')));


rohan
Diablosblizz
I don't think I can change it because there is a program reading that line and it must be like that.
rohan2kool
no.. man.. you don't have to change it at all.. once you read a file, the file's contents which you store into a variable, are in the memory (not always and exactly all of it in the memory, but for abstraction purposes, let's say it is).. they are no longer connected to the file. Any changes in the variable won't in any ways reflect to any change in the file. Moreover, since we've opened the file with a 'r' option, there's no way we can write to the file. We just load the file line-wise in the memory, and change the values in the memory... making it easy for us to obtain info from it.

As for the whitespace stripping function, here's the code:

Code:

define('CHAR_WHITESPACE', 1);
define('CHAR_UNCLASSIFIED', 2);

function characterType($input) {
   if(strlen($input) > 1) {
      $input = $input[0];
   }
      
   switch($input) {
      case ' ':
      case '\t':
      case '\n':
      case '\r': {
         return CHAR_WHITESPACE;
      } break;
      
      default: {
         return CHAR_UNCLASSIFIED;
      }
   }
}

function stripWhitespace($string, $beg = true, $trail = true) {
   $nString = $string;
        $subLength = strlen($string);
      
   $brPos = 0;
   $brPosE = 0;
      
   if($beg === true) {
      for($i = 0; $i < ($subLength); $i++) {
         if($this->characterType($string[$i]) != CHAR_WHITESPACE) {
            $brPos = $i;
            break;               
         }
      }
   }
      
   if($trail === true) {
      for($i = ($subLength-1); $i >= 0; $i--) {
         if($this->characterType($string[$i]) != CHAR_WHITESPACE) {
            $brPosE = $i;
            break;
         }
      }
         
      $brPosE = ($brPosE + 1) - $brPos;
   } else {
      $brPosE = $subLength - $brPos;
   }
      
   $nString = substr($string, $brPos, $brPosE);
      
   return $nString;
}


use it as: stripWhitespace($string [,$beg [, $trail]]); where $string = the string to be stripped of whitespace. $beg = true if you want to remove the beginning whitespaces; $trail = true if you want to remove the trailing whitespaces.

rohan
Aredon
Diablosblizz wrote:

Code:

[CHARACTER]
character-height = 0
character-posx = 3213
character-posy = 3423
character-rights = 3
character-ismember = 1
character-messages = 0
character-lastconnection = localhost
character-lastlogin = 20070624
character-energy = 100
character-gametime = 0
character-gamecount = 1800


I want it to read the 3 in "character-rights". Just the 3, nothing else.


PHP has built-in support for this. parse_ini_file

Code:

<?php
$arr=parse_ini_file("blah.txt",true);
echo $arr['CHARACTER']['character-rights']; // echos 3
?>

But you usually want your file to be in the INI extension when following its syntax.
Code:

<?php
$arr=parse_ini_file("blah.ini");
echo $arr['character-rights']; // echos 3
?>
rohan2kool
ohh.. crap.. i didn't realize this was an .ini file... silly me...
Diablosblizz
Code:

$arr=parse_ini_file("http://24.141.134.127/RS/URLTOTHEFILE/$logged[username].txt",true);
echo $arr['CHARACTER']['character-rights']; // echos 3


Before I start the $logged[username] gets the users username that is logged in. Smile

I did this, and now I get this:

Code:

Warning: parse_ini_file() [function.parse-ini-file]: URL file-access is disabled in the server configuration in C:\Program Files\xampplite\htdocs\runescapeconnect.php on line 38

Warning: parse_ini_file(http://24.141.134.127/RS/URLTOTHEFILE/Diablosblizz.txt) [function.parse-ini-file]: failed to open stream: no suitable wrapper could be found in C:\Program Files\xampplite\htdocs\runescapeconnect.php on line 38


What did I do wrong? :S
rohan2kool
look.. you didn't really do anything wrong but choose a sucky hosting service [in case it's paid, in case it's on frihost, which i doubt.. then well.. you shouldn't expect much].

Your hosting service has disabled the ability of php to open remote files [files that do not reside on the computer running the script, but some other computer, connected via a network]. All you can do is, ask your host to allow accessing of remote files. In case you are getting the error on a machine you debug on and have access to the php.ini file on, try this:

find php.ini [in windows, it's generally c:\php.ini OR c:\windows\php.ini OR c:\windows\system32\php.ini].

Once there, look for: 'allow_url_fopen'. It might have been set to 'off' or commented out. If it is commented out, de-comment it [remove the ';' in front of it] and set it's value to 'on'.

In case of a hosting service, you can try ini_set(), I doubt if that would work. What would really work is if you have the files locally, but are connecting to it via a network interface, in which case you should just load the local file.

Refer:

http://php.net/manual/en/function.ini-set.php

[edit]
sorry mate, ini_set does not allow you to set allow_url_fopen. It has to be changed from the php.ini itslef.
Diablosblizz
You just confused me even more. :S

What am I supposed to do? In my case my host is not frihost, and it is not paid.
MrBlueSky
Here is a function you can use:

Code:

  function fromFile($str, $filename) {
    $fh = fopen($filename,'r');
    while (!feof($fh)) {     
      if (preg_match("/\s*$str\s*=\s*(.+)/i", fgets($fh), $res))
        return $res[1];
    }
    return null;
  }


If you have, for example, in the same directory a file called 'data.txt' which contains this text:

Code:


[CHARACTER]
character-height = 0
character-posx = 3213
character-posy = 3423
character-rights = 3
character-ismember = 1
character-messages = 0
character-lastconnection =localhost
character-lastlogin = 20070624
character-energy = 100
character-gametime = 0
character-gamecount = 1800


you can call fromFile("characer-rights", "data.txt") to get the value set for character-rights which in this case returns 3:

Code:

<?php

  function fromFile($str, $filename) {
    $fh = fopen($filename,'r');
    while (!feof($fh)) {     
      if (preg_match("/\s*$str\s*=\s*(.+)/i", fgets($fh), $res))
        return $res[1];
    }
    return null;
  }
 
  if ($r = fromFile("character-rights", "data.txt"))
    echo "Character-rights is set to ".$r;
  else
    echo "Character-rights not set";
   
 
?>


The argument is case-insensitive, so it doesn't matter if you use "Character-rights", "CHARACTER-RIGHTS" or whatever. Additional spaces are ignored. It returns null when the value isn't found.
rohan2kool
Diablosblizz wrote:
You just confused me even more. :S

What am I supposed to do? In my case my host is not frihost, and it is not paid.


now.. it's obvious that i have confused you. The part where i mentioned the hosting.. it was for the humour part of it. Completely pointless, so ignore it.

Well, you must be knowing about php.ini : it's a file which php uses for configurational purposes. Now, you can have files of two types:

1. Local files [the files that reside on your computer]
2. Remote files [the files that reside on some other computer]

php uses a global file access sorta principle meaning, both files to the scripter, appear to be of similar type, meaning all functions/operations which use files, can be used with a local file or a remote file. Internally, the things are different though. There are different methods of accessing a remote file and that for a local file. So, php uses wrappers, which are basically different snippets of code [call it libraries, packages or whatever] to handle different types of files. Now, the thing is.. it also allows us to switch off specific wrappers. One way to switch off wrappers for remote files is to set allow_url_fopen to 'off' in php.ini. allow_url_fopen is a parameter in php.ini.

as is obvious in ur case, ur hosting service has set allow_url_fopen to 'off' meaning you cannot open remote files with filesystem functions. now, you can request the service to set it to 'on', but since it isn't paid.. it's not gonna happen in most cases... Another alternative is to use CURL functions [although it's gonna require some advanced programming skills]

Refer:

http://php.net/manual/en/ref.curl.php
Related topics
How To : Secure Your PHP Website
PHP DB Error: syntax error
Fatal PHP error
uma grande dúvida em php, por favor me ajudem
PHP script has MSQL access denied
[PHP] Error link
phpBB Error, seems to be a MYSQL DB error...
[Resolved] Object Orientated PHP errors
PHP Login Problem
PHP/Blogger error
Anyone Using Simple PHP Blog
Need help with php script
need some help - php switch code
php msql problem
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.