Echo can you hear me? - php

Why is showphp_Smartfm() Not echoing at all.
foreach($response->quizzes as $quiz)
{
echo $quiz->question; // not echoing
echo $quiz->answer; // not echoing
}
Followup Question to Navigating objects and arrays
http://github.com/klanestro/Vortoj
<html>
<body>
<?php
// Created by Talisman 01/2010 ★✩
$vorto = $_GET['vorto']; // Get the Word from Outer Space and Search for it!
if (isset($vorto))
{
echo " Your Direct search was " . $vorto . ' <br></br> ';
} else {
$Help = "No Vorto -> add ?vorto=TheWordYouWant to the end of this website";
echo $Help;
}
// Now Lets Search Alex's Vortaro, It uses jsonp
// ex. http://vortaro.us.to/ajax/epo/eng/petas/?callback=?
/* Future Feature inproved language functinality */
// I used the capital AV to denote variables belonging to Alex's Vortaro
// #Plans for ( traduku.net, tn
// :apertium.org,ap // I think its apertium.org
// :reto-vartaro,rv
// each root word has an xml file, but how to you find this xml file?
// there is a xml link on the bottom of a search result, but I can't figure
// out a way to get to this info.
// :project gutenburg, pg
// :google books, gb
// BUT NEXT UP ЄЭ smart.fm
// it also assumes epo-eng
function getphp_AlexVortaro ($vorto)
{
$AVurl1 = "http://vortaro.us.to/ajax/epo/eng/";
$AVurl2 = "/?callback=";
$AVfinalurl= $AVurl1 . $vorto . $AVurl2;
$AVcontent = file_get_contents($AVfinalurl) ;
// Now we need to trim the () jsonp to json
$AVcontent = substr($AVcontent, 1);
$AVcontent = substr($AVcontent,0,-1);
$AVDecode = json_decode($AVcontent);
return ($AVDecode);
}
function getphp_Smartfm($vorto)
{
$SFurl="http://api.smart.fm/items/matching/";
// $SFurl2=urlencode($vorto); // +".json";
$SFurl3="?language=eo&translation_language=en";
$SFfinalurl = $SFurl . $vorto . ".json" . $SFurl3; // you can change .json to .xml
$SFcontent = file_get_contents($SFfinalurl);
$SFDecode = json_decode($SFcontent);
return ($SFDecode);
}
$AVvorto = getphp_AlexVortaro ($vorto);
$SFvorto = getphp_Smartfm($vorto);
function showphp_AlexVortaro ($AVvorto)
{
$AVvortoshow = $AVvorto->text;
echo $AVvortoshow;
}
showphp_AlexVortaro ($AVvorto);
function showphp_Smartfm($SFvorto)
{
// $objects is the array with all those objects
foreach($SFvorto as $object)
{
echo $object->cue->language; // language
foreach($object->responses as $response)
{
// if there are no quizzes, we skip the part below
// we skip it because $object->quizzes will produce a warning or a notice
// if "quizess" is not a member of the $object
if(!isset($object->quizzes))
{
continue;
}
// quizess
foreach($response->quizzes as $quiz)
{
echo $quiz->question; // question
echo $quiz->answer; // answer
}
}
}
}
showphp_Smartfm($SFvorto);
?>
</body>
</html>

This fixed it
- if(!isset($object->quizzes))
0
+ if(!isset($object->responses))
Go here
http://github.com/klanestro/Vortoj/commit/625fce9ffbd2a4d45d7b8dffddff6986fe521a00#comment_43364

Start doing 'echo-debugging'.
print_r($response);
print_r($response->quizzes);
foreach($response->quizzes as $quiz)
{
echo $quiz->question; // question
echo $quiz->answer; // answer
}
Maybe there are no $response->quizzes
Maybe the question and answer are empty string
Maybe this code is never being reached
Maybe it's outputting inside an HTML tag and you never thought to check View Source
Maybe it's dying way earlier in the script and you don't have error reporting turned on.

