loadHTMLFile loads, but is empty? PHP - php

so I tried to get a fix for this earlier but I think we were all going in the wrong direction. I'm trying to check two servers to make sure that at least one of them are active to make a call to. The service provides me with a page for each that simply has "OK" under a div with id="server_status". When I try to loadHTMLFile into a variable, it returns true, but I can never pull the element I need from it. After doing some output testing with saveHTML(), it appears that the variable holding the DOMDocument is empty. Here's my code:
servers = array('tpeweb.paybox.com', // primary URL
'tpeweb1.paybox.com'); // backup URL
foreach($servers as $server){
$doc = new DOMDocument();
$doc->validateOnParse = true;
$doc->loadHTMLFile('https://'.$server.'/load.html');
$server_status = "";
$docText = $doc->saveHTML();
if($doc) {
echo "HTML should output here: ";
echo $docText;
}
if(!$doc) {
echo "HTML file not loaded";
}
$element = $doc->getElementById('server_status');
if($element){
$server_status = $element->textContent;
}
if($server_status == "OK"){
// Server is up and services are available
return array(true, 'https://'.$server.'/cgi/MYchoix_pagepaiement.cgi');
}
}
return array(false, 'e404.html');
All I get as output is "HTML should output here: " twice, and then it returns the array at the bottom. This is the code that they provided:
$servers = array('tpeweb.paybox.com', // primary URL
'tpeweb1.paybox.com'); // backup URL
$serverOK = "";
foreach($servers as $server){
$doc = new DOMDocument();
$doc->loadHTMLFile('https://'.$server.'/load.html');
$server_status = "";
$element = $doc->getElementById('server_status');
if($element){
$server_status = $element->textContent;
}
if($server_status == "OK"){
// Server is up and services are available
$serverOK = $server;
break;
}
// else : Server is up but services are not available .
}
if(!$serverOK){
die("Error : no server found");
}
echo 'Connecting to https://'.$server.'/cgi/MYchoix_pagepaiement.cgi';
This also seems to be having the same problem. Could it be something with my PHP configuration? I'm on version 5.3.6.
Thanks,
Adrian
EDIT:
I tried it by inputting the HTML as a string instead of calling it to the server and it worked fine. However, calling the HTML into a string to use in the PHP function results in the same issue. Fixes??

Related

PHP getElementById not working

So I'm trying to write a short function using PHP to check whether a server (or the back up) is available. The service provides two servers to use, and a page within the server that simply has "OK" in an element with id "server_status". I basically took their code that they provided and adjusted it so that it provides the kind of output I need. I want to get an array of true or false (depending on whether one of the sites is available), and the correct page if it is. Right now the output every time is (false, "e404.html"), which is what I set it up to output if no conditions are met. Here is my code:
function checkURL() {
$servers = array('tpeweb.paybox.com', // primary URL
'tpeweb1.paybox.com'); // backup URL
foreach($servers as $server){
$doc = new DOMDocument();
$doc->loadHTMLFile('https://'.$server.'/load.html');
$server_status = "";
$element = $doc->getElementById('server_status');
if($element){
$server_status = $element->textContent;
}
if($server_status == "OK"){
// Server is up and services are available
return array(true, 'https://'.$server.'/cgi/MYchoix_pagepaiement.cgi');
}
}
return array(false, 'e404.html');
}
Doing some output testing, it appears that I'm loading the document into $doc, but it doesn't fill $element. I'm new to PHP so I'm not quite sure what is wrong.
EDIT:
This is the original code that the service provided to make this check, I adjusted it because I needed to be able to actually output the link to use:
<?php
$servers = array('urlserver.paybox.com', // primary URL
'urlserver1.paybox.com'); // backup URL
$serverOK = "";
foreach($servers as $server){
$doc = new DOMDocument();
$doc->loadHTMLFile('https://'.$server.'/load.html');
$server_status = "";
$element = $doc->getElementById('server_status');
if($element){
$server_status = $element->textContent;
}
if($server_status == "OK"){
// Server is up and services are available
$serverOK = $server;
break;
}
// else : Server is up but services are not available .
}
if(!$serverOK){
die("Error : no server found");
}
?>
//echo 'Connecting to https://'.$server.'/cgi/MYchoix_pagepaiement.cgi';
Thanks,
Adrian
Does your html file have a doctype declared?
from http://php.net/manual/en/domdocument.getelementbyid.php
For this function to work, you will need either to set some ID attributes with DOMElement::setIdAttribute or a DTD which defines an attribute to be of type ID.
It should be sufficient to include <!DOCTYPE html> at the very top of your html files, and set
$doc->validateOnParse = true; before calling the getElementByID function.

