calling php function from another file - php

I am a PHP beginner and trying to write PHP classes that work with HTML and MySql.
I am facing the following problem,
I have created a class called DatabaseManager that contains the function get_value. This function simply returns a value. In another file, I am calling this function on a button click using java script. But the link doesn't seem to work between the two files....Can someone help me?
thank you.
Here's my file that contains the PHP class.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<?php
class DatabaseManager {
private $value=1;
public function get_value ()
{
return value;
}
}
/php>
</body>
</html>
and here's the other file that calls it.
<html>
<head>
<?php include("DatabaseManager.php"); ?>
<script type="text/javascript">
function connect()
{
<?php
$database_manager= new DatabaseManager;
echo "the value is" . $database_manager->get_value();
?>
}
</script>
</head>
<body>
<input type="button" value="Search " onclick="connect()">
</body>
</html>
The name of the file that contains the function get_value is DatabaseManager.php

DO Like this
In Databasemanager.php
<?php
class DatabaseManager {
private $value = 1;
public function get_value() {
return $this->value;
}
}
?>
In another PHP file
<html>
<head>
<?php include("Databasemanager.php"); ?>
<script type="text/javascript">
function connect()
{
<?php
$database_manager= new DatabaseManager;
echo "the value is" . $database_manager->get_value();
?>
}
</script>
</head>
<body>
<input type="button" value="Search " onclick="connect()">
</body>
</html>

A few things:
in DatabaseManager.php remove all HTML. You're including the file elsewhere, you don't need or want duplicated HTML tags.
Remove the # in your MySQL section. This suppresses any errors you are having.
Switch to PDO or MySQLi. They are safer (if used properly)
Your closing php tag is wrong in the database file. You have /php> it should be ?>
Your class does absolutely nothing as-is.