Enable all the error reportings:
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
//or directly edit your php.ini !
and try with:
foreach($response->quizzes as $quiz)
{
var_dump($quiz->question); // question
var_dump($quiz->answer); // answer
}
and see what is going on

Related

How can I check if my function print/echo's something?

I am often using echo to debug function code:
public function MyFunc() {
// some code...
echo "OK";
// some code...
}
How can I check that my function print's/echo's something?
(pseudo code):
MyFunc();
if (<when something was printed>){
echo "You forgot to delete echo calls in this function";
}
This should work for you:
Just call your functions, while you have output buffering on and check if the content then is empty, e.g.
ob_start();
//function calls here
MyFunc();
$content = ob_get_contents();
ob_end_clean();
if(!empty($content))
echo "You forgot to delete echos for this function";
You could create a $debug flag and a debuglog() function, which checks for the debug flag and only then echos the message. Then you can toggle your debug messages on and off from one location.
define('DEBUGMODE', true); // somewhere high up in a config
function debuglog($msg){
if( DEBUGMODE ){ echo $msg; }
}
Should you ever want to get rid of your debug echos, you can search for "debuglog(" and delete those lines of code. This way you won't accidentally delete any echo statements that are required in normal execution or miss any debug echo statements that should really have been removed.
It's the bad way checking if something is echoed.
You can set a variable named is_echoed to 1 or you can return the value
public $is_echoed = 0;
//rest
$this->is_echoed = 1;
or
function myFunc()
{
return "OK";
}
if(myFunc() == 'OK')
//rest
You can use var_dump() and die() to debug your code more efficiently.
$test = "debud test";
public function MyFunc($test)
{
// some code...
var_dump($test); die();
// some code...
}
Reference:
http://php.net/manual/en/function.var-dump.php
http://php.net/manual/en/function.die.php
Why do you want to try such an extensive process of seeing if something has been echoed or not?
For debugging you can definitely use echo to see if the particular block is being hit during a particular use-case. But I would suggest you use flags and return the values to the calling function.
function xyz () {
if (something) return some_value;
else return some_other_value;
}
There is no particular need to have variables and use space in storing a 0 or 1 when you can just return a hard-coded literal.
I would suggest to you to use something like log4php [1]
But if not, I use a function like this:
define('DEBUG', true);
function debug($msg){
if(DEBUG){ echo $msg; }
}
Or something like this to see the log in the browser console:
function debug_to_console( $data ) {
if ( is_array( $data ) )
$output = "<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>";
else
$output = "<script>console.log( 'Debug Objects: " . $data . "' );</script>";
echo $output;
}

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

How to fix XML-RPC Client returning fault code in PHP?