Converting JSON to UTF-8 issues in PHP

So I have this program that allows a user to enter information into a form and upon submission turns that information into a JSON file. When a user goes to a different part of the program, the programs retrieves the JSON file and builds a questionnaire out of it.
The building of the JSON file works fine but whenever I try to retrieve the file I'm getting an error that the JSON is returning as ASCII and as NULL. I've done my homework and saw that this usually happens when their is an encoding conflict(even though ASCII is a subset of UTF-8...).
So I made sure that when creating the file I'm using using mb_convert_encoding($x, 'UTF-8', 'auto');
to ensure that the JSON is properly being encoded as UTF-8.
I was also using mb_convert_encoding when retrieving the JSON, but saw that double encoding can cause issues so when I removed that piece it no longer echoed out what the encoding was(using mb_detect_encoding) but it is still NULL.
I even went so far as to pull down the JSON file, save it as UTF-8 and re-upload it.
Any and all help on this is much appreciated it. I've banged my head for two days over this. This is built in Code Ignitor, if that makes a difference
Here is the code to create the JSON file:
$thisClient = $this->input->cookie('client');
$date = "%m-%Y";
$date = mdate($date);
$clientDir = *********PATH TO CREATE THE DIRECTORIES IN;
$dialogDir = $clientDir."/".$date;
$d_file_name = $thisClient.'-'.$date;
//check to see if client directory exists, if it doesn't then it creates it
if(!is_dir($clientDir)){
mkdir($clientDir, 0755, TRUE);
echo "Client Directory Created!<br>";
} else{
echo "No Client Directory Created!<br>";
}
//check to see if client directory exists, if it doesn't then it creates it
if(!is_dir($dialogDir)){
mkdir($dialogDir, 0755, TRUE);
echo "DIALOG Directory Created!<br>";
} else{
echo "No DIALOG Directory Created!<br>";
}
$custDialog = array();
if(isset($_POST['cust-dialog-title'])){
function encodeMe($x){
//this ensure proper encoding
return mb_convert_encoding($x, 'UTF-8', 'auto');
}
$customDialog = array();
for($i = 0; $i < count($_POST['cust-dialog-title']); $i++){
$customDialog[$i]["title"] = encodeMe($_POST['cust-dialog-title'][$i]);
$customDialog[$i]["intro"] = encodeMe($_POST['cust-dialog-intro'][$i]);
for($ii = 0; $ii < count($_POST['cust-dialog-quest-'.$i]); $ii++){
$customDialog[$i]["questions"]["q".$ii] = encodeMe($_POST['cust-dialog-quest-'.$i][$ii]);
if($_POST["cust-dialog-pos-".$i."-".$ii] == "TRUE"){
//if the question is a true positive
$customDialog[$i]["questions"]["agree"] = -5;
$customDialog[$i]["questions"]["disagree"] = 5;
} else{
//if the question is a false positive
$customDialog[$i]["questions"]["agree"] = 5;
$customDialog[$i]["questions"]["disagree"] = -5;
}
}
$jsonDIALOG = json_encode($customDialog);
$jsonDIALOG = str_replace("[", " ", str_replace("]", " ", $jsonDIALOG));
if ( ! write_file($dialogDir."/".$d_file_name.".json", $jsonDIALOG )) {
echo 'Unable to write the file';
} else {
echo 'File written!';
}
//save Custom DIALOG info in database
***********DATABASE INFO**************
}
}
Here is the code to retrieve the JSON object:
if($row["custom"] !== null){ //If the Dialog is a Custom Dialog
$path = str_replace(*****removes an unnecessary portion from the path string**);
$thisDialog = file_get_contents(****PATH TO JSON FILES*****);
//THE FOLLOWING helps debug issues with the JSON -- displays order number and dialog being called -- uncomment to use
//echo $i.' is '.$curDialog[$i]. '<br>';
//$thisDialog = substr($thisDialog,1);
//echo $thisDialog;
//THIS IS THE CODE FOR DEBUGGING ENCODING ISSUES
//$thisDialog = mb_convert_encoding($thisDialog, 'UTF-8', 'ASCII');
//echo mb_detect_encoding($thisDialog);
$jsonDialog = json_decode($thisDialog, true);
echo var_dump($jsonDialog);
if($jsonDialog){
$allDialogs = $jsonDialog;
} else {
echo "Error: Invalid Dialog. Call Order# 0<br>" ;
}
return $allDialogs;
}
I've included some debugging things that I've tried and commented out. Thanks!!
You should probably add JSON_UNESCAPED_UNICODE as an option to json_encode. Keep in mind that this constant is available since PHP 5.4.0

