PHP variables and XML elements - php

I'm trying to use PHP variables to load certain elements from a XML file, so if index.php?id=1 is loaded it would pull the information from $projects->project[1]. No errors come up in the following code, but nothing gets displayed. Any help is appreciated :)
<?php
$projects = simplexml_load_file('portfolio.xml');
$id = $_GET["id"];
echo $projects->project[$id]->title;
?>

It may be one of two things (or both):
echo doesn't show anything if there is nothing to show.
there has been an error, but your server is not reporting it, try checking logs if there are any. Also check if error reporting is enabled.
That said, try using print_r or var_dump to get the data.

print_r($_GET); die;
to check if u are getting the data in get or not .

error_reporting(~0); // show me everything i do wrong
$projects = simplexml_load_file('portfolio.xml');
var_dump($projects); // make sure $projects actually has something
var_dump($_GET['id']); // are you getting the request data?
$id = (int) $_GET["id"]; // cast to int for good measure
// i'm assuming it's numeric, don't if its not
echo $projects->project[$id]->title; // still not showing anything?
var_dump($projects->project[$id]->title); // dump it for good measure

Related

simple_html_dom not finding my element

I'm trying prices off of Amazon for an exercise.
<?php
require('simple_html_dom.php');
$get = $_GET['id'];
$get_url = 'http://www.amazon.co.uk/s/field-keywords='.$get;
echo $get_url;
// Retrieve the DOM from a given URL
$html = file_get_html($get_url);
foreach($html->find('li[class=newp]') as $e)
echo $e->plaintext . '<br>';
I tried a few differents:
li[class=newp]
.price
ul[class=rsltL]
but it doesn't return anything, what am I doing wrong?
I tried returning the titles as well:
.lrg.bold
Tried Xpath, nothing.
Thanks
Your code is fine. It is very likely that your PHP settings are the culprits.
put
error_reporting(E_ALL);
ini_set('display_errors', '1');
at the begining of your php script and see if it prints out any useful error.
Also, note that simple_html_dom uses the file_get_contents() function internally to grab page content. So, you may want to run file_get_contents($get_url) to see what happens.
If that function does not work then it is definitely your PHP setting. In such case, I recommend starting another thread with that issue in the title.
This might help though:
PHP file_get_contents does not work on localhost

Get and decode json with php

I'm sure this is similar to other questions, but I have tried the solutions, and couldn't get it to work.
I'm trying to get the location of an IP address, decode the json, and print it. I actually plan to put it into a database, but Im not even sure why I cant get anything to print to the screen.
$ip = $_SERVER['REMOTE_ADDR'];
$json = file_get_contents("http://api.hostip.info/get_json.php?ip=".$ip);
$local = json_decode($json,true);
thanks.
A. When you mean I cant get anything to print to the screen. definitely you can get anything because you did not output anything to screen.
error_reporting(E_ALL);
$ip = $_SERVER['REMOTE_ADDR'];
$json = file_get_contents("http://api.hostip.info/get_json.php?ip=".$ip);
$local = json_decode($json,true);
echo $local['city'] ;
print $local['country_name'] ;
var_dump($local);
B. It would also mean that allow_url_include set to Off which would not allow file_get_contents load a information from another domain
Firstly, the code you've provided does not actually print anything, which would explain why you're getting a blank screen. I assume you're doing something like echo $local; later in the program, but if not, that'll be the problem.
Assuming that isn't the issue....
Two possibilities:
file_get_contents() is returning an error.
json_decode() is returning an error.
Firstly, you should add some additional error trapping in your code to determine which one is the problem.
If you have PHP set to not display errors, consider switching them on so you can see any errors that are generated. Or else look at your server log to see the errors.
file_get_contents() may fail if the URL is invalid. It may also fail if your PHP installation is set to not allow URLs via the file handling functions. If this is the case you'll need to change your php.ini settings. If you can't do that, you'll have to load the file via a different method (eg Curl).
json_decode() is only likely to fail if the string it gets is invalid JSON. You should check the output of the URL to confirm that it looks right, and check it something like firebug to ensure it is valid.
Hope that helps.

Pass multiple variables via URL and reading all of them on next page