It is my first experience with XML-RPC. I am having a problem retrieving the data from the server as it's being returned to client as fault code. Why is this happening? Do I also need to make an XML-RPC Server file or is it already set up here?
$beerClient = new xmlrpc_client('localhost:1234/341/xmlrpc-lab/xmlrpcserver.php','alvin.ist.rit.edu:8100',1234);
Is it because the data does not match the server return type or something else I'm missing?
I made sure I included the xmlrpc libraries to the right path and everything.
The webpage error returns:
An XML-RPC Fault Occured
Fault Code:-1
Fault Desc:java.lang.NoSuchMethodException: BeerHandler.List()
XML-RPC Client:
<?php
require_once('xmlrpc-3.0.0.beta/lib/xmlrpc.inc');
// Initialize $Beers as an empty Array.
// $Beers will hold all the information available for each beer.
// (BeerID, Name, Rating, Comments)
//
// It will be used later to create the HTML output.
$Beers = Array();
// GET A LIST OF THE AVAILABLE BEERS ON THE XML-RPC SERVER
$beerClient = new xmlrpc_client('localhost:1234/341/xmlrpc-lab/xmlrpcserver.php','alvin.ist.rit.edu:8100',1234);
$msg_listBeers = new xmlrpcmsg('beer.List');
$response = $beerClient->send($msg_listBeers);
if($response == false)
{
die('Unable to contact XML-RPC Server');
}
if(!$response->faultCode()) // faults occurred?
{
// convert to a more usable PHP Array
$beerList = xmlrpc_decode($response->value());
foreach($beerList as $beerID => $beerName)
{
// for each available beer listed by the server grab it's
// a) Rating
// b) Comments
//
// and put the data into the $Beer array. This is incredibly
// inefficient since it performs a lot of HTTP calls to grab each
// piece of data. Not recommended for use beyond this example.
$Beers[$beerID]['name'] = $beerName;
// GET THE RATING FOR THE CURRENT BEER
// Build XML-RPC Request for the Beer's Rating
$msg_beerRating = new xmlrpcmsg('beer.Rating',array(new xmlrpcval($beerID, 'int')));
// Send the Message to the server
$response = $beerClient->send($msg_beerRating);
// Negative number If no rating found
$Beers[$beerID]['rating'] = (!$response->faultCode()) ? xmlrpc_decode($response->value()) : -1;
// GET THE COMMENTS FOR THE CURRENT BEER
$msg_beerComments = new xmlrpcmsg('beer.Comments', array(new xmlrpcval($beerID,'int')));
// Send the Message to the server
$response = $beerClient->send($msg_beerComments);
// Fill in the Comments for the Beer
$Beers[$beerID]['comments'] = (!$response->faultCode()) ? xmlrpc_decode($response->value()) : array(); //empty array for not Comments
} // END foreach ($beerList as ...
}
else // XML-RPC returned a fault...
{
echo '<h1>An XML-RPC Fault Occured</h1>';
printf('<b>Fault Code:</b>%s<br/>',$response->faultCode());
printf('<b>Fault Desc:</b>%s<br/>',$response->faultString());
die();
}
// GENERATE THE OUTPUT
$xmlrpc_client->setDebug(1); // turn on debugging, if I/O fault occurred between communication xmlrpc_client and xmlrpc_server
?>
<html>
<head>
<title>Beer List XML-RPC</title>
<meta charset="utf-8">
</head>
<body>
<h1>Beer List</h1>
<ol type="1">
<?php
if(count($Beers))
{
foreach($Beers as $BeerData)
{
printf('<font size="+2" color="#990000"><li> %s</font><br>', $BeerData['beer']);
// Output the beer's rating if it exists
if($BeerData['rating'] != -1)
{
printf('<b>Rating: %s/5.0</b><br>',$BeerData['rating']);
}
// Output the beer's comments if they exist
if(count($BeerData['comments']))
{
echo '<b>Comments:</b><ul>';
foreach($BeerData['comments'] as $Comment)
{
echo "<li> $Comment";
}
echo '</ul>';
}
}
}
else
{
echo '<li> Darn No Beers Found';
}
?>
</ol>
</body>
</html>

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');