Add http or https for user input validation

$xml = $_GET['url']
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);
..
..
if the user put without http or https my script will be broken, is concatenation a good way to validation in this case?
The simplest way of doing this is checking for the presence of http:// or https:// at the beginning of the string.
if (preg_match('/^http(s)?:\/\//', $xml, $matches) === 1) {
if ($matches[1] === 's') {
// it's https
} else {
// it's http
}
} else {
// there is neither http nor https at the beginning
}
You are using a get method. Or this is done by AJAX, or the user appends a url in the querystring You are not posting a form?
Concatenation isn't going to cut it, when the url is faulty. You need to check for this.
You can put an input with placeholder on the page, to "force" the user to use http://. This should be the way to go in HTML5.
<input type="text" pattern="^(https?:\/\/)([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$" placeholder="http://" title="URLs need to be proceeded by http:// or https://" >
This should check and forgive some errors. If an url isn't up to spec this will return an error, as it should. The user should revise his url.
$xml = $_GET['url']
$xmlDoc = new DOMDocument();
if (!preg_match(/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/, $xml ) )
{
echo 'This url is not valid.';
exit;
}
else if (!preg_match(/^http(s)?:\/\/, $xml))
{
//no http present
$orgUrl = $xml;
$xml = "http://".$orgUrl;
//extended to cope with https://
$loaded = loadXML();
if (substr($loaded, 0, 5) == "false")
{
//this attempt failed.
$xml = "https://".$orgUrl;
$loaded = loadXML();
if (substr($loaded, 0, 5) == "false")
{
echo substr($loaded, 6);
exit;
}
}
}
else
{
$loaded = loadXML();
}
function loadXML()
{
try {
return $xmlDoc->load($xml);
}
catch($Ex)
{
return echo 'false Your url could\'t be retrieved. Are you sure you\'ve entered it correctly?';
}
}
You can also use curl to check the url before loading xml:
$ch = curl_init($xml);
// Send request
curl_exec($ch);
// Check for errors and display the error message
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
echo "$error_message :: while loading url";
}
// Close the handle
curl_close($ch);
Important side-note: Using this methods to check if the url is available and than take the appropriate action can take a very long time, since the server response can take a while to return.

Save XML retrieved with rest and php

I can retrieve certain information with a rest command, the data it shows (in the browser) is already an XML. How do I save it to an XML file on the server after retrieving the information.
I have already tried it with the $dom-save command but I seem to do something wrong. Any help would be appreciated. See below for code (I want to save the $response to XML.)
<?php
require_once 'includes/rest_connector.php';
require_once 'includes/session.php';
// check to see if we start a new session or maintain the current one
checksession();
$rest = new RESTConnector();
$url = "/api/tax_codes/0/";
$rest->createRequest($url,"GET", null, $_SESSION['cookies'][0]);
$rest->sendRequest();
$response = $rest->getResponse();
$error = $rest->getException();
// save our session cookies
if ($_SESSION['cookies']==null)
$_SESSION['cookies'] = $rest->getCookies();
// display any error message
if ($error!=null)
echo $error;
// display the response
if ($response!=null)
echo $response;
else
echo "There was no response.";
?>
The RESTConneconnector is a specific class Lightspeed. I solved it by using this:
ibxml_use_internal_errors(true);//load if improperly formatted
file_put_contents("exportProduct.xml", $responseProduct);
So it was very easy in the end :)
I dont know any about RESTConnector class. But I suppose, you can try something like it:
$dom = new DOMDocument('1.0','utf-8');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($response->asXML());
$dom->save($this->fileexport);

Having trouble getting the right idea