I have a link that points to a webpage e.g. "land.php".
The link looks like this:
link
this takes me to the page land.php where I can read the first parametere with $id (and it is equal to 1, correctly), but I cannot read the second one. I either tried with $cd or $_GET['cd']. None of them works.
if I tried isset($cd) it says false. Same thing for isset($_GET['cd']).
How can I pass the second parameter too (and read it!)?
EDIT:
some code (so people are happy. I think it's pointless in this case..).
land.php
<?php
if($_GET['cd']==a)
echo "<h2>HI</h2>";
else
echo "<h2>BY</h2>";
?>
if I use $cd instead of $_GET['cd'] it doesn't work anyway..
EDIT2 I don't get any syntax error, it just doesn't behave how expected.
The value is stored in $_GET['cd'].
Try printing out the $_GET array, with print_r($_GET);
print_r($_GET) should output
Array
(
[id] => 1
[cd] => a
)
This should ofcourse be in the land.php page, as the get variables are only available in the requested page.
Your server might be set up to accept semicolon instead of ampersands. Try replacing & with ;
$_GET['cd'] is the correct syntax. Are you actually on the land.php page, ie does your browser's address bar read something like
example.com/land.php?id=1&cd=a
Also, it looks like you have register_globals enabled if you can read $id. This is a very bad idea.
Update
Your code snippet contains syntax errors. I recommend the following, including enabling decent error reporting for development
ini_set('display_errors', 'On');
error_reporting(E_ALL);
if(isset($_GET['cd']) && $_GET['cd'] == 'a') {
echo "<h2>HI</h2>";
} else {
echo "<h2>BY</h2>";
}

PHP Function 'return' not returning

This is a bit of an oddity for me. PHP is my forte, and I can normally figure out any issue I encounter.
I have a custom framework that I have been using for years. I have taken it upon myself to rewrite it, and I'm doing everything essentially the same that I was before. The problem lies in the following construct:
function ModPages_GetPage() {
$page = ModPages_GetPageByName($_GET['page_name']);
if($page != false) {
include(TPL_DIR.'pages/pages.view.php');
} else {
ErrorMessage('Invalid Page', 'The selected page could not be found.');
}
}
function ModPages_GetPageByName($page_name = null) {
$db = new Database;
$query = '
SELECT *
FROM pages
WHERE page_name = "'.CleanStr($page_name).'"
AND page_enabled = "yes"
LIMIT 1
';
$page = $db->GetRow($query);
return $page;
}
This code is being called with 'home' for the value of $_GET['page_name']. The call to ModPages_GetPageByName() is working fine, but the value of $page in ModPages_GetPage() isn't getting set. Matter of fact, any debugging statements thrown in after that call are failing to display anything.
I have display_errors set to on, and error_reporting set to E_ALL. I get a couple notices from my Database class, but that's it.
Running the script at a shell fails to produce any errors. When using strace, I do see the process spits out an 'exit_group(255)'.
This one has me quite baffled. I could sure use some direction on this.
I would think it's your query, shouldn't you just return the page name instead of star? as star (*) would return an array which is probably being passed back as the value? just my guess.
$query = '
SELECT *
FROM pages
WHERE page_name = "'.CleanStr($page_name).'"
AND page_enabled = "yes"
LIMIT 1
';
if you do a print_r on the $page return I would think it should be an array
$page = $db->GetRow($query);
echo "Page:<pre>".print_r($page,true)."</pre><br />\n";
Then maybe return something like this
return $page['page_name_field'];
ok before we get to a solution can we first make sure that before setting the $page variable, first just echo $_GET['page_name'] to see if there is a value being received.
PK
Does your script stop right after your database call, or just doesn't display any output?
If the first is true, then it looks like a fatal error. With E_ALL, it should be displayed, are you sure both display_errors and error_reporting are as you say at that point, and that the GetRow function doesn't alter them in any way? If so, maybe there's something in the Apache error log (PHP errors are sometimes logged there).
If the latter is true I'm thinking about an exception being thrown in a method that is being called, and caught in a higher level function. To check this you can put the database call (ie: the point where things go wrong) inside a try/catch block and see if you reach the catch block.
I would try following:
replace $_GET with $_REQUEST (maybe your form is using POST?)
do a print_r to check contents of your variables.
use mysql_error to view any errors, or print your mysql query in your browser, copy/paste it in phpmyadmin, is it returning anything? error.. data?
something similar happend to me once, my framework was encoded in ANSI and my calling php file was UTF8+BOM... I changed everything to UTF8+BOM and it worked.
try also different browser, I know it might not be a browser problem, but it might be that your script is cached somewhere.
are you using some caching? like eaccelerator?
Are those functions in a class? If so, you will need $page = $this->ModPages_GetPageByName().
Also I would echo out the argument and the sql statment in ModPages_GetPageByName(). This way you can verify that it isn't a SQL error.
I can't say for sure why your code isn't working, but I can make some suggestions that might help in locating the error.
The first thing I notice is you don't check that $db actually contains a valid database. I don't know the details of your Database object but I'm assuming there's some mechanism in there for checking if it's actually connected to the database. You should use that to determine if the database is connected before running queries on it.
$db = new Database ();
if ($db -> isConnected ())
{
$query = 'SELECT * (etc etc etc)';
// ...
}
else
{
// Put some kind of DB connection error notification or throw an exception here
}
Just on a stylistic note, you don't need to store the results of your DB lookup before returning it, unless you're planning on doing some processing on the result before returning it. You can just return the lookup directly. Of course that's just a stylistic choice, but it saves a line or two :)
return ($db->GetRow($query));
After you run your getpage function, I'd strongly recommend var_dump()ing the result. Even if your function returned NULL, you'll still see this in the var_dump. If in doubt, dump it out :). I'd also recommend installing xdebug to make the var_dump output more readable.
$page = ModPages_GetPageByName($_GET['page_name']);
var_dump ($page);
I would also strongly recommending var_dumping your query before you execute just to make absolutely sure that you're running the query you think you're running. Copy and paste the outputted query into sqlyog or phpmyadmin or whatever you use for interactive access to your database and make sure it returns what you think it should return.
Other things to check, is the page you're trying to return actually set page_enabled='yes'? Does the page_enabled column actually store the value as 'yes', or is it a bool or an integer or something else? Is magic quotes enabled or disabled? If they're in one state when you think they're in the other they can cause confusion. Are errors actually being reported to the browser? Add a line at the top of your script that's guaranteed to fail just to make sure, like an attempted foreach on an integer. If you don't see an error, then maybe error reporting isn't configured properly. I know those are obvious questions but I also know how easy it is to overlook the obvious if you're not getting what you expect out of a query.
Are you sure $page is not set, or is it just that your debug instructions don't print anything? Try logging to a file or a database instead; maybe your code triggered output buffering or something like that.
Also, you are calling ModPages_GetPageByName before declaring it. That is usually okay, but might not be in special circumstances (e.g. when the code is wrapped in an if block). Try swapping the two.
Also, check your environment and disable opcode caching and other possible error sources. APC for example can call the old version of the script long after you changed the PHP file.
While some of you have put extra effort into responding to this, nobody has been able to see the full picture, even given the details I have provided. I have been unable to trace the issue back to its source, but have moved on to a different project.