Link checker - mail for invalid links [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I got this link checker script and i would like it to give me a mail when a link doesnt work.
I need it to remember that it send me an email about a link so i dont get multiple emails about the same link.
I would appeciate if anyone help me with this since it was too hard for me.
<?
function checklink($links) {
$working = 0;
$link = $links;
$links = preg_replace('/\s+/', '', $links);
if(strstr($links,"rapidshare.com")){
$var = file_get_contents($links);
if(strpos($var,"You want to download the file ")) {
$working = 1;
}
}
elseif (strstr($links,"megaupload.com")) {
$var1 = file_get_contents($links);
if(strpos($var1,"Please enter")) {
$working = 1;
}
}
elseif (strstr($links,"megashares.com")) {
$var2 = file_get_contents($links);
if(strpos($var2,"Filename:")) {
$working = 1;
}
}
elseif (strstr($links,"sendspace.com")) {
$var3 = file_get_contents($links);
if(strpos($var3,"404 Page Not Found")) {
$working = 0;
}
elseif(strpos($var3,"Sorry, the file you requested is not available.")){
$working = 0;
}
else {
$working = 1;
}
}
elseif(strstr($links,"rapidshare.de")) {
$var5 = file_get_contents($links);
if(strpos($var,"You want to download the file ")){
$working = 1;
}
}
elseif (strstr($links,"mediafire.com")) {
$var4 = file_get_contents($links);
if(strpos($var4,"Sharing")) {
$working = 1;
}
}
if ($working == 1) {
echo "". $link . "";
}
else {
echo "The link is not working. Please let me know about it and I'll fix it.";
}
}
?>
I think the best way would be to collect the links and store them in a database table.
Then have a system that goes through the links and checks, if it works it marks it as a working link and if it doesn't then it marks it as a broken link and sends you an email.
You would then have to do a check to see if a link is in a database (since you cant use mysql's varchar as a unique, because it's maxed out at 255 and links can be longer)
If it is in the database, then check what the result of the scan was.
BTW your way of using file_get_contents is a slow process. Since it downloads the entire page. I would recommend using cURL.
I agree with Olafur, but alternatively if you haven't got access to a database you could use the server's file system to save the stats of an URL in a combined config/log file, like a comma-delimited file. Let's say you have a file like this:
rapidshare.com,You want to download the file,0,0
megaupload.com,Please enter,0,0
megashares.com,Filename:,0,0
The four fields are 'URL', 'text to check for', 'last check result' and 'has mail been sent'. The code could be something like this:
$file = "myfile.txt";
// open the file
$fh = fopen($filename, "r");
// read the full file contents into a string
$contents = fread($fh, filesize($file));
// close the file
fclose($fh);
// split the string into an array of lines
$lines = split("\n", $contents);
// split each line into its fields for processing
$i = 0;
foreach ($lines as $line) {
$checkarray[$i] = split(",", $line);
$i++;
}
Now you can cycle through the array and do whatever you want, writing back the information including the 'mail sent' status field as you go along. Use $fields[0] for the URL, $fields[1] for the text to check for, and you can read the last status with $fields[2] en the 'mail sent' status with $fields[3].
foreach($checkarray as $fields) {
// insert code to do your checks here
...
// write back the results
$fh = fopen($filename, "w");
fwrite($fh, $fields[0] . "," . $fields[1] . "," . $working . "," . $mailsent . "\n";
fclose($fh);
}
Hope this helps you on your way.
this is the code you want:
function StatusCheck($url)
{
$urlparts=parse_url($url);
$curl=new CCurl($url);
$headers=$curl->execute();
$headers=$curl->close();
$headers=$curl->getHeader();
$headers=split("\r\n",$headers);
$status=$headers[0];
print_r($headers);
if (strpos($status,"HTTP/1.1 200 OK")===FALSE)
{
echo date("d.m.Y H:i:s").$url,': bad'."\n";
return 0;
}
else
{
echo date("d.m.Y H:i:s").$url,': good'."\n";
return 1;
}
}
it checks the URL (link) provided and prints out the headers + info if the URL is bad (not working) or good (status 200 OK)
PS: set curl options to follow redirection
EDIT: this is the CCurl class, sorry forgot about it:
class CCurl {
var $m_handle;
var $m_header;
var $m_body;
function CCurl($sUrl) {
$this->m_handle = curl_init();
curl_setopt($this->m_handle, CURLOPT_URL, $sUrl);
curl_setopt($this->m_handle, CURLOPT_HEADER, 1);
curl_setopt($this->m_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->m_handle, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($this->m_handle, CURLOPT_USERAGENT, "StatusCheckBot 0.1");
return;
}
function getHeader() {
return $this->m_header;
}
function execute() {
$sResponse = curl_exec($this->m_handle);
$this->m_body = substr($sResponse, strpos($sResponse, "\r\n\r\n") + 4);
$this->m_header = substr($sResponse, 0, -strlen($this->m_body));
return $this->m_body;
}
function close() {
curl_close($this->m_handle);
return;
}
}

Categories