Page 1 of 1

Grabbing a line of PHP code from a file and running it

Posted: Sun Jun 03, 2007 1:10 pm
by mecablaze
Hello,

I am writing a PHP app that needs a function that can open a certain a PHP file on my server. then run the code on a certain line in that file. For simplicity's sake, let's say I have a file like this called commands.php:

Code: Select all

<? // (line 1)
echo "Line 2";
echo "Line 3";
echo "Line 4";
echo "Line 5";
echo "Line 6";
echo "Line 7";
echo "Line 8";
?> // (line 9)
And I have another program PHP file that grabs a certain line in commands.php and runs it.

If this is possible, it would make the task I'm doing much much easier. Thanks!

-Joel

Posted: Sun Jun 03, 2007 1:27 pm
by maliskoleather
why do you want it to only run one line?

i would think it would be much easier to make a folder, then have it just run one file in that folder. That way, youre not limited to one line of code, and can properly debug stuff much easier.
something like:

Code: Select all

//$filename is the script you want to run...
$filename = 'foo';
include('path/to/folder/'.$foo);

Posted: Sun Jun 03, 2007 2:16 pm
by feyd
Your needs need a rethink I think.

Posted: Sun Jun 03, 2007 2:20 pm
by mecablaze
So I guess there's no way to do that?

:(

I'll just try a completely different approach to this part of my program.

Thanks anyways!

Posted: Sun Jun 03, 2007 2:21 pm
by John Cartwright
It's certainly possible, although there are far better ways to accomplish this. The design simply makes very little sense.

Posted: Sun Jun 03, 2007 2:29 pm
by galbus
If you really need to do it this way then look at the fread() function as there is a way of doing it.

The issue that was raised is that it is much easier, faster and just plain better if you use an include file for each command as maliskoleather has suggested. It shouldn't be that hard to split the commands.php file into seperate files. If it is very large and don't want to do it by hand you could even write a function using fread() to do it for you.

Posted: Mon Jun 04, 2007 1:14 pm
by RobertGonzalez
You could also put the commands in an array in a single file and include that file then call the member of the array you want. Though this is not the best way to do it. But it doeas beat trying to read a file:
commands.php

Code: Select all

<?php
$commands = array(
  'comm1' => 'Some command #1',
  'comm2' => 'Some command #2',
  'comm3' => 'Some command #3',
  'comm4' => 'Some command #4',
);
?>
processor.php

Code: Select all

<?php
include_once 'commands.php';
// Now you can call them using $command['comm1'] syntax
?>