echo not displaying value on page

I have used "echo $query" to see whether it is getting value or not but it is not showing anything on the page. What is the other way to see what value it is getting?
I use Aptana Studio 2.0 PDT but I am not able to set the breakpoints. Quite new in it.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$ulName = $_GET['ControlName'];
$query = $_GET['SqlQuery'];
echo $query;
mysql_connect('localhost:3306','pffsddsf','dfsdfsd');
mysql_select_db('publicdb');
$result=mysql_query("select * from electioncategorymaster");
?>
<ul id="<?php echo $ulName; ?>" name="<?php echo $ulName; ?>">
<?php while($row=mysql_fetch_array($result))
{ ?>
<li><?php echo $row[1]; ?></li>
<?php } ?>
</ul>
You may not be getting the parameters you expect, so start your script with
var_dump($_GET);
to see what your page is actually getting.
While I appreciate you are just learning, accepting parameters which are passed verbatim to the database server and to the client browser is a security no-no.
Take the $ulName variable - I could inject HTML of my choosing there, so why not constrain it to alphanumerics?
if (preg_match('/[^a-z0-9_]/i', $ulName)
die("Invalid ControlName specified");
As for accepting SQL via a parameter, I really wouldn't do that unless you trust the user of your application completely....
?SqlQuery=DROP+DATABASE+publicdb
Scary right? Now how about if you combined both these flaws? I could craft a link which displayed your page, but embedded a form with hidden fields containing that query, along which a big button which said "click me for funny cat videos". Now I just need to send the link out there and wait for someone else to do my evil bidding :)
Try var_dump($query); (will also report/show empty strings)
If your page is completely blank a look into your apache (or webserver of your choice) errorlogs could also be helpful.
try this:
var_dump($query);
exit;
and see what's happens.
This may sound useless, but you should also copy in an 'example' URL that you are using.
PHP is case-sensitive (especially when it comes to array keys) so for one, I would check that the URL that you are calling is using the correct case when it comes to the GET parameters.
When this simple method fails to show any value the question naturally arises: "Is echo working or is there no value to display?"
I did something similar a while ago, but rather than use echo, I used
printf("[%s]", $query);
So I could see the empty [] when there was no value returned by $_GET
first: enable error logging and also log to a logfile.
error_reporting(E_ALL);
ini_set('display_errors','On');
you can try if your error logging is working by doing the following:
error_log("This Error should be displayed!", 0);
see more about error handling and logging on the php.net site: http://www.php.net/manual/en/book.errorfunc.php

Categories