PHP File Cannot Enter Some Part of Code

PHP file cannot enter some part of code

As written in the comment above, you should divide and conquer to make your life easier (especially as you write the code while you play around with it in that large function). That does work as easy as:

function file_put($number, $data)
{
$path = sprintf("C:/temp/wamp/www/file%d.txt", $number);
file_put_contents($path, $data);
}

for example that is just replacing the many duplicate lines where you just need a (numbered) file you put some string in.

But you can also do this with more complex stuff, like the database operation. You probably want to move the error handling out of your sight as well as taking care to connect to the database when needed and a more flexible way to fetch the data. That can be done by moving the (softly deprecated) mysql_* functions into one or two classes of its' own, so that it gets out of your sight. That will make it's usage much more easier (which I show first):

// Create your database object to use it later on:
$config = array(
'server' => 'localhost',
'name' => 'root',
'password' => '',
'db' => 'test',
);
$db = new MySql($config);

I called the database class MySql as it represents the mysql connection and it works with the old mysql extension. You only need to pass that database object then into the function in your question. Combined with the file_put function, it would look like this:

function checkin(MySql $DB, $TechID, $ClientID, $SiteID)
{
$query = sprintf("SELECT `Type` FROM `Log` WHERE `TechID` = '%d' ORDER BY LogTime DESC LIMIT 1", $TechID);
file_put(5, $query);

$result1 = $DB->query("SELECT COUNT(*) FROM Log");
$result2 = $DB->query($query);

foreach ($result1 as $row1) {
list($count) = $row1;
$data = "ClientID:$ClientID TechID:$TechID SiteID:$SiteID Count:$count"
file_put(3, $data);
foreach ($result2 as $row2) {
file_put(4, $data);
}
}
}

Still the checkin function is close to being large (12 lines of code already), but is much shorter than your first version because it delegates the work for writing the files and accessing the database. I hope this demonstration is useful. What follows is the full code example:

/**
* MySql Exception
*/
class MySqlException extends RuntimeException
{
}

/**
* MySql Database Class
*/
class MySql
{
private $server;
private $name;
private $password;
private $db;
private $connection;

public function __construct(array $config)
{
$this->server = $config['server'];
$this->name = $config['name'];
$this->password = $config['password'];
$this->db = $config['db'];
}

private function connect($server, $name, $password)
{
$this->connection = mysql_connect($server, $name, $password);
if (!$this->connection) {
$this->error("Unable to connect to '%s' as user '%s'", $server, $name);
}
}

private function select($db)
{
if (!mysql_select_db($db, $this->connection)) {
$this->error("Unable to select database '%s'", $db);
}
}

private function close()
{
$this->connection && mysql_close($this->connection);
}

private function connectSelect()
{
$this->connect($this->server, $this->name, $this->password);
$this->select($this->db);
}

/**
* @param $query
* @return MySqlResult
*/
public function query($query)
{
$this->connection || $this->connectSelect();
$result = mysql_query($query, $this->connection);
if (!$result) {
$this->error("Unable to execute query '%s'", $query);
}
return new MySqlResult($result);
}

/**
* @param string $format
* @param ...
* @throws MySqlException
*/
private function error($format)
{
$args = func_get_args();
array_shift($args);
$format .= ': %s';
$args[] = $this->connection ? mysql_error($this->connection) : mysql_error();
throw new MySqlException(vsprintf($format, $args));
}

public function __destruct()
{
$this->close();
}
}

/**
* MySql Result Set - Array Based
*/
class MySqlResult implements Iterator, Countable
{
private $result;
private $index = 0;
private $current;

public function __construct($result)
{
$this->result = $result;
}

public function fetch($result_type = MYSQL_BOTH)
{
$this->current = mysql_fetch_array($this->result, $result_type);
return $this->current;
}

/**
* Return the current element
* @link http://php.net/manual/en/iterator.current.php
* @return array
*/
public function current()
{
return $this->current;
}

public function next()
{
$this->current && $this->fetch();
}

/**
* Return the key of the current element
* @link http://php.net/manual/en/iterator.key.php
* @return mixed scalar on success, or null on failure.
*/
public function key()
{
return $this->current ? $this->index : null;
}

/**
* Checks if current position is valid
* @link http://php.net/manual/en/iterator.valid.php
* @return boolean The return value will be casted to boolean and then evaluated.
* Returns true on success or false on failure.
*/
public function valid()
{
return (bool)$this->current;
}

/**
* Rewind the Iterator to the first element
* @link http://php.net/manual/en/iterator.rewind.php
* @return void Any returned value is ignored.
*/
public function rewind()
{
$this->fetch();
}

/**
* Count of rows.
*
* @link http://php.net/manual/en/countable.count.php
* @return int The count of rows as an integer.
*/
public function count()
{
return mysql_num_rows($this->result);
}
}

// Create your database object to use it later on:
$config = array(
'server' => 'localhost',
'name' => 'root',
'password' => '',
'db' => 'test',
);
$db = new MySql($config);

function file_put($number, $data)
{
$path = sprintf("C:/temp/wamp/www/file%d.txt", $number);
file_put_contents($path, $data);
}

function checkin(MySql $DB, $TechID, $ClientID, $SiteID)
{
$query = sprintf("SELECT `Type` FROM `Log` WHERE `TechID` = '%d' ORDER BY LogTime DESC LIMIT 1", $TechID);
file_put(5, $query);

$result1 = $DB->query("SELECT COUNT(*) FROM Log");
$result2 = $DB->query($query);

foreach ($result1 as $row1) {
list($count) = $row1;
$data = "ClientID:$ClientID TechID:$TechID SiteID:$SiteID Count:$count";
file_put(3, $data);
foreach ($result2 as $row2) {
file_put(4, $data);
}
}
}