There are multiple things here that you're douing wrong.
You don't need the html code in the first example.
You close the php wrong /php> should generate an error, it should be ?>
When your instantiating your DatabaseManager class you've left out the parentheses which means that the constructor will never get called, this should also generate an error.
You're probably trying to use alert in javascript which in this case you're not doing.
It should look something like this instead:
<?php
class DatabaseManager {
private $value = 1;
function getValue() {
return $this->value;
}
}
?>
And in your html (still php, but the one containing the html-markup) file:
<html>
<head>
<script type="text/javascript">
function connect() {
alert("
<?php
include "nameofDBManagerClassFile.php"
$dbm = new DatabaseManager();
echo "the value is " . $dbm->getValue();
?>
");
}
</script>
</head>
<body>
</body>
</html>
It could also be that you think that the php-code that is inside of the javascript function will not be executed untill you call the JS function connect() this is not so. PHP code is executed on the server and thus will be called when a user requests that webpage, the javascript on the other hand is clientside and will be executed in the users browser. I highly recommend that you read up on both php and JavaScript.

You do it wrong way, to output something in your JavaScript function connect() make this :
function connect() {
alert("
<?php
$database_manager= new DatabaseManager;
echo "the value is" . $database_manager->get_value();
?>
");
}
because php code is executed apart from your on click event.
Actually it's unclear what you wish to get, but you misunderstand the basics.
[edited to clarify users question how to output something to the screen]

I think the easiest way is to use require i another file.
require('login.php');
function get_value()
{
return get_value;
}

Related

Php OOP does not work

I have a problem. I writed OOP in php, but it does not work. It gives me blank result. I putted screenshots of my code and result of that code above. Please analyse these codes and help me, how I can solve it. By the way my php version is 5.3. I can upgrade or downgrade it if it is important. Thanks.
index.php
<?php include('class_library.php'); ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OOP ilk dersim)</title>
</head>
<body>
<?php
$phpders = new adam();
$padisah = new adam();
//----------
$phpders -> set_ad('NurlanXp 1');
$padisah -> set_ad('NurlanXp 2');
//------------
echo "PhpDersden gelen: ".$phpders -> get_ad;
echo "<br>Padisahdan gelen: ".$padisah -> get_ad;
?>
</body>
</html>
class_library.php
<?php
class adam{
var $ad;
function set_ad($yeni_ad){
$this -> ad = $yeni_ad;
}
function get_ad(){
return $this -> ad;
}
}
?>
index.php, class_library.php and the result of the code. Screenshots.
All documents in the same folder.
You seems using $padisah -> get_ad but your adam class doesn't have any getter metod so you have to use like
$padisah -> get_ad();
You can find working example on https://eval.in/591811
In Turkish: get_ad kısmının sonunda parantez açıp, kapatırsan sorun çözülür. Adam class'ının içerisinde getter metodu yok. Yukarıda verdiğim linkte sonundaki parantezle sorunun çözüldüğünü görebilirsin.
this is Your class:
<?php
class adam {
private $ad;
public function get_ad() {
return $this->ad;
}
public function set_ad($ad) {
$this->ad = $ad;
return $this;
}
}
and inside of code:
$phpders = new adam();
$padishah = new adam();
$phpders->set_ad('NurlanXP 1');
$padishah->set_ad('NurlanXP 2');
and usage of get_ad:
echo 'phpdersden gelen: '.$phpders->get_ad().'<br/>';
echo 'padishahdan gelen: '.$padishah->get_ad().'<br/>';
(After solving the issue mentioned by "num8er" - calling method with () ...)
Try to give an absolute include path
<?php include('/complete/path/to/class_library.php'); ?>
or set an appropriate include path set_include_path() before. You can use $_SERVER['DOCUMENT_ROOT'] as a base to build a path.

PHP Memory Shortage? Or?

I've got a web server running IIS7 and I just updated to PHP 5.3. I have two sites that seem to run fine, and they both use some small degree of PHP. The revision I am currently testing on this server, presumably uses much... much more.
The problem I am encountering is that on my testing server ( a local XAMPP installation ), my page loads fine. When I push this to my server and hit the page in my browser, I get the following:
Id ) return true; } return false; } public static function PrintSelector($SelectionArray) { if( !isset($SelectionArray)) { Page::WriteLine("
No selections are available.
"); } else { $FoundViewer = false; foreach($SelectionArray as $Selection) { if( $Selection->IsViewing()) { $ViewerSelection = $Selection; $FoundViewer = true; } } if( $FoundViewer ) { Page::WriteLine("Show / Hide " . get_class($Selection) . " Selections"); $ViewerSelection->PrintOverview(); Page::WriteLine("
"); } Page::WriteLine("\n"); foreach($SelectionArray as $Selection) if( $Selection->IsSelectable() && !$Selection->IsViewing()) $Selection->PrintSelection(); Page::WriteLine("
\n"); if( $FoundViewer ) Page::WriteLine("
"); } } } ?>
Which is just a bit of the underlying code for my new site.
Upon further investigation, I run down to one of my other sites and get this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>AGP Credential Manager</title>
<link rel="stylesheet" href="styles.css" type="text/css" />
<script type="text/javascript">
function submitPageForm()
{
document.forms["pageForm"].submit();
}
function submitForm(formName)
{
document.forms[formName].submit();
}
</script>
<script language="javascript">
function toggleDiv(divid){
if(document.getElementById(divid).style.display == 'none'){
document.getElementById(divid).style.display = 'block';
}else{
document.getElementById(divid).style.display = 'none';
}
}
</script></head>
<body>
<div id="wrap">
<div class="header">
<!-- TITLE -->
<h1>AGP Credential Manager</h1>
<!-- END TITLE -->
</div>
<div id="nav">
<ul>
<!-- MENU -->
In the source code. And as I'm sure you can presume, not much for my front-end. It seems as if the PHP starts executing, but fails some couple hundred lines in... for no apparent reason.
Curious if anyone has seen this before and happens to know the fix? Would be great. Thanks.
IIS and Apache are two different beasts. For you own sanity, strive to keep your development environment close to your deployment environment.
I suspect the issue may be that your PHP script uses short tags <? but the PHP configuration is such that it does not accept short tags and wants full tags <?php.
You can either change php.ini and set short_open_tag to 1 or modify the scripts to use the full open tag. I would recommend using the full open tag as the short tags have problems with XML files with PHP extensions.
You will also want to check for short echo's, <?= and replace those with <?php echo.
Some regex you may try:
/<?([^p])/<?php$1/g
/<?= /<?php echo /g

Arguments to PHP template functions

This is more of a style question. I have a template file header.php in which I define a PrintHeader() function.
Callers of this function can specify, via global variables, the title of the page and any Javascript scripts to include when printing the header (because surely not every page will have the same title or want to include the same scripts). I chose to use global variables rather than function arguments because the latter would require the interface to change when adding new arguments.
Is this considered "good" style, and is there a "better" way to do what I'm trying to do?
header.php (simplified)
<?php
function PrintHeader()
{
global $pageTitle, $scripts; // Set by the caller of this function
echo <<<HEADER
<html>
<head>
<title>$pageTitle</title>
HEADER;
if( !empty($scripts) )
{
foreach($scripts as $script)
{
echo " <script type=\"text/javascript\" src=\"$script.js\"></script>\n";
}
}
echo " </head>\n";
}
?>
index.php (simplified)
<?php
$pageTitle = 'Welcome';
$scripts = array('script1', 'script2');
require('header.php');
PrintHeader();
// Print the rest of the page
?>
is there a "better" way to do what I'm trying to do?
sure.
I see no point in defining and calling a function at all. as well as in using heredoc.
header.php (dramatically simplified):
<html>
<head>
<title><?=$pageTitle?></title>
<? if( !empty($scripts) ): ?>
<? foreach($scripts as $script): ?>
<script type="text/javascript" src="<?=$script?>.js"></script>
<? endforeach ?>
<? endif ?>
</head>
index.php:
<?php
$pageTitle = 'Welcome';
$scripts = array('script1', 'script2');
require('header.php');
?>
but still it's not the best way, as it seems you're not using a template where it most valuable - to output page contents itself.
So, I'd make it in three parts:
links.php (simplified):
<?
//include our settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA = getdata("SELECT * FROM links");
$pagetitle = "Links to friend sites";
//etc
//and then call a template:
$tpl = "links.tpl.php";
include "main.tpl.php";
?>
where main.tpl.php is your main site template, including common parts, like header, footer, menu etc:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<? include $tpl ?>
</div>
</body>
</html>
and finally links.tpl.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<? foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<? endforeach ?>
<ul>
notice native HTML syntax, which is highlighted, readable and centralized in one place instead of being split between numerous functions and files
The point is in having separate template for the every PHP page as well as main site template for them all. With such setup you'll get a lot of advantages such as custom error pages, multiple representations of the same data (say, HTML, JSON or XML) by switching only templates without changing the code and many more
The use of global variables is certainly not advisable, and I question the necessity of using heredoc as you have - not that there is anything inherently wrong with heredoc, just that you seem to have rather arbitrarily utilized it in this sample template.
It is not elegant to use a return-value of a function as the output of each template - this defeats one of the purposes of templates which is re-usability.
Take a look at smarty, if not to directly use it (after all, why re-invent the wheel), at least to get an idea of how a rendering class is used to shuttle in the variables that a template needs without resorting to messy globals.
Here's a very quick overview of a way to do templating:
You have a template class that you can assign data to and then render a template.
Template.php:
class Template
{
protected $data = array();
public function assign($key, $value)
{
$this->data[$key] = $value;
}
public function render($file)
{
extract($this->data);
require $file;
}
}
You then have your template, header.php:
<html>
<head>
<title><?php echo $pageTitle; ?></title>
....
In index.php, you then use the template class to assign data and render your template.
$tpl = new Template;
$tpl->assign('pageTitle', 'My page title!');
$tpl->render('header.php');
This is just a simple example to demonstrate the idea, and could give you a good starting point.
While "better" may be in the eye of the beholder, I would suggest having some sort of functions that set the page bits rather than exposing raw variables. For instance, instead of doing $pageTitle = 'Welcome'; you could have set_page_title('Welcome');.
For JavaScript you could have a function that adds to the current script set -- rather than possibly replacing it all -- such as add_javascript($code);. This will allow a developer to set all of these without having to keep track of what the variable name was, and also without needing to global it as well if they want to set it from within a function.
This is an alternative using output buffering.
p/example_page/index.php is one of your pages:
<?php
ob_start() ?>
<h1>Example</h1>
<p>This is the page content</p>
<?php $main = ob_get_clean();
ob_start() ?>
<script defer src="js/example_page/example.js"></script>
<?php $script = ob_get_clean();
$title = 'Example page';
include 'templates/base.php';
templates/base.php is your reusable layout:
<!doctype html>
<html>
<head>
<script defer src="js/main.js"></script>
<?php echo $script ?>
<title><?php echo $title ?> - Example website</title>
</head>
<body>
<header>
<nav aria-label="Main menu"></nav>
</header>
<main><?php
echo $main;
?></main>
<footer>Example footer</footer>
</body>
</html>
Global variables are generally considered bad, and should be avoided if possible.
Rather than listing every variable in the interface, as you said things could change, pass a single array to the PrintHeader() functions:
<?php
function PrintHeader($opts=array()) {
if(!isset($opts['title'])) $opts['title'] = 'Default Title';
echo <<<HEADER
<html>
<head>
<title>$opts['title']</title>
HEADER;
if(!empty($opts['scripts'])) {
foreach($opts['scripts'] as $script) {
echo " <script type=\"text/javascript\" src=\"$script.js\"></script>\n";
}
}
echo " </head>\n";
}
$opts = array('title'=>'Welcome',
'scripts'=>array('script1', 'script2'));
require('header.php');
PrintHeader($opts);
?>
This way, you can add new capabilities in the function without breaking old code.

External JS not working when called from PHP created HTML

I have a PHP script that creates HTML by calling PHP class that I have created. The class creates all the HTML tags one of which is a tag that loads an external JS file. When I try to access the functions from said file nothing happens. Any Ideas?
index page:
function main(){
$content = "Heres some text for you";
$page = new Page($title="MyTitle", $script="external.js", $content=$content)
echo $page->toString();
}
function __autoload($className){
require_once $className . '.class.php';
}
class page:
//class constructor
function __construct($title='untitled', $script='', $content='Default Page class page'){
$this->title = $title;
$this->script = $script;
$this->stylesheet = $stylesheet;
$this->content = $content;
// $this->currentUser = $currentUser;
}
// creates tag structure for HTML pages
function toString(){
return <<<END
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery.js"></script>
// Heres the link to the external JS file
<script type="text/javascript" src="$this->script"></script>
<script type="text/javascript">
test();
</script>
<title>$this->title</title>
<link type="text/css" rel="stylesheet" href="$this->stylesheet" />
</head>
<body>
$this->content
<p id='content'>page content</p>
</body>
</html>
END;
}// end toString function
} // end class Page
?>
External JS:
function test(){
alert("ext. JS test works");
}
You cannot have any spaces before the ending identifier of your heredoc:
END;
should be:
END;
I would also check to make sure that the path to your external.js file is correct. Are any of the other things working? Like the title or css? You also are not passing $stylesheet into your __construct anywhere which produces an error trying to set $this->stylesheet, maybe the whole script is failing to load because of that?
Don't see anything that stands out....
Are you sure the JS file is accessible in the same directory as your script (may want to apply an absolute or relative path if necessary)?
You might also, since you have jquery (assuming it's loaded), try putting the call to test(); in an "on ready" block, like so:
$(document).ready(function () {
test();
});
Other than that, I'd use your given browsers debugging tools to see if you can glean anything useful (like the script not even being loaded as a resource).
Good luck!

Is there any way to return HTML in a PHP function? (without building the return value as a string)

I have a PHP function that I'm using to output a standard block of HTML. It currently looks like this:
<?php function TestBlockHTML ($replStr) { ?>
<html>
<body><h1> <?php echo ($replStr) ?> </h1>
</html>
<?php } ?>
I want to return (rather than echo) the HTML inside the function. Is there any way to do this without building up the HTML (above) in a string?
You can use a heredoc, which supports variable interpolation, making it look fairly neat:
function TestBlockHTML ($replStr) {
return <<<HTML
<html>
<body><h1>{$replStr}</h1>
</body>
</html>
HTML;
}
Pay close attention to the warning in the manual though - the closing line must not contain any whitespace, so can't be indented.
Yes, there is: you can capture the echoed text using ob_start:
<?php function TestBlockHTML($replStr) {
ob_start(); ?>
<html>
<body><h1><?php echo($replStr) ?></h1>
</html>
<?php
return ob_get_clean();
} ?>
This may be a sketchy solution, and I'd appreciate anybody pointing out whether this is a bad idea, since it's not a standard use of functions. I've had some success getting HTML out of a PHP function without building the return value as a string with the following:
function noStrings() {
echo ''?>
<div>[Whatever HTML you want]</div>
<?php;
}
The just 'call' the function:
noStrings();
And it will output:
<div>[Whatever HTML you want]</div>
Using this method, you can also define PHP variables within the function and echo them out inside the HTML.
Create a template file and use a template engine to read/update the file. It will increase your code's maintainability in the future as well as separate display from logic.
An example using Smarty:
Template File
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title>{$title}</title></head>
<body>{$string}</body>
</html>
Code
function TestBlockHTML(){
$smarty = new Smarty();
$smarty->assign('title', 'My Title');
$smarty->assign('string', $replStr);
return $smarty->render('template.tpl');
}
Another way to do is is to use file_get_contents() and have a template HTML page
TEMPLATE PAGE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title>$title</title></head>
<body>$content</body>
</html>
PHP Function
function YOURFUNCTIONNAME($url){
$html_string = file_get_contents($url);
return $html_string;
}
If you don't want to have to rely on a third party tool you can use this technique:
function TestBlockHTML($replStr){
$template =
'<html>
<body>
<h1>$str</h1>
</body>
</html>';
return strtr($template, array( '$str' => $replStr));
}
Or you can just use this:
<?
function TestHtml() {
# PUT HERE YOU PHP CODE
?>
<!-- HTML HERE -->
<? } ?>
to get content from this function , use this :
<?= file_get_contents(TestHtml()); ?>
That's it :)
Template File
<h1>{title}</h1>
<div>{username}</div>
PHP
if (($text = file_get_contents("file.html")) === false) {
$text = "";
}
$text = str_replace("{title}", "Title Here", $text);
$text = str_replace("{username}", "Username Here", $text);
then you can echo $text as string

Categories