PHP sending message via TCP/IP - php

Im try to send a Message from PHP Website via TCP/IP to an Arduino.
With following code i'm able to send a message from php website
<?php
$errno = NULL;
$error = NULL;
if (!$handle = #fsockopen("192.168.188.24", "49419", $errno, $error, 10))
{
die("Fehler (".$errno."): ".$error);
}
fwrite($handle, "ON\r\n");
fclose($handle);
?>
The problem is, when calling the website for the first time, the message doesnt get delivered immediatly. Just after some refreshes of the website, the message arrives, but logical so many times like amount of website refreshes.
Already tried to limit the messagelength to 2bytes, but without any success.

Try adding inside a try - catch block.
try {
} catch (Exception $e) {
echo $e->getMessage();
}
To see what exception you may get.

Related

how to stop PHP to catch errors in an array loop?

I am trying to loop through an array of four servers. I am trying to find a user on those servers. I am able to see the program works but PHP throws errors from the servers it cannot find from the array. Could someone help how to avoid those errors?
$ID = '1234';
$server_list = array("example1.com", "example2.com", "example3.com");
function serverQuery($server_array, $ID){
foreach ($server_array as $value) {
$host = $value;
try{
include('info.php');
$response = $client->getUser(array("name" => ID))->return;
//print_r($response);
}catch (Exception $e){
echo "Print the error";
}
}
}
Every time I search the user, it did fine in one of the servers but "Print the Error" is also printed along with it. Please help.
Thanks.

How to end a php functionality if their is no response in some time

I'm using neverbounce api in my project to check the email is valid or not. Usually neverbounce returning 5 result codes as a response result codes.In this, we'll get response for status code 0 to 3 in almost 3-4 seconds. but the last status code for unknown emails took almost 30 seconds to get the result. They are providing a timeout option in the API itself but it is not working. I contacted the support team but no use still the issue exists.
So I need to exit the functionality and return a default value if the response didn't receive from API. I tried by using set_time_limit(5); but it didn't work.Any help is appreciable.
This is the code that we're using
$res = 0;
try {
// Make verification request, specify optional $max_execution_time
$result = \NeverBounce\Single::check($email, // Email to verify
true, // Address info
true, // Credits info
5// Timeout in seconds
);
if (!empty($result->result_integer)) {
$res = $result->result_integer;
} else {
$res = 0;
}
// Call wrapper method here
} catch (\NeverBounce\Errors\AuthException $e) {
// The API credentials used are bad, have you reset them recently?
$res = 0;
} catch (\NeverBounce\Errors\BadReferrerException $e) {
// The script is being used from an unauthorized source, you may need to
// adjust your app's settings to allow it to be used from here
$res = 0;
} catch (\NeverBounce\Errors\ThrottleException $e) {
// Too many requests in a short amount of time, try again shortly or adjust
// your rate limit settings for this application in the dashboard
$res = 0;
} catch (\NeverBounce\Errors\HttpClientException $e) {
// An error occurred processing the request, something may be wrong with
// the Curl PHP extension or your network
$res = 0;
} catch (\NeverBounce\Errors\GeneralException $e) {
// A non recoverable API error occurred check the message for details
$res = 0;
} catch (Exception $e) {
// An error occurred unrelated to the API
$res = 0;
}
return $res;

Magento custom email Not sending when tried programatically in localhost from shell folder (not in local directory) using SMTP

i need to create a custom mailing script in magento in Shell folder. I got the sample script from internet. this script was described as a stand alone script and no template id's are required and this type of script is what I needed and program didn't work for me.Below is the script.
require '../app/Mage.php';
ini_set('display_errors', true);
ini_set('max_execution_time', 3600); // just put a lot of time
ini_set('default_socket_timeout', 3600); // same
set_time_limit(0);
class Mage_Shell_Report
{
public function myfunc()
{
$body = "Hi there, here is some plaintext body content";
$mail = Mage::getModel('core/email');
$mail->setToName('reig');
$mail->setToEmail('rieg.philippe#neuf.fr');
$mail->setBody($body);
$mail->setSubject('The Subject');
$mail->setFromEmail('boutique#infosys.com');
$mail->setFromName("divine");
$mail->setType('text');// You can use 'html' or 'text'
try {
$mail->send();
if($mail->send())
{
$msg = true;
echo "<br>mail sent<br>";
}
else
{
echo "<br>mail not send<br>";
}
Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
}
catch (Exception $e) {
Mage::getSingleton('core/session')->addError('Unable to send.');
$this->_redirect('');
}
echo "<br>end program<br>";
}
}
echo "out-1";
$shell1 = new Mage_Shell_Report();
$shell1->myfunc();
?>
This program shows no error . Though mail function returns success , i am not receiving any mail. i am testing in local using SMTP. Other email's, like order email, customer emails are sent successfully and can be viewed in SMTP mailbox. I browsed through pages and came to know that this issue has something to do with queuing but am not clear about that. Kindly help me out

RabbitMQ with AMQP PHP extension , Queue returning 3 items only

I am new to RabbitMQ and am stuck on this weird issue. This is my consumer code:
<?php
function processMessage($envelope, $queue)
{
echo $envelope->getBody() . "\n";
}
$routing_key = 'newTest.txt';
$exchange_name = 'newTest.msg';
$connection = new AMQPConnection();
if ($connection->connect()) {
echo "Established a connection to the broker\n";
$ch = new AMQPChannel($connection);
$queue = new AMQPQueue($ch);
$queue->declare();
try{
if($queue->bind($exchange_name,$routing_key))
{
$queue->consume("processMessage");
}
else
echo "Could Not Bind";
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
else {
echo "Cannot connect to the broker";
}
?>
I am publishing from the command line with:
rabbitmqadmin publish exchange=newTest.msg routing_key=newTest.txt payload='HELLO';
When the consumer is running if i run the command line publish multiple times the output from the queue stops after 3 items. Any idea whats going on?
Thanks.
You have to acknowledge or reject message in consumer.
function processMessage($envelope, $queue)
{
echo $envelope->getBody() . "\n";
$queue->ack($envelope->getDeliveryTag());
}
Also you can use AMQP_AUTOACK to automatically acknowledge all income messages.
$queue->consume("processMessage", AMQP_AUTOACK);
By default prefetch count on channel is 3, so you receive 3 messages and then broker waits for client to ack or reject messages.
P.S.: alternativly, you can look into my demo sources for consumer and producer example in php.

Handle error when getimagesize can't find a file

when I'm trying to getimagesize($img) and the image doesn't exist, I get an error. I don't want to first check whether the file exists, just handle the error.
I'm not sure how try catch works, but I want to do something like:
try: getimagesize($img) $works = true
catch: $works = flase
Like you said, if used on a non-existing file, getimagesize generates a warning :
This code :
if ($data = getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
will get you a
Warning: getimagesize(not-existing.png) [function.getimagesize]:
failed to open stream: No such file or directory
A solution would be to use the # operator, to mask that error :
if ($data = #getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
As the file doesn't exist, $data will still be false ; but no warning will be displayed.
Another solution would be to check if the file exists, before using getimagesize ; something like this would do :
if (file_exists('not-existing.png') &&
($data = getimagesize('not-existing.png'))
) {
echo "OK";
} else {
echo "NOT OK";
}
If the file doesn't exist, getimagesize is not called -- which means no warning
Still, this solution is not the one you should use for images that are on another server, and accessed via HTTP (if you are in this case), as it'll mean two requests to the remote server.
For local images, that would be quite OK, I suppose ; only problem I see is the notice generated when there is a read error not being masked.
Finally :
I would allow errors to be displayed on your developpement server,
And would not display those on your production server -- see display_errors, about that ;-)
Call me a dirty hacker zombie who will be going to hell, but I usually get around this problem by catching the warning output into an output buffer, and then checking the buffer. Try this:
ob_start();
$data = getimagesize('not-existing.png');
$resize_warning = ob_get_clean();
if(!empty($resize_warning)) {
print "NOT OK";
# We could even print out the warning here, just as PHP would do
print "$resize_warning";
} else {
print "OK"
}
Like I said, not the way to get a cozy place in programmer's heaven, but when it comes to dysfunctional error handling, a man has to do what a man has to do.
I'm sorry that raise such old topic. Recently encountered a similar problem and found this topic instead a solution. For religious reasons I think that '#' is bad decision. And then I found another solution, it looks something like this:
function exception_error_handler( $errno, $errstr, $errfile, $errline ) {
throw new Exception($errstr);
}
set_error_handler("exception_error_handler");
try {
$imageinfo = getimagesize($image_url);
} catch (Exception $e) {
$imageinfo = false;
}
This solution has worked for me.
try {
if (url_exists ($photoUrl) && is_array (getimagesize ($photoUrl)))
{
return $photoUrl;
}
} catch (\Exception $e) { return ''; }
Simple and working solution based on other answers:
$img_url = "not-existing.jpg";
if ( is_file($img_url) && is_array($img_size = getimagesize($img_url)) ) {
print_r($img_size);
echo "OK";
} else {
echo "NOT OK";
}

Categories