checkin($db, 1, 2, 3, 4);

Include PHP, not working when included php code is for files in different directories

The problem: The links in your menu are relative to the pages in which menu.php is included. For example, including menu.php in art1.php makes the link to contact.php point to http://yoursite.com/articles/contact.php rather than http://yoursite.com/contact.php.

Solution: Use absolute URLs in your menu links:

<ul>
<li><a href="http://yoursite.com/index.php" class="navon">Home Page</a></li>
<li><a href="http://yoursite.com/contact.php">Contact us</a></li>
</ul>

One way to highlight the current page is to do something like this in menu.php:

<?php
// DO NOT CHANGE THESE
$server = 'http://'.$_SERVER["SERVER_NAME"]; // domain name or localhost
$this_page = $server . $_SERVER["PHP_SELF"]; // name of the script that
// includes menu.php

/*
* This array holds the menu items. I put in a few examples.
*
* The key (left side/before =>) is the URL to a page.
* It takes the form "$server/path/to/somepage.php"
* Make sure to include $server at the beginning.
*
* The value (right side/after =>) is the text that will appear in the menu.
*
* This is the only part you need to change to fit your site.
* Make sure you put a comma after each item, except the last one.
*/
$menuitems = array(
"$server/index.php" => 'Home Page', // notice the
"$server/home_page/page1.php" => 'Page 1', // comma after
"$server/home_page/articles/art1.php" => 'Article 1', // each item
"$server/contact.php" => 'Contact Us' // except the last
);


// The rest just generates an unordered list in HTML
// You do not need to change anything below.

$doc = new DOMDocument();
$menu = $doc->createElement('ul');
$doc->appendChild($menu);

// this creates the list of links in your menu
foreach ($menuitems as $url=>$label) {
$item = $doc->createElement('li');
$menu->appendChild($item);

$link = $doc->createElement('a',$label);
$link->setAttribute('href', $url);

// if the current page matches the current link,
// set class="current" on that link
if ($url === $this_page)
$link->setAttribute('class', 'current');

$item->appendChild($link);
}

echo $doc->saveHTML($menu);
?>

How do I read the source code without access to file

You can technically see the function content using Reflection, but you must include the file.

function thatIsMyFunction($a) {
$x = $a * 3 / ($a + 7);
return $x;
}

function function_dump($function) {
try {
$func = new ReflectionFunction($function);
} catch (ReflectionException $e) {
echo $e->getMessage();
return;
}

$start = $func->getStartLine() - 1;

$end = $func->getEndLine() - 1;

$filename = $func->getFileName();

echo implode("", array_slice(file($filename),$start, $end - $start + 1));
}


function_dump('thatIsMyFunction');

// will dump
/*
function thatIsMyFunction($a) {
$x = $a * 3 / ($a + 7);
return $x;
};
*/

PHP cannot write to text file

You have to provide Web server path of actual file location path in your server instead of url.

$test = 'http://advokatami.bg/ot/a/docs/test/test.txt';

Replace it by Server path

$test = '<location_of_your_webroot_folder_in_server>/ot/a/docs/test/test.txt';

Make sure test have permission for read and write publicly.

How can you check your folder path?

1) Make test.php file in ot folder with below code

<?php
echo dirname(__FILE__);
die();

2) Upload it in ot folder.

3) execute file from browser http://advokatami.bg/ot/test.php

4) Copy path before \ot\.... and replace it on <location_of_your_webroot_folder_in_server>.

Not able to write a file


  1. If file does not exists, is_writable causes your error. You can simply omit this condition and try to write to file and check the result of fopen:

    if ($handle = fopen($ics_file, 'w')) {
    if (fwrite($handle, $ics_contents) === FALSE)
    echo "Cannot write to file ($ics_file)\n\n";
    else {
    # echo "Success, wrote to <b>schedule.ics</b><br>\n\n";
    }

    fclose($handle);
    exit;
    }
    else {
    echo "Cannot write to file ($ics_file)\n\n";
    exit;
    }
  2. If previous solution does not help, check directory/file permissions. File access depends on server configuration. Try to create file by your own, and set up permission to 777 (for testing). Then script should have access to write into it.

  3. You are reading whole file content to memory. In such case, if you don't need to have the file on disk, you can just send the content to the client using something like this PHP - send file to user.

Python: can't execute a php file

Thanks to @nitrin0 I found the answer:

if you want to use subprocess.run() you have to specify the FULL path of everything (Ex. subprocess.run(['/usr/bin/php', '/home/admin/hen-durance/writetofile.php ', word]))

if you want to use os.system() you can avoid to specify the path, but remember to format the command in a proper way (Ex. os.system('php writetofile.php ' + word) [notice the space before the closing quote, I didn't put that there before so my script executed php writetofile.phpword that obviously can't work])

Can anyone get access to my PHP source code?

With a correctly configured web server, the PHP code isn't visible to your website visitors. For the PHP code to be accessible by people who visit your website, the server would have to be configured to display it as text instead of processing it as PHP code.

So, in other words, if you visit your website and you see a HTML page and not PHP code, your server is working correctly and no one can get to the PHP code.



Related Topics



Leave a reply



Submit