One of my projects has intermittent connection problems to gateway.watsonplatform.net. It had been working fine, nothing has changed, but now, 80% of the time, it cannot find hostname in DNS Cache.
I've tried to set CURLOPT_RESOLVE option but it just prepends a line to the output about adding hostname into the cache, but then it's still not found.
I'm trying to run the project locally and I figured out it is network-specific. It works on one access point fine, on the other, it has connection issues.
And another strange hint: curl command in shell works.
There is the output:
Added gateway.watsonplatform.net:80:158.85.132.88 to DNS cache
Hostname was NOT found in DNS cache
Could not resolve host: gateway.watsonplatform.net
UPDATE:
The port should be 443, not 80. After this change, it works. After deleting whole this assignment, it still works. Now, I cannot reproduce the problem.
I had the same problem when I implement one project with IBM Watson inside one Customer. And in this case: You need to release the URL inside your Proxy network.
The reason for cURL and Nodejs calls works is because the server is calling through Firewall, and not passing for your proxy network.
Make sure if the url works when you set the proxy inside your Server: Connect advanced inside your SO (Options internet).
as a little ugly hack to get it working, you could add a hosts file alias, perhaps reinforced with a hourly cronjob to update the real IP - at the cost of the script failing for up to 1 hour every time they actually change IP? (i actually did this a couple of years back when i was facing a similar problem, i don't think i still have the source code though, ill check)
edit: i don't have the original cronjob, but it looked something like this:
<?php
declare(strict_types = 1);
$hosts = '/etc/hosts';
assert ( is_file ( $hosts ) && is_readable ( $hosts ) && is_writable ( $hosts ), 'need access to ' . $hosts );
$host = 'google.com';
$ip = getIP ( $host );
$str = file_get_contents ( $hosts );
$start = strpos ( $str, '#<wtf_cronjob>' );
$end = strpos ( $str, '#</wtf_cronjob>' );
assert ( false !== $start && false !== $end, 'invalid syntax for hosts file!' );
$end += strlen ( '#</wtf_cronjob>' );
$newstr = substr ( $str, 0, $start ) . '#<wtf_cronjob>' . "\n" . $ip . ' ' . $host . ' ' . "\n" . '#</wtf_cronjob>' . substr ( $str, $end );
file_put_contents ( $hosts, $newstr );
function getIP(string $host, string $dns = '8.8.8.8'): string {
exec ( 'host ' . escapeshellarg ( $host ) . ' ' . escapeshellarg ( $dns ) . ' 2>&1', $lines, $ret );
if ($ret !== 0) {
ob_start ();
var_dump ( $lines, $ret );
$debugstr = ob_get_clean ();
throw new \RuntimeException ( 'host failed. debuginfo: ' . $debugstr );
}
foreach ( $lines as $line ) {
if (false === stripos ( $line, 'has address ' )) {
continue;
}
// found it
$ret = trim ( substr ( $line, stripos ( $line, 'has address ' ) + strlen ( 'has address ' ) ) );
if (! filter_var ( $ret, FILTER_VALIDATE_IP )) {
throw new \RuntimeException ( 'the extracted ip address is invalid! (wrong syntax for host?)' );
}
return $ret;
}
throw new \RuntimeException ( 'could not find ip address!' );
}
with the following new lines in the hosts file:
#<wtf_cronjob>
216.58.209.142 google.com
#</wtf_cronjob>
I've tried to assign manually how the domain should be resolved. Since this step, the request is working and after deleting this assignment, it still works.
Related
I am facing a weird network problem trying to resolve for the last 2 days. I can not get to open the port 25003 on php web page. The code does not seem to be a problem, however, its as given below.
$host = 'xx.xx.xx.xx'; // statis public ip address assigned by my isp
$ports = array(80, 25003);
foreach ($ports as $port)
{
$connection = fsockopen($host, $port);
if (is_resource($connection))
{
echo '<h2>' . $host . ':' . $port . ' ' . '(' . getservbyport($port, 'tcp') . ') is open.</h2>' . "\n";
fclose($connection);
}
else
{
echo '<h2>' . $host . ':' . $port . ' is not responding.</h2>' . "\n";
}
}
Port 80 shows open but not port 25003.
The site is hosted on Bluehost shared hosting plan with a static IP too. Cross verified with them more than 3 times the fact that port 25003 is open on both incoming and outgoing connections. Would they be lying, I don't think so.
On client PC settings :
(1) Firewall is disabled for testing purpose.
(2) Port forwarding is done correctly in router. I assume so because
I can easily telnet MY PUBLIC IP with a port 25003 within the same
LAN and from phone using sim card's internet.
(3) I did a port check from https://ping.eu/port-chk/ and it shows open.
(4) Client PC has a serproxy installed for serial to IP & Port.
(5) When I do a port check from above link, serproxy shows following message which seems to be okay on its part.
* server thread launched
* server(1) - thread started
* server(1) - EOF from sock
* server(1) - Exiting
(6) Again, when I telnet from external lan, it shows above message in Client PC's Serproxy which means it is doing its work properly. And it shows correct data from serial port to cmd line while telneting.
The problem is when I fsockopen using above pieces of code, it says CONNECTION REFUSED.
Below is my actual code which should try to connect and read data from serial port but CONNECTION REFUSED.
$fp = fsockopen("tcp://xx.xx.xx.xx", 25003, $errno, $errstr);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
if (!feof($fp)) {
$weight = trim(fgets($fp, 64)," ");
}
}
echo $weight;
fclose($fp);
I think the problem lies either in bluehost shared server or client windows PC or SERPROXY or local network configuration. I am afraid there is any major config change possible other than baud rate, com port etc in the SERPROXY which is set correctly.
I am now totally clueless as to how to resolve the said problem. If somebody could help will be greatly appreciated.
I would share the public IP if somebody wants to check the connectivity.
Like I mentioned - previously when I attempted to connect all attempts failed but both methods below now work so I'd assume the problem is fixed. I'd maybe suggest restarting the webserver and browser(s)
<?php
set_time_limit( 0 );
error_reporting( E_ALL );
$address = 'xxx.xxx.xxx.xxx';
$port = 25003;
/* Method #1 */
$fp = fsockopen( "tcp://{$address}", 25003, $errno, $errstr );
if( !$fp ) echo "$errstr ($errno)<br />\n";
else {
if( !feof( $fp ) ) {
$weight = trim(fgets($fp, 64)," ");
}
}
printf('<h1>Method #1</h1>Weight: %s<br /><br />',$weight);
fclose($fp);
/* Method #2 */
function geterror(){
$obj=new stdClass;
$obj->code=socket_last_error();
$obj->error=socket_strerror( $obj->code );
return $obj;
}
function negotiate( $socket ) {
socket_recv( $socket, $buffer, 1024, 0 );
for( $chr = 0; $chr < strlen( $buffer ); $chr++ ) {
if( $buffer[ $chr ] == chr( 255 ) ) {
$send = ( isset( $send ) ? $send . $buffer[$chr] : $buffer[$chr] );
$chr++;
if( in_array($buffer[$chr], array(chr(251), chr(252))) ) $send .= chr(254);
if( in_array($buffer[$chr], array(chr(253), chr(254))) ) $send .= chr(252);
$chr++;
$send .= $buffer[$chr];
} else {
break;
}
}
if( isset($send)) socket_send($socket, $send, strlen($send), 0);
if( $chr - 1 < strlen($buffer)) return substr($buffer, $chr);
}
$socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP );
try{
if( $socket && is_resource( $socket ) ){
if( !socket_connect( $socket, $address, $port ) ){
$err=geterror();
throw new Exception( sprintf( 'socket_connect: %s', $err->error ), $err->code );
} else {
while( true ){
$e=null;
$w=null;
$r = array( $socket );
$c = socket_select( $r, $w, $e, 5 );
foreach( $r as $read_socket ) {
if( $r = negotiate( $read_socket ) ) {
exit( sprintf( '<h1>Method #2</h1>Reading: %s', print_r( $r, true ) ) );
}
}
}
}
} else {
$err=geterror();
throw new Exception( sprintf( 'Failed to create socket: %s',$err->error ), $err->code );
}
}catch( Exception $e ){
printf( "
<pre>
<h1>Error: %d</h1>\nMessage: %s\nTrace: %s\nLine: %d
</pre>",$e->getCode(),$e->getMessage(),$e->getTraceAsString(),$e->getLine() );
}
socket_close( $socket );
?>
Months ago, I have placed a 301 redirect rule in my .htaccess file to redirect all the www request to a non-www request.
The problem is two days ago, when I tried to access my example.net site using www.example.net I get the following warnings in the page and website is not loaded.
http://i.stack.imgur.com/nXBMF.png
Here are the corresponding lines:
1. Plugin.php Line 647 = if ( strpos( $file, $realdir ) === 0 ){
Full function:
/**
* Gets the basename of a plugin.
*
* This method extracts the name of a plugin from its filename.
*
* #since 1.5.0
*
* #param string $file The filename of plugin.
* #return string The name of a plugin.
*/
function plugin_basename( $file ) {
global $wp_plugin_paths;
foreach ( $wp_plugin_paths as $dir => $realdir ) {
if ( strpos( $file, $realdir ) === 0 ) { /** LINE 646 */
$file = $dir . substr( $file, strlen( $realdir ) );
}
}
$file = wp_normalize_path( $file );
$plugin_dir = wp_normalize_path( WP_PLUGIN_DIR );
$mu_plugin_dir = wp_normalize_path( WPMU_PLUGIN_DIR );
$file = preg_replace('#^' . preg_quote($plugin_dir, '#') . '/|^' . preg_quote($mu_plugin_dir, '#') . '/#','',$file); // get relative path from plugins dir
$file = trim($file, '/');
return $file;
}
2. Pluggable.php Line 1178 = header("Location: $location", true, $status);
Full file: http://pastebin.com/0zMJZxV0
I use WordPress only to write some articles. My PHP knowledge is very basic and limited only to locate errors.
Please help me figure out the problem with this. As I have read from the Codex FAQ, they say that empty strings may be a culprit for the pluggable.php error. But I have no idea how to locate it and I have attached the file for your reference.
Please provide your suggestions to avoid this error in the future. Thanks in advance.
3. EDIT - wp setting file: (the error line - include_once( $plugin ); )
// Load active plugins.
foreach ( wp_get_active_and_valid_plugins() as $plugin ) {
wp_register_plugin_realpath( $plugin );
include_once( $plugin );
}
unset( $plugin );
The issue with the header information has been discussed in here: Cannot modify header information error in Wordpress. Could you give this a try and see whether this solves this part of your problem?.
On the other issue:
try var_dump ($file) (for instance -- or echo $file ) to see what they actually contain.
Check your configuration path of plugins :
var_dump($wp_plugin_paths);
You've got an error because $realdir is empty.
How can I determine if a PDF file is corrupt (not openable) in PHP? I have downloaded thousands of PDFs via CURL and a small number are incomplete.
$part = 'pdffile.pdf';
$escPath = str_replace( " ", "\\ ", escapeshellcmd( $part ) );
$out = shell_exec( 'pdfinfo ' . $escPath . ' 2>&1' );
if( $out != null && !preg_match( '~Error~i', $out ) )
echo "GOOD: $part\n";
else
echo "CORRUPT: $part\n";
I can only find a way to do this via the command line. The second line is required to escape file paths.
Sorry that the context is so vague but this problem is very vague. I will try to convey the experience so far.
This is the code I am editing and it is on line 133:
$log->log('info', 'total_data: ' . count( $result->data ) );
The above code worked, when I changed the string to 'total_results' it caused a syntax error:
$log->log('info', 'total_results: ' . count( $result->data ) );
The error randomly changes whenever any characters change. For example the above code made this error
Parse error: syntax error, unexpected ']' in /web/api.php on line 180
FYI: there are only 179 lines in this file.
If I remove one letter from the string:
$log->log('info', 'total_result: ' . count( $result->data ) );
The above error changes to:
Parse error: syntax error, unexpected ']' in /web/api.php on line 181
If I keep removing one letter at a time and refreshing the line number keeps incrementing.
Sometimes if I delete the line, save, refresh, paste it back in, save, refresh it will then work. Sometimes if I add more characters to the string it will work. This must be something on a level beyond syntax errors because the same code will work at a later time. I have tried to restart apache2 but that does not fix anything, it usually displays a different random error. I cannot see any consistency with the error messages. The one consistent thing seems to be that as long as nothing changes the error will stay the same.
Here are other error messages I have seen while trying to find some consistencies:
Parse error: syntax error, unexpected 'DirectMap4k' (T_STRING) in /web/api.php on line 180
Again I deleted one line, saved, refreshed, put that line back, saved, refreshed and then it worked.
logging.php
<?php
class logger {
protected $file = null;
protected $log_level = 3;
protected $_date_fmt = 'Y-m-d H:i:s.u';
protected $_levels = [ 'CRITICAL' => 0,
'ERROR' => 1,
'WARNING' => 2,
'INFO' => 3,
'DEBUG' => 4,
'TRACE' => 5,
'TRACE1' => 6,
'TRACE2' => 7 ];
function __construct( $name = 'Anonymous',
$file = 'application.log' )
{
$this->name = $name;
$this->filename = $file;
// check if file exists before fopen creates the file
$new_file = ! file_exists( $file );
// die if file is not writable
if( ! ( $new_file or is_writable( $file ) )) {
die( "logger class cannot write to file: <b>" . $file . "</b>" );
}
$this->file = fopen( $file, 'a' );
if( $new_file ) {
$this->write( "<"."?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?".">\n\n" );
}
}
public function log( $level, $message )
{
if( $this->_levels[ strtoupper( $level ) ] > $this->log_level ) {
// do not log
return;
}
list( $usec, $sec ) = explode( ' ', microtime() );
$datetime = sprintf( '%s.%03d',
date("Y-m-d H:i:s", $sec),
floor($usec * 1000) );
$write = sprintf( '%s - %8.8s : %s',
$datetime,
strtolower( $level ),
$message );
$this->write( $write . "\n" );
}
private function write( $message )
{
fwrite( $this->file, $message );
}
function __destruct()
{
if( $this->file ) {
fclose( $this->file );
}
}
}
?>
The problem ended up being with Vagrant file synching using HGFS. The files are actually on the host machine and they were not being accurately synchronized. To avoid the random errors, I have resorted to never sharing development code over HGFS.
I want to print out the current URL path, but my code doesn't work propperly.
I use this in my file.php
echo "http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
When i open the url http://sub.mydomain.com/file.php it seems to work fine, and it prints "http://sub.mydomain.com/file.php"
But if i remove the .php extension so the url will be http://sub.mydomain.com/file instead, it prints "http://sub.mydomain.com/sub/file.php" which is wrong.
It prints the subdomain twice, and I don't know why?
In my .htaccess file, I have a rewrite that makes it possible to removes .php extensions.
Anyone who can/want to help me please? :)
You need $_SERVER['REQUEST_URI'] instead of $_SERVER['SCRIPT_NAME'], cos $_SERVER['SCRIPT_NAME'] will always give you the file which is working at the moment.
From manual:
SCRIPT_NAME: Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. .
I suppose this helps you getting current URL fully.
echo 'http://'. $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
Notice: DO NOT RELY ON CLIENT'S HTTP_HOST, USE SERVER_NAME INSTEAD! SEE: What is the difference between HTTP_HOST and SERVER_NAME in PHP?
Security Warning
You need to filter (sanitize) $_SERVER['REQUEST_URI'] if you use it in anywhere (to print or store in database), cos it's not safe.
// ie: this could be harmfull
/user?id=123%00%27<script...
Hence, always filter user inputs before using them. At least use htmlspecialchars, htmlentities, strip_tags etc..
Or something like this;
function get_current_url($strip = true) {
static $filter, $scheme, $host, $port;
if ($filter == null) {
$filter = function($input) use($strip) {
$input = trim($input);
if ($input == '/') {
return $input;
}
// add more chars if needed
$input = str_ireplace(["\0", '%00', "\x0a", '%0a', "\x1a", '%1a'], '',
rawurldecode($input));
// remove markup stuff
if ($strip) {
$input = strip_tags($input);
}
// or any encoding you use instead of utf-8
$input = htmlspecialchars($input, ENT_QUOTES, 'utf-8');
return $input;
};
$scheme = isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME']
: ('http'. (($_SERVER['SERVER_PORT'] == '443') ? 's' : ''));
$host = $_SERVER['SERVER_NAME'];
$port = ($_SERVER['SERVER_PORT'] != '80' && $scheme != 'https')
? (':'. $_SERVER['SERVER_PORT']) : '';
}
}
return sprintf('%s://%s%s%s', $scheme, $host, $port, $filter($_SERVER['REQUEST_URI']));
}
$main_folder = str_replace('\\','/',dirname(__FILE__) );
$document_root = str_replace('\\','/',$_SERVER['DOCUMENT_ROOT'] );
$main_folder = str_replace( $document_root, '', $main_folder);
if( $main_folder ) {
$current_url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME']. '/' . ltrim( $main_folder, '/' ) . '/';
} else {
$current_url = $_SERVER['REQUEST_SCHEME'].'://'.rtrim( $_SERVER['SERVER_NAME'], '/'). '/';
}