php if statement - php

I am using a twitter class to post updates to my account for this I have removed my twitter credentials so I am aware that XXXXX is wrong. I am able to parse the text from the remote xml file. This xml files text always reads "There are no active codes." So in my if statement i said that if the xml file reads "There are no active codes." i dont want to post anything to my twitter, but if it changes to anything else then i would like to parse that information and post it to my twitter. So today when there was an update to the xml file nothing happened. I know that the twitter portion is correct because I have a similar script that does not use an if statement and it posts fine. Once i introduced the if statement i have run into problem of not being able to post. So what can i do to post to twitter only when the xml file changes from "There are no active codes." to anything else?
// Parse Message
$source = file_get_contents('WEBSITE_URL_GOES_HERE');
$dom = new DOMDocument();
#$dom->loadHTML($source);
$xml = simplexml_import_dom($dom);
$match = $xml->xpath("//code_message");
//Twitter class (Updating status)
require_once 'twitteroauth.php';
//Twitter credentials
define("CONSUMER_KEY", "XXXXXX");
define("CONSUMER_SECRET", "XXXXXX");
define("OAUTH_TOKEN", "XXXXXX-XXXXXX");
define("OAUTH_SECRET", "XXXXXX");
// Verify credentials
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
$content = $connection->get('account/verify_credentials');
//If Statement
if ( $match[0] == "There are no active codes." ) {
/* Do Nothing */;
} else {
$connection->post('statuses/update', array('status' => 'New Code Available - ' . $match[0] ));
return $connection;
}
var_dump of the $match array:
array(1) { [0]=> object(SimpleXMLElement)#3 (1) { [0]=> string(32) "There are no active codes." } }

You should probably use a string comparison function.
like strcmp : http://php.net/manual/en/function.strcmp.php
if (strcmp($match,"There are no active codes.") != 0 )
{
$connection->post('statuses/update', array('status' => 'New Code Available - ' . $match[0] ));
return $connection;
}

Why don't you just add some debugging code and check what's going on? Echo you $match[0] and check what's in there. It's hard to imagine "if" being broken, isn't it? Maybe var_dump($match) just to check what's going on. Then you should probably either fix your condition or fix the retrieval of $match.
Check your array: the [0] element is an object, not a string. You need to get the first element of that object, if you know what I mean.
You are comparing:
Object(SimpleXMLElement)#3 (1) { [0]=> string(32) "There are no active codes." }
to
"There are no active codes."
Which is obviously not the same.
I can't test it from here, but check out the manual of simpelXMLElement: http://php.net/manual/en/class.simplexmlelement.php
You should probably get away with a simple call. Just check out what kind of object you have. A simple example would be something like "$match[0]->childname", but I can't quickly see what the childname is. Check out the manual for some sort of getchild or something, shouldn't be too tricky

Related

Global/SESSION PHP Array/Variable without content

I have a huge problem which I can't seem to fix. I got 2 files. insertDB.php(for writing content into my database) & mail.php(for sending me a mail if something got written into databse). Because I don't want the mail stuff in the same file as the SQL-Statements, I created the mail.php file.
Now I want to pass Variables or an Array from insertDB to mail. It works in every other file I'm using but it's not working here.
<?php
//insertDB.php
Session_Start();
include 'dbconnect.php';
$login = $_SESSION['login'];
$num = $_mysqli->real_escape_string($_POST['num']);
$date = $_mysqli->real_escape_string($_POST['date']);
$user = $_mysqli->real_escape_string($_POST['user']);
$program = $_mysqli->real_escape_string($_POST['program']);
$name = $_mysqli->real_escape_string($_POST['name']);
$path = $_mysqli->real_escape_string($_POST['path']);
$mailData = [$num, $date, $user, $program, $name, $path];
$_SESSION['mailData'] = $mailData;
// var_dump($_SESSION['mailData']); <- outputs array WITH content
$insert = "INSERT INTO Zeichnungen (Num, Date, User, Program, Name, Path, Info, Leer)
VALUES ('$num', '$date', '$user', '$program', '$name', '$path', '', '$login')";
if ($_result = $_mysqli->query($insert)) {
header('Location: mail.php');
}
?>
<?php
//mail.php
Session_Start();
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
include '/opt/composer/vendor/autoload.php';
include 'insertDB.php';
$login = $_SESSION['login'];
var_dump($_SESSION['mailData']);
?>
/* Output I see in Browser from mail.php -> var_dump($_SESSION['mailData']); : */
array(6) { [0]=> string(0) "" [1]=> string(0) "" [2]=> string(0) "" [3]=> string(0) "" [4]=> string(0) "" [5]=> string(0) "" }
What is the problem? Why does it have no content but the 6 keys?
Any help appreciated.
Looking at the code, there is nothing obvious to me that can cause var_dump() to print 6 empty strings. Running the provided code does not reproduce your problem (despite unnecessarily calling start_session() again, but that has no effect other than a warning).
This is difficult to debug this way. Don't use the session for this if this data does not survive through multiple requests. If you don't want to use classes, at least pass the data to functions with one responsibility. Using the session to store these variables is not a good practice. It is unnecessary global state and will eventually make this code even more difficult to follow and debug.
You have several examples in http://php.net/manual/en/functions.user-defined.php. Define the functions in one file and note that you must include that file before being able to use them. Do not mix concerns, ie: your mail function should not set HTTP headers, and your database function should not access the $_SESSION or $_POST variables.
For example, in insertIntoDb.php (less fields for clarity) and using functions:
<?php
// ... (necessary mysqli includes, etc.)
function insertIntoDB(array $formData) {
// we escape the data here, this escaping is DB specific.
$num = $_mysqli->real_escape_string($formData['num']);
$date = $_mysqli->real_escape_string($formData['date']);
$login = $formData['login'];
$insert = "
INSERT INTO SomeTable (Num, Date, Login)
VALUES ('$num', '$date', '$login');
";
// it's better not to have other side effects here
// if everything goes right, we just continue
$result = $_mysqli->query($insert);
if (!$result) {
die("Database error");
}
}
In your mail.php file:
<?php
include 'insertIntoDb.php';
include 'sendEmail.php';
// we read the POST and other values here
// constructing an associative array is an
// option if not using objects.
$formData = [
'num' => $_POST['num'],
'date' => $_POST['date'],
'login' => $_SESSION['login'],
];
// using the functions
insertIntoDb($formData);
sendEmail($formData); // defined in sendEmail.php, not in example.
// this point is reached when everything works,
// no need to control flow...
header('Location: success.php'); // perhaps "thanks" message.
as many have said, the code is clean and should work. The other possible culprit is the following line
header('Location: mail.php');
The php function header() clears all GETs & POSTs when client leaves current page.
Instead make mail.php a function then include mail.php in insertDB.php
NB: try to adopt OOP coding particulary when dealing with PHP

PHP XML converter response

im quite new on XML, i am currently work in PHP and i have a request to other server which normaly and always return the callback with XML
In any case i would not talk about how i get the response, but how to convert the XML reponse.
They are two type of the XML response, we could call it as $response
first :
<BASEELEMENT SCHEMA="RESULT" METHOD="ADD-MBX">
<RETURN_VALUE>4</RETURN_VALUE>
<ERROR_DESCRIPTION>
<![CDATA[Error (7004): Login name already exists. Please use another login name.]]>
</ERROR_DESCRIPTION>
</BASEELEMENT>
and the second one is :
<baseelement schema="TIMEOUT" method="ADD-MBX"></baseelement>
i have searched and i got how to convert the xml reponse to obejct or array, which is
$response = new \SimpleXMLElement($response);
after convert :
object(SimpleXMLElement)#256 (3) {
["#attributes"]=>
array(2) {
["SCHEMA"]=>
string(6) "RESULT"
["METHOD"]=>
string(7) "ADD-MBX"
}
["RETURN_VALUE"]=>
string(1) "4"
["ERROR_DESCRIPTION"]=>
object(SimpleXMLElement)#257 (0) {
}
}
as we can see the ERROR_DESCRIPTION become 0.
So i would like to ask, is there any xml converter else simplexml_load_string() or new \SimpleXMLElement()
i cant use that function because i could not get the ERROR_DESCRIPTION
thank you :)
Loading it as you are with -
$response = new \SimpleXMLElement($response);
You can fetch the value quite simply as...
echo (string)($response->ERROR_DESCRIPTION).PHP_EOL;
If you want the full content (as in an XML version)...
echo $response->ERROR_DESCRIPTION->asXML().PHP_EOL;
Using XPath, you can fetch the values by...
echo (string)$response->xpath("//ERROR_DESCRIPTION")[0].PHP_EOL;
The output you are seeing shows that ERROR_DESCRIPTION is an object of SimpleXMLElement type, not that it isn't loaded.

