I have scoured the net and watched endless You Tube vids but cant find an answer to this. Most of what I am finding is for more complex issues and I am just a newbie starting out.
I am trying to learn OOP. I took an old PHP example I had lying around and decided to try converting it to oop. All it is is a loop with a counter. Problem is I cant get it to work out at all.
My original view page was this...
<html>
<head><title>1 Loop</title></head>
<body>
<h2>1 Loop for age</h2>
<?php
$age=18;
while ($age <= 20)
{
echo ("You are " . $age . " years old. <br /> You are not old enough to enter. <br /><br />");
$age++;
}
echo ("You are " . $age . " You may enter!");
?>
</body>
</html>
Now I am trying to create a class_lib page and a php page. Here is my class page:
<?php
class person {
public $age;
function __construct($persons_age) {
$this->age = $persons_age;
}
function get_age() {
while ($age <= 20)
{
echo ("You are " . $age . " years old. <br /> You are not old enough to enter. <br /><br />");
$age++;
}
echo ("You are " . $age . " You may enter!");
return $this->age;
echo $this->age;
}
}
?>
And lastly, my php view:
<html>
<head>
<title>1 Loop</title>
<?php include("class_lib.php"); ?>
</head>
<body>
<h2>1 Loop for age</h2>
<?php
$obj = new person(17);
echo $obj->get_age();
?>
</body>
</html>
Can someone give me a few pointers as to where I am going wrong?
In your get_age() function you use $age instead of using $this->age. The latter uses the class variable, instead of a local variable (that does not exist).
Remove the echo $this->age; line which resides after the return-statement of the function. It is never reached and does not seem to have any value, as you already printed the age.
Your get_age() function is wrong, you're trying to access the $age variable like a local variable though it should be accessed like a class variable.
Try this:
function get_age() {
while ($this->age <= 20)
{
echo ("You are " . $this->age . " years old. <br /> You are not old enough to enter. <br /><br />");
$this->age++;
}
echo ("You are " . $this->age . " You may enter!");
return $this->age;
}
Remove the echo function, the last line of it, because this will never get called since you any code after the return call is dismissed.
Also, you're already echoing the content you're returning in your php view.
Related
I really don't know Drupal but have managed to create a simple HTML page that I would like to use the first and last name inputted to run snoopy.class.php to run a script on a web site to retrieve some data. The button should run a function that will submit the URL but I am not getting any results.
Because I don't know how to debug in Drupal I added some echo statements to see how far the code ran it seems to be stopping when it tries to create a new snoopy object. I downloaded the class and put it in what I would think would be an accessible folder, namely public_html/tools it:
-rw-r--r-- 1 agentpitstop apache 37815 Sep 3 21:03 Snoopy.class.php
Below is the code I am using
<form method="post">
<p>Last Name: <input type="text" name="lastname" /><br />
First Name: <input type="text" name="firstname" /></p>
<p><input type="submit" value="Send it!"></p>
</form>
<?php
if($_POST)
{
echo "1st display <br />\n";
$url = "https://pdb-services-beta.nipr.com/pdb-xml-reports/hitlist_xml.cgi?";
$url = $url . "customer_number=beta83agent&pin_number=nipr123&report_type=1";
$lastname = $_POST['lastname'];
$firstname = $_POST['firstname'];
$parms = array("name_last"=>$lastname,"name_first"=>$firstname);
echo "2nd display <br />\n";
$result = curl_download($url,$parms);
$xml=simplexml_load_file("$result.xml");
$nipr_id = $xml->NPN;
echo "url " . $url . "<br />\n";
echo "Agent " . $_POST['firstname'] . " " . $_POST['lastname'] . " Id is:". $nipr_id . "<br />\n";
echo "3rd Result from call " . $result . "<br />\n";
}
?>
<?php
include "Snoopy.class.php";
function curl_download($url,$parms)
{
echo "in call to curldownload ";
$snoopy = new Snoopy();
echo "after setting object";
$snoopy->curl_path = "/usr/bin/curl"; # Or whatever your path to curl is - 'which curl' in terminal will give it to you. Needed because snoopy uses standalone curl to deal with https sites, not php_curl builtin.
echo "after setting path";
$snoopy->httpsmethod = "POST";
echo "after setting post";
$snoopy->submit($url, $parms);
echo "after setting submit";
print $snoopy->results;
echo "results: " . results;
return $snoopy->results;
}
?>
Any help would be appreciated.
If you need custom development on a Drupal site create a custom module and use Drupal's form API.
If you need to perform HTTP request from PHP, use a PHP library/extension, such a php-curl, Guzzle or Drupal's drupal_http_request(). And yes, they all support HTTPS.
This question already has answers here:
Making global var from inside a function in PHP
(3 answers)
Closed 9 years ago.
I have a function in location.php with this code:
$isp = $ipInfo["isp"];
$country = $ipInfo["country"];
$state = $ipInfo["state"];
$town = $ipInfo["town"];
echo "ISP: " . $isp . "<br>\n";
echo "Country: " . $country . "<br>\n";
echo "State: " . $state . "<br>\n";
echo "Town: " . $town . "<br>\n";
I have a file named test.php. If I use this code:
<?php
include('location');
echo "ISP: " . $isp . "<br>\n";
echo "Country: " . $country . "<br>\n";
echo "State: " . $state . "<br>\n";
echo "Town: " . $town . "<br>\n";
?>
inside test.php I get the following output:
ISP: dslb-094-219-040-096.pools.arcor-ip.net
Country: DE - Germany
State: Saarland
Town: Schiffweiler
ISP:
Country:
State:
Town:
The second ISP, country, state and town are in test.php and do not show anything and the first ones are inside location.php. The whole problem is, I can't use a variable created inside the function on the outside or in another php file. How can I use a variable on the outside?
It has to do with global and scope?
Sorry if I am confusing, but it's almost 3:30 am and I am getting nuts
You can use the global keyword to do this
function my_func()
{
global $isp,$country,$state,$town;
//do stuff to variables
}
echo $isp.$country.$state.$town;
Something like that would work. Although a better option would probably be returning the variables in a return statement.
--edit--
Just made a working mockup
p1.php
<?php
function a()
{
global $b,$c,$d;
$b='hi';
$c='bye';
$d='what';
}
a();
?>
p2.php
<?php
include 'p1.php';
echo $b.$c.$d;
?>
There shouldn't really be any reason something like this wouldn't work for you.
You shouldn't try to lift variables over include statements, it makes for messy code. include isn't like a function call.
Typically the kind of files you want to include are files that have just function or class definitions in them. And then you'll probably want to use include_once.
include can be useful for things like templates, where you might actually end up repeating the same file but for just PHP code: no.
The proper way would look like this:
// location.php
function printIPInfo($ipInfo) { // THIS is a function
$isp = $ipInfo["isp"];
$country = $ipInfo["country"];
$state = $ipInfo["state"];
$town = $ipInfo["town"];
echo "ISP: " . $isp . "<br>\n";
echo "Country: " . $country . "<br>\n";
echo "State: " . $state . "<br>\n";
echo "Town: " . $town . "<br>\n";
}
// test.php
include_once('location.php');
printIPInfo($ipInfo);
I am not entirely sure why you are having problems
I often have a "Dim.php" file to define constant strings and then include using:
include("location.php");
Using the .php extension may fix your problem?
For example if I had the script:
<?php
$page = "My Page";
echo "<title>" . $page . "</title>";
require_once('header.php');
require_once('content.php');
require_once('footer.php');
?>
Is there something I can add to the bottom of that page to show the entire pre-compiled php?
I want to literally echo the php code, and not compile it.
So in my browser I would see the following in code form...
// stuff from main php
$page = "My Page";
echo "<title>" . $page . "</title>";
// stuff from require_once('header.php');
$hello = "Welcome to my site!";
$name = "Bob";
echo "<div>" . $hello . " " . $name . "</div>";
// stuff from require_once('content.php');
echo "<div>Some kool content!!!!!</div>";
// stuff from require_once('footer.php');
$footerbox = "<div>Footer</div>";
echo $footerbox;
Is this possible?
There's no way to do it native to PHP, but you could try to hack it if you just wanted something extremely simplistic and non-robust:
<?php
$php = file_get_contents($_GET['file']);
$php = preg_replace_callback('#^\s*(?:require|include)(?:_once)?\((["\'])(?P<file>[^\\1]+)\\1\);\s*$#m', function($matches) {
$contents = file_get_contents($matches['file']);
return preg_replace('#<\?php(.+?)(?:\?>)?#s', '\\1', $contents);
}, $php);
echo '<pre>', htmlentities($php), '</pre>';
Notes:
Warning: Allowing arbitrary file parsing like I've done with the fist line is a security hole. Do your own authentication, path restricting, etc.
This is not recursive (though it wouldn't take much more work to make it so), so it won't handle included files within other included files and so on.
The regex matching is not robust, and very simplistic.
The included files are assumed to be statically named, within strings. Things like include($foo); or include(__DIR__ . '/foo.php'); will not work.
Disclaimer: Essentially, to do this right, you need to actually parse the PHP code. I only offer the above because it was an interesting problem and I was bored.
echo '$page = "My Page";';
echo 'echo "<title>" . $page . "</title>";';
echo file_get_contents('header.php');
echo file_get_contents('content.php');
echo file_get_contents('footer.php');
For clarity I'd put the title generation in it's own file, then just use a series of echo file_get_contents()...
echo file_get_contents('title.php');
echo file_get_contents('header.php');
echo file_get_contents('content.php');
echo file_get_contents('footer.php');
I am trying to pass array using form post method :
submit.php
<form method="post" action="makepub.php">
<?php
.... Loop
....
echo '</td><td align="center">';
echo '<input type="checkbox" name="file_list[]" value="'.$pr.'">' ;
echo '</td><tr/>';
....
.... Loop end
?>
makepub.php :
if (isset($_POST['submit1'])) {
$file_list = $_POST["file_list"];
$how_many = count($file_list);
echo '<b>Total No of Public files chosen : </b>'.$how_many.'<br><br>';
if ($how_many>0) {
echo '<b>You changed following files to public : </b><br>';
}
for ($i=0; $i<$how_many; $i++) {
echo ($i+1) . '- ' . $file_list[$i] . '<br>';
// Some code here
}
echo "<br><br>";
}
Ok these two files works perfectly on my localhost with XAMPP.
php version 5.3
but on my server array is not getting passed.
I checked by replacing the array with single variable. Even so nothing is passed to file makepub.php
Is there anything i am missing with post here ???
Any suggestion is appreciated.
Thanks.
Your code should work as it appears, however you should make sure your submit button has a name of submit1 and then you close the form with a closing tag.
I'm sure there is a simple answer to this, but I have been fumbling with everything for almost a week now and surrender. I am trying to build a shopping cart app and every coding solution I build will work when I include the code on the same page, but when I try to use an external page to run the function it does not seem to return the data. I have tried various monitoring techniques to determine what it is happening.
Here is the code for the main page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Cart Connection</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<p>Will this display?</p>
<p><a href='<?php echo "showCart.php?PHPSESSID=" . session_id() ?>'>View Cart</a></p>
<?php
$Database = "L3TtL2B5DdY";
$Table = "tblProds";
if (isset($_SESSION['curCart']))
$Cart = unserialize($_SESSION['curCart']);
else
{
if (class_exists("shoppingCart"))
{
$Cart = new shoppingCart();
$Cart->setDatabase($Database);
echo ("<p>If statement ran successfully</p>");
}
else
exit("<p>The shoppingCart class is not available!");
}
$Cart->setTable($Table);
$Cart->getProductList();
$_SESSION['curCart'] = serialize($Cart);
?>
<p><a href='<?php echo "showCart.php?PHPSESSID=" . session_id() ?>'>View Cart</a></p>
</body>
</html>
Here is the relevant code on the "shoppingCart.php" page:
<?php
class shoppingCart
{
private $dbConn = "";
private $dbName = "";
private $tableName = "";
private $orders = array();
private $orderTable = array();
function _construct()
{
$this->dbConn = #new mysqli("localhost", "root", "");
if (mysqli_connect_errno())
die("<p>Unable to connect to the database server.</p>" . "<p>Error Code " .
mysqli_connect_errno() . ": " . mysqli_connect_error() . "</p>");
}
public function setDatabase($Database)
{
$this->dbName = $Database;
#$this->dbConn->select_db($this->dbName)
Or die("<p>Unable to select the database.</p>" . "<p>Error code " . mysqli_errno($this->dbConn) .
": " . mysqli_error($this->dbConn) . "</p>");
}
public function setTable($Table)
{
$this->tableName = $Table;
}
public function getProductList()
{
$sqlString = "SELECT prodID, prodName, prodPrice FROM $this->tableName";
#$qryResult = $this->dbConn->query($sqlString)
Or die("<p>Unable to perform the query.</p>" . "<p>Error code " . mysqli_errno($this->dbConn) .
": " . mysqli_error($this->dbConn) . "</p>");
echo "<table width='100%' border='1'>";
echo "<tr><th>Product ID</th><th>Product Name</th><th>Product Price</th><th>Select Item</th></tr>";
$row = $qryResult->fetch_row();
do
{
echo "<tr><td>{$row[0]}</td>";
echo "<td>{$row[1]}</td>";
echo "<td>{$row[2]}</td>";
echo "<td><a href='showCart.php?PHPSESSID=" . session_id() . "&operation=addItem&productID=" . $row[0] .
"'>Add</a></td></tr>";
$row = $qryResult->fetch_row();
} while ($row);
echo "</table>";
}
......
?>
When I try to load the main page it will display the two lines and that is all. I debugged all the errors when I first created the code and thought it would work. When I wrote the original version of this page I put the "connection" code on the same page and the table displayed fine, so I don't know what else it could be.
I installed WAMP on my Windows XP box and it seems to work fine. I haven't touched the configuration files for any of the programs and all my other test code seems to work fine. It is just when I try to contact an external file.
Any help would be greatly appreciated as I think my brain is turning to mush.
Thanks
You probably need to include the ShoppingCart.php file in your main page, so it has the definition of the ShoppingCart class. Try putting at the top of your main page:
<?php require('ShoppingCart.php'); ?>
What I think might be happening is that the cart object is getting unserialised from the Session, but there is no class definition, so it becomes an instance of an incomplete class. When you then call a method on it you are getting a fatal error. What probably doesn't help is that you may not be displaying errors, so the script will just end. You could also try putting at the top of the main page:
<?php ini_set('display_errors', true); ?>
This should make PHP errors get shown.
Edit
It might be worth pointing out that you can't store a database connection in the session. You need to connect to the server / select the database etc. on every request. I don't think your script is currently doing that.
Also, you can store objects in the session without worrying about the serialisation yourself, here is a quick example:
<?php
//include class definition before starting session.
require('ShoppingCart.php');
session_start();
if (!isset($session['cart'])) {
$session['cart'] = new ShoppingCart();
}
$cart = $session['cart'];
//do stuff to cart
$cart->doSomething();
//changes are now saved back to the session when the script is terminated, without you having to do anything.
You need to
include_once("ShoppingCart.php");
Read up on the different ways to include files
http://www.w3schools.com/PHP/php_includes.asp