- PHP show_source() Function
- Definition and Usage
- Syntax
- Parameter Values
- Technical Details
- Reconstruct get code of php function
- Exporting function source [duplicate]
- Reconstruct / get source code of a PHP function
- How get code of method in class [duplicate]
- Is it possible to get code of php function defined in eval'ed code?
- How to reconstruct paths from a multi-path Dijkstra?
- Get Code Line and File That's Executing the Current Function in PHP
- Get code line and file that's executing the current function in PHP?
- How to use _LINE_ in PHP to display current line of execution
- Get the current script file name
- Determine What Line a Function Was Executed From
- Finding out the filename that called my function in PHP
- Function to get currently executing directory name of executing file
- PHP - pass line number automatically as function argument
- How to find line number and file name of error
PHP show_source() Function
Using a test file («test.php») to output the file with the PHP syntax highlighted:
The browser output of the code above could be (depending on the content in your file):
The HTML output of the code above could be (View Source):
Definition and Usage
The show_source() function outputs a file with the PHP syntax highlighted. The syntax is highlighted by using HTML tags.
The colors used for highlighting can be set in the php.ini file or with the ini_set() function.
show_source() is an alias of highlight_file().
Note: When using this function, the entire file will be displayed — including passwords and any other sensitive information!
Syntax
Parameter Values
Parameter | Description |
---|---|
filename | Required. Specifies the file to display |
return | Optional. If set to TRUE, this function will return the highlighted code as a string, instead of printing it out. Default is FALSE |
Technical Details
Return Value: | If the return parameter is set to TRUE, this function returns the highlighted code as a string instead of printing it out. Otherwise, it returns TRUE on success, or FALSE on failure |
---|---|
PHP Version: | 4+ |
Changelog: | As of PHP 4.2.1, this function is now also affected by safe_mode and open_basedir. However, safe_mode was removed in PHP 5.4. PHP 4.2 — The return parameter was added. |
❮ PHP Misc Reference
Reconstruct get code of php function
Take following graph: This graph, for the sake of simplicity, has only paths from vertex A to J, going through multiple other vertices, which are all equal in cost, that is, the edge weight for each path add up to 10. For posterity’s sake, here is the code I used to turn the output of the multi-path Dijkstra into an array of paths: Solution 2: Like this?
Exporting function source [duplicate]
Possible Duplicate:
reconstruct/get code of php function
In JavaScript there is simply .toString() in function object, that outputs its source.
Is there an equivalent function or, how would one write one to do the same in PHP?
I am looking to write a PHP -> JS compiler. And, since token_get_all requires source as it’s parameter, I’m looking for this particular export.
The equivalent function to toString() in php is strval()
PHP DOCS: String and strval
strval — Get string value of a variable
There is a descriptive answer here (regarding converting something from type to string) on stackoverflow.
if you want the source code of a function in php you must use ReflectionFunction to find the file which it is defined in as well as start and end line.
ReflectionFunction::getFileName(); ReflectionFunction::getStartLine(); ReflectionFunction::getEndLine();
Then you must read the file and substr that portion.
Php — How Do I See The Final Text Of A Query Resulting, PDO simulates binding if you set it like that; in this topic you can read about the debugDumpParams statement, which is also in the PHP documentation.There is no way, however, to check if the value substitution happened properly when you leave it to the real sql engine; one workaround could be a SELECT with the field …
Reconstruct / get source code of a PHP function
Reconstruct / get source code of a PHP function — PHP [ Ext for Developers : https://www.hows.tech/p/recommended.html ] Reconstruct / get source code of a …
How get code of method in class [duplicate]
How to get the code of the method? I’m trying something like this: :
//SiteController.php class SiteController < public function actionIndex()< //bla bla.. >public function actionCustomMethod() < if(1)< echo '1'; >else < echo '2'; >> > //i need take code of "function actionCustomMethod()< . >" preg_match('/function actionCustomMethod[^>]+/i', file_get_contents('SiteController.php'), $out); //but the preg_match returns /* public function actionCustomMethod()< if(1)< echo '1'; */
I don't know how to get the code with nested braces. Any ideas?
class SiteController < public function actionIndex()< //bla bla.. >public function actionCustomMethod() < if(1)< echo '1'; >else < echo '2'; >> > $res = new ReflectionMethod('SiteController', 'actionCustomMethod'); $start = $res->getStartLine(); $end = $res->getEndLine(); $file = $res->getFileName(); echo 'get from '.$start.' to '.$end .' from file '.$file.'
'; $lines = file($file); $fct = ''; for($i=$start;$i <$end+1;$i++) < $num_line = $i-1; // as 1st line is 0 $fct .= $lines[$num_line]; >echo ''; echo $fct;
Php - Refactoring: How to replace function call with, I don't need full recursion, like if module1() function contain another function call - I don't need to go deep inside of it. Just let it be on level 1. It also doesn't matter for me how to do it, with PhpStorm, another IDE …
Is it possible to get code of php function defined in eval'ed code?
I am trying to implement a code obfuscation system. The idea is to have a piece of php code and encrypt it and store in a text file. When executing the code, just fetch the encrypted text, decrypt it and eval it to get the functionality.
Now I am wondering if there is a way to get the function code after the eval(). I tried ReflectionFunction to get the function code but so far I could not. Is there a way to get the code of the function defined in the eval'ed code?
Assuming the text-file it contains an encrypted class : how about decrypting the file, put PHP-tags around it and store it in a temp file. After that is done include('tmp.php'); the file, remove the temp file and call the Reflector functionality?
Is there a way in PHP to calculate the checksum of a, Call getFileName () and load the source code, e.g. with file_get_contents () or file () (which splits the file into an array of lines) Call getStartLine (), and getEndLine (), and extract those lines from the source file That will give you the source code for the function, which you can then hash to form …
How to reconstruct paths from a multi-path Dijkstra?
I am currently writing a PHP library for graphs. I have already implemented a single-path Dijkstra's algorithm successfully, but now struggle with implementing a multi-path version at the path reconstruction stage.
This graph, for the sake of simplicity, has only paths from vertex A to J, going through multiple other vertices, which are all equal in cost, that is, the edge weight for each path add up to 10. The modified Dijkstra correctly produces the following output (which is the array $this->prev ):
Array ( [A] => [B] => Array ( [0] => A ) [C] => Array ( [0] => A ) [D] => Array ( [0] => C ) [E] => Array ( [0] => C ) [F] => Array ( [0] => E [1] => D ) [G] => Array ( [0] => A ) [H] => Array ( [0] => G ) [I] => Array ( [0] => H ) [J] => Array ( [0] => B [1] => F [2] => I ) )
The current, single-path Dijkstra path reconstruction algorithm is implemented as such:
public function get($dest) < $destReal = $dest; $path = array(); while (isset($this->prev[$dest])) < array_unshift($path, $dest); $dest = $this->prev[$dest]; > if ($dest === $this->start) < array_unshift($path, $dest); >return array( 'path' => $path, 'dist' => $this->dist[$destReal] ); >
Is there a way to modify the above, such that it returns me all the paths in a paths array? I have already thought about using maybe a stack or DFS, but couldn't come up with a solution. I also gave foreach loops and recursion a try, to no avail.
What I essentially want to happen is the result to be processed as follows:
- J connects to B, B connects to A, hence $paths[0] = ['J', 'B', 'A']
- J connects to F, F connects to E and D, hence continue on through E, remembering to return to F, then create another path through D, resulting in paths[1] = ['J', 'F', 'E', 'C', 'A'] and $paths[2] = ['J', 'F', 'D', 'C', 'A']
- J connects to I, I connects to H, H connects to G and G connects to A, resulting in $paths[3] = ['J', 'I', 'H', 'G', 'A']
Any help would be appreciated!
Actually, a modified DFS function I named "enumerate" solved this question. For posterity's sake, here is the code I used to turn the output of the multi-path Dijkstra into an array of paths:
/** * Returns all shortest paths to $dest from the origin vertex $this->start in the graph. * * @param string $dest ID of the destination vertex * * @return array An array containing the shortest path and distance */ public function get($dest) < $this->paths = []; $this->enumerate($dest, $this->start); return array( 'paths' => $this->paths, 'dist' => $this->dist[$dest], ); > /** * Enumerates the result of the multi-path Dijkstra as paths. * * @param string $source ID of the source vertex * @param string $dest ID of the destination vertex */ private function enumerate($source, $dest) < array_unshift($this->path, $source); $discovered[] = $source; if ($source === $dest) < $this->paths[] = $this->path; > else < if (!$this->prev[$source]) < return; >foreach ($this->prev[$source] as $child) < if (!in_array($child, $discovered)) < $this->enumerate($child, $dest); > > > array_shift($this->path); if (($key = array_search($source, $discovered)) !== false) < unset($discovered[$key]); >>
function output_paths(source, dest, tail) < if source == dest: output([dest] + tail) for each node in prev[dest]: output_paths(source, node, [dest] + tail) >output_paths(source=A, dest=J, tail=[])
Php - Get code of a specific user define function or class, I have a folder with some classes and another with some functions. Usually one class or function per file, but that is not always the case. On a few occasions a class might be accompanied with a
Get Code Line and File That's Executing the Current Function in PHP
Get code line and file that's executing the current function in PHP?
You can use debug_backtrace().
So, in your log function, you would be able to retrieve the filename and line number from which the log function was called.
I'm using this approach in my logging classes and it has significantly reduced the amount of code required to get meaningful log data. Another benefit would be readability. Magic constants tend to get quite ugly when mixed with strings.
function log($msg)
$bt = debug_backtrace();
$caller = array_shift($bt);
// echo $caller['file'];
// echo $caller['line'];
// do your logging stuff here.
>
How to use _LINE_ in PHP to display current line of execution
Get the current script file name
Just use the PHP magic constant __FILE__ to get the current filename.
But it seems you want the part without .php . So.
A more generic file extension remover would look like this.
function chopExtension($filename) return pathinfo($filename, PATHINFO_FILENAME);
>
var_dump(chopExtension('bob.php')); // string(3) "bob"
var_dump(chopExtension('bob.i.have.dots.zip')); // string(15) "bob.i.have.dots"
Using standard string library functions is much quicker, as you'd expect.
function chopExtension($filename) return substr($filename, 0, strrpos($filename, '.'));
>
Determine What Line a Function Was Executed From
I suppose a solution could be to use debug_backtrace .
The given example gets a backtrace like this :
array(2) [0]=>
array(4) ["file"] => string(10) "/tmp/a.php"
["line"] => int(10)
["function"] => string(6) "a_test"
["args"]=>
array(1) [0] => &string(6) "friend"
>
>
[1]=>
array(4) ["file"] => string(10) "/tmp/b.php"
["line"] => int(2)
["args"] =>
array(1) [0] => string(10) "/tmp/a.php"
>
["function"] => string(12) "include_once"
>
>
So, should include what you want 😉
And if you just want to output the trace (not likely), there is also debug_print_backtrace .
Finding out the filename that called my function in PHP
A solution might be to use the debug_backtrace function : in the backtrace, that kind of information should be present.
Or, as Gordon pointed out in a comment, you can also use debug_print_backtrace if you just want to output that information and not work with it.
For instance, with temp.php containing this :
include 'temp-2.php';
my_function();
and with temp-2.php containing this :
function my_function() var_dump(debug_backtrace());
>
Calling temp.php (i.e. the first script) from my browser gets me this output :
array
0 =>
array
'file' => string '/. /temp/temp.php' (length=46)
'line' => int 5
'function' => string 'my_function' (length=11)
'args' =>
array
empty
In there, I have the " temp.php " filename -- which is the one in which the function has been called.
Of course, you'll have to test a bit more (especially in situations where the function is not in the "first level" included file, but in a file included by another one -- not sure debug_backtrace will help much, there. ) ; but this might help you get a first idea.
Function to get currently executing directory name of executing file
To get the directory of the file I use the dirname function like this :
PHP - pass line number automatically as function argument
You can use debug_backtrace inside of Logger::Log to retrieve a call stack, which includes the file and line number of the code that called Logger::Log . That's a sensible thing to include in loggers in general.
How to find line number and file name of error
Your custom error function can capture the file and line as arguments:
function customError($errno, $errstr, $errfile, $errline) $e=$errno . ",". $errstr . "," . $errfile . "," . $errline;
.
>
A callback with the following siganture. NULL may be passed instead, to reset this handler to its default state.
bool handler ( int $errno , string $errstr [, string $errfile [, int $errline [, array $errcontext ]]] )