well i'm writing a php code to edit tags and data inside those tags but i'm having big trouble getting my head around the thing.
basically i have an xml file similar to this but bigger
<users>
<user1>
<password></password>
</user1>
</users>
and the php code i'm using to try and change the user1 tag is this
function mod_user() {
// Get global Variables
global $access_level;
// Pull the data from the form
$entered_new_username = $_POST['mod_user_new_username'];
$entered_pass = $_POST['mod_user_new_password'];
$entered_confirm_pass = $_POST['mod_user_confirm_new_password'];
$entered_new_roll = $_POST['mod_user_new_roll'];
$entered_new_access_level = $_POST['mod_user_new_access_level'];
// Grab the old username from the last page as well so we know who we are looking for
$current_username = $_POST['mod_user_old_username'];
// !!-------- First thing is first. we need to run checks to make sure that this operation can be completed ----------------!!
// Check to see if the user exist. we just use the normal phaser since we are only reading and it's much easier to make loop through
$xml = simplexml_load_file('../users/users.xml');
// read the xml file find the user to be modified
foreach ($xml->children() as $xml_user_get)
{
$xml_user = ($xml_user_get->getName());
if ($xml_user == $entered_new_username){
// Set array to send data back
//$a = array ("error"=>103, "entered_user"=>$new_user, "entered_roll"=>$new_roll, "entered_access"=>$new_access_level);
// Add to session to be sent back to other page
// $_SESSION['add_error'] = $a;
die("Username Already exist - Pass");
// header('location: ../admin.php?page=usermanage&task=adduser');
}
}
// Check the passwords and make sure they match
if ($entered_pass == $entered_confirm_pass) {
// Encrypt the new password and unset the old password variables so they don't stay in memory un-encrytped
$new_password = hash('sha512', $entered_pass);
unset ($entered_pass, $entered_confirm_pass, $_POST['mod_user_new_password'], $_POST['mod_user_confirm_pass']);
}
else {
die("passwords did not match - Pass");
}
if ($entered_new_access_level != "") {
if ($entered_new_access_level < $access_level){
die("Access level is not sufficiant to grant access - Pass");
}
}
// Now to load up the xml file and commit changes.
$doc = new DOMDocument;
$doc->formatOutput = true;
$doc->perserveWhiteSpace = false;
$doc->load('../users/users.xml');
$old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0);
// For initial debugging - to be deleted
if ($old_user == $current_username)
echo "old username found and matches";
// Check the variables to see if there is something to change in the data.
if ($entered_new_username != "") {
$xml_old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0)->replaceChild($entered_new_username, $old_user);
echo "Username is now: " . $current_username;
}
if ($new_pass != "") {
$current_password = $doc->getElementsByTagName($current_user)->item(0)->getElementsByTagName('password')->item(0)->nodeValue;
//$replace_password = $doc
}
}
when run with just the username entered for change i get this error
Catchable fatal error: Argument 1 passed to DOMNode::replaceChild() must be an instance of DOMNode, string given, called in E:\xampp\htdocs\CGS-Intranet\admin\html\useraction.php on line 252 and defined in E:\xampp\htdocs\CGS-Intranet\admin\html\useraction.php on line 201
could someone explain to me how to do this or show me how they'd do it.. it might make a little sense to me to see how it's done :s
thanks
$entered_new_username is a string so you'll need to wrap it with a DOM object, via something like$doc->createElement()
$xml_old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0)->replaceChild($doc->createElement($entered_new_username), $old_user);
This may not be quite right, but hopefully it points you in the correct direction.
alright got it writing and replacing the node that i want but i have ran into other issues i have to work out (IE: it's replacing the whole tree rather then just changing the node name)
anyway the code i used is
// For initial debugging - to be deleted
if ($old_user == $current_username)
echo "old username found and matches";
// Check the variables to see if there is something to change in the data.
if ($entered_new_username != "") {
try {
$new_node_name = $doc->createElement($entered_new_username);
$old_user->parentNode->replaceChild($new_node_name, $old_user);
}
catch (DOMException $e) {
echo $e;
}
echo "Username is now: " . $current_username;
}
if ($new_pass != "") {
$current_password = $doc->getElementsByTagName($current_user)->item(0)->getElementsByTagName('password')->item(0)->nodeValue;
//$replace_password = $doc
}
$doc->save('../users/users.xml');

Categories