Does memcache retain information until flush?

The question title basically says it all..
If I perform:
$Cache = new Memcache;
$Cache->connect('HOST');
$Cache->set('Information', 'array(
"Testing" => "Value,
"Anther_Test" => "Another Value"
)');
and leave the information there, would the information be flushed/deleted after an interval?
or will it retain within the server until I call:
$Cache->flush();
What #hakre wrote in a comment plus you should get how to use cache.
Cache is not a date storage, it is a cache. You should never relay on what is there and what is not.
Typically you have a limit of a cache size and when it gets full it purges old values.
Typical usage case:
function get_something() {
$Cache = new Memcache;
$something = $Cache->get('something');
if ($something === false) {
$something = //get from db, prepare or whatever
$Cache->set('something', $something);
}
return $something;
}
TLDR; no

ZendFramework - Why the results of isValid always failing?

My post data is from Captcha adapter is as following:
["ffck"] => array(2) {
["id"] => string(32) "661db3996f5e60e71a60671496ec71a9"
["input"] => string(3) "dys"
}
My code is trying to validate now, but always failing:
Zend_Loader::loadClass('Zend_Captcha_Image');
$captcha = new Zend_Captcha_Image();
$captchaArray = array(
'id' => $post['ffck']['id'], // valid id
'input' => $post['ffck']['input'] // valid input
);
if ($captcha->isValid($captchaArray)) { // FAILs!!!!
echo "working";
} else {
echo "fails";
}
Zend_Debug::dump($post) ; // 100% valid ....
exit;
How to fix it? Or whats causing this to fail?
Check the generated html, you should only have two inputs: name="captcha[id]" and name="captcha[input]", if you have a third one with name="captcha", then you have to remove the viewhelper from the captcha element before rendering.
Ex.:
$form->getElement('captcha')->removeDecorator("viewhelper");
The array you pass to the CAPTCHA object should just contain the two keys, so try:
$captchaArray = $post['ffck']
instead of what you are currently doing.
But the code you've posted is not valid anyway since you never generate the CAPTCHA image. I imagine you've cut down the code sample to keep the question short, so if the above fix doesn't work please edit your example to include how and where the CAPTCHA image is generated.

Zend Soap and MindBody

For those of you who aren't familiar with MindBody ( http://www.mindbodyonline.com ) it is a convenient merchant processing tool for health and wellness centres like the yoga studio I do work for. It can track clients and manage employees and all sorts of great stuff. I have been generating reports using nuSOAP and the MindBody SOAP API v0.4 for a while now. When my client asked me to generate a report that needed the updated MindBody SOAP API v0.5 I decided to drop nuSOAP for PHP5's native SOAP. Then I heard that Zend Soap offers the same speed as the native soap but also has a bunch of other benefits so I wrote the following code.
<?php
require_once 'Zend/Soap/Client.php';
$sourceCredentials = array('SourceName'=>'****', 'Password'=>"****", 'SiteIDs'=>array('****'));
try {
$client = new Zend_Soap_Client('https://api.mindbodyonline.com/0_5/ClientService.asmx?WSDL');
$result = $client->GetClients(array("SourceCredentials"=>$sourceCredentials, "XMLDetail"=>"Basic", "PageSize"=>"10", "CurrentPageIndex"=>"0", "ClientIDs"=>array("100009536")));
echo $client->getLastRequest();
} catch (SoapFault $s) {
die('ERROR: [' . $s->faultcode . '] ' . $s->faultstring);
} catch (Exception $e) {
die('ERROR: ' . $e->getMessage());
}
var_dump($client);
var_dump($result);
?>
I'm not sure what I'm doing wrong. The page just keeps loading and loading but never loads. I'm hoping someone can take a look at the WSDL or the API Docs and tell me what I'm missing. Here's the link to the API Docs http://api.mindbodyonline.com/Doc I am trying to use the client service in this example.
If I comment out the $result = $client->GetClients~ line then the page loads and the var_dump of $client returns this
object(Zend_Soap_Client)#1 (28) { ["_encoding:protected"]=> string(5)
"UTF-8" ["_classmap:protected"]=> NULL
["_faultExceptions:protected"]=> array(0) { }
["_soapVersion:protected"]=> int(2) ["_uri:protected"]=> NULL
["_location:protected"]=> NULL ["_style:protected"]=> NULL
["_use:protected"]=> NULL ["_login:protected"]=> NULL
["_password:protected"]=> NULL ["_proxy_host:protected"]=> NULL
["_proxy_port:protected"]=> NULL ["_proxy_login:protected"]=> NULL
["_proxy_password:protected"]=> NULL ["_local_cert:protected"]=> NULL
["_passphrase:protected"]=> NULL ["_compression:protected"]=> NULL
["_connection_timeout:protected"]=> NULL
["_stream_context:protected"]=> NULL ["_features:protected"]=> NULL
["_cache_wsdl:protected"]=> NULL ["_user_agent:protected"]=> NULL
["_wsdl:protected"]=> string(58)
"https://api.mindbodyonline.com/0_5/ClientService.asmx?WSDL"
["_soapClient:protected"]=> NULL ["_lastMethod:protected"]=> string(0)
"" ["_soapInputHeaders:protected"]=> array(0) { }
["_permanentSoapInputHeaders:protected"]=> array(0) { }
["_soapOutputHeaders:protected"]=> array(0) { } }
I'm not sure what the values should be but all those NULLs look bad to me. I have tried different combinations of nesting the arrays passed to $client->GetClients and I've tried accessing different functions other than GetClients as well..
Okay so for anyone who happens to google this and wants the answer. You have to add a user-agent string to your page headers in order to make it work with the API for some reason. Add this code to the top of your PHP page
ini_set("user_agent", "FOOBAR");
then you need to create a Zend_Soap_Client with soap_version set to SOAP_1_1. Create an array of the parameters you are going to send. Then call the function you want and in this case you pass in a array ( "Reqest"=>$params )
$client = new Zend_Soap_Client('https://api.mindbodyonline.com/0_5/ClientService.asmx?WSDL', array("soap_version"=>SOAP_1_1));
$sourceCredentials = array('SourceName'=>'****', 'Password'=>"****", 'SiteIDs'=>array('****'));
$params = array("SourceCredentials"=>$sourceCredentials, "XMLDetail"=>"Basic", "PageSize"=>"10", "CurrentPageIndex"=>"0", "ClientIDs"=>array("123456789","123456789"));
$result = $client->GetClients(array("Request"=>$params));
EDIT: For more information check out the article I'm writing on how to get started with the MINDBODY API in under 30 minutes

Categories