file_get_contents load error and loop? - php

I just looking for solution to load content using file_get_contents
My script works fine, but sometimes file are not load, i know how to check if file_get_contents fails but how to try get it again without page reload?
$url = file_get_contents('url.to.file');
if ( $url === false )
{
// code to do it again, how?
}

Ok, i found my own solution with for loop.
it will try 5 times to load file if will load for loop will be break
$url = file_get_contents('File');
if ( $url === false ) {
for ($x = 0; $x <= 5; $x++) {
$url = file_get_contents('File');
if ( $url === true ) {
break;
}
}
}

Then you could try runnning the get in a loop
$max_loop = 5;
while (FALSE == $url = file_get_contents('url.to.file') ) {
$cur_loop++
if ( $cur_loop >= $max_loop )
// indicate an error so can be put on page
break;
}
}
Written in a function it might look like this
function get_url($the_url, $max_try)
$cur_loop = 0;
while (FALSE == $url = file_get_contents($the_url) ) {
$cur_loop++
if ( $cur_loop >= $max_try )
break;
}
}
return $url;
}
//called like this
$data = get_url('the.url',5);
if ( $data === false ) {
// error message
exit;
}

Related

Get all the links from a URL then check whether URL exists or not

PHP Code :
$get_url="some url";
$content_of_url=file_get_contents($get_url);
$content_of_url = strip_tags($content_of_url,"<a>");
$get_string = preg_split("/<\/a>/",$content_of_url);
foreach ( $get_string as $val_get ){
if( strpos($val_get, "<a href=") !== FALSE ){
$val_get = preg_replace("/.*<a\s+href=\"/sm","",$val_get);
$val_get = preg_replace("/\".*/","",$val_get);
$headers = #get_headers($val_get);
if($headers && strpos( $headers[0], '200')) {
$check_url = $val_get." <b>URL Exist</b>"."<br/><br/>";
}
else {
$check_url = $val_get." <b>URL Doesn't Exist</b>"."<br/><br/>";
}
echo($check_url);
}
}
It shows the incorrect result for some URLs that it doesn't exist or not working but actually that link is working.

check if a url is reachable, always returning false

My problem is that it returns an error for every url entered:
The below code takes and checks the url entered, if i enter 'http://eample.com' it would return success but for some reason it returns all urls as unreachable.
<?php
Global $excludeLocal;
$excludeLocal = true; // Whether to exclude checking links on the same host as the plugin resides
// Hook our custom function into the 'shunt_add_new_link' filter
yourls_add_filter( 'shunt_add_new_link', 'churl_reachability' );
// Add a new link in the DB, either with custom keyword, or find one
function churl_reachability( $churl_reachable, $url, $keyword = '' ) {
global $ydb, $excludeLocal;
// Check if the long URL is a different type of link
$different_urls = array (
array ( 'mailto://', 9 ),
array ( 'ftp://', 6 ),
array ( 'javascript://', 13),
array ( 'file://', 7 ),
array ( 'telnet://', 9),
array ( 'ssh://', 6),
array ( 'sip://', 6),
);
foreach ($different_urls as $url_type){
if (substr( $url, 0, $url_type[1] ) == $url_type[0]){
$churl_reachable = true; // No need to check reachability if URL type is different
break;
} elseif ($excludeLocal) {
if (substr($url, 0, strlen('http://'.$_SERVER['SERVER_NAME'])) == 'http://'.$_SERVER['SERVER_NAME']) {
$churl_reachable = true;
break;
}
}
}
// Check if the long URL is a mailto
if ($churl_reachable == false){
$churl_reachable = churl_url_exists( $url ); // To do: figure out how to use yourls_get_remote_content( $url ) instead.
}
// Return error if the entered URL is unreachable
if ( $churl_reachable == false ){
$return['status'] = 'fail';
$return['code'] = 'error:url';
$return['message'] = 'The entered URL is unreachable. Check the URL or try again later.';
$return['statusCode'] = 200; // regardless of result, this is still a valid request
return yourls_apply_filter( 'add_new_link_fail_unreachable', $return, $url, $keyword, $title );
} else {
return false;
}
}
function churl_url_exists( $churl ){
$handle = #fopen($churl, "r");
if ($handle === false)
return false;
fclose($handle);
return true;
}
is there something i might have did wrong ?
Any help is appreciated
check allow_url_fopen directive in your php.ini
Try to run the command $handle = fopen($churl, "r"); without a # symbol and see the error

PHP Error - "Warning: Creating default object from empty value in..." [duplicate]

This question already has answers here:
Creating default object from empty value in PHP?
(18 answers)
Closed 7 years ago.
I have a PHP file on my website that is producing errors after upgrading from PHP 5.3 to PHP 5.4. This is the error it produces:
Warning: Creating default object from empty value in (removing this
part of the error)/arcade.php on line 60
This is what the code looks like after like 60:
{
$this->arcade->version = '';
}else
{
$this->arcade->version = '3.4.0';
}
I'm assuming it has to do with the blank value there. I researched some similar fixes, but I'm still having trouble figuring out exactly what I should add to the php file to fix it.
Thank you very much for any help ahead of time!
Edit: Here's the rest of the code I'm not sure where it intializes. I'm pretty ignorant of these things.
if ( ! defined( 'IN_IPB' ) )
{
print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded all the relevant files. <br /> <b>File Version 3.3.0</b>";
exit();
}
class component_public
{
var $ipsclass = '';
var $arcade = '';
function run_component()
{
$this->ipsclass->load_language( 'lang_Arcade' );
if( !$this->ipsclass->cache['arcade_settings']['allow_user_skin'] )
{
if( $this->ipsclass->cache['arcade_settings']['skin'] == 0 ) {
$this->ipsclass->load_template('skin_Arcade1');
}
if( $this->ipsclass->cache['arcade_settings']['skin'] == 1 ) {
$this->ipsclass->load_template('skin_Arcade2');
}
if( $this->ipsclass->cache['arcade_settings']['skin'] == 2 ) {
$this->ipsclass->load_template('skin_Arcade3');
}
}else
if( $this->ipsclass->cache['arcade_settings']['allow_user_skin'] && !$this->ipsclass->member['id'] )
{
if( $this->ipsclass->cache['arcade_settings']['skin'] == 0 ) {
$this->ipsclass->load_template('skin_Arcade1');
}
if( $this->ipsclass->cache['arcade_settings']['skin'] == 1 ) {
$this->ipsclass->load_template('skin_Arcade2');
}
if( $this->ipsclass->cache['arcade_settings']['skin'] == 2 ) {
$this->ipsclass->load_template('skin_Arcade3');
}
}else
if( $this->ipsclass->cache['arcade_settings']['allow_user_skin'] && $this->ipsclass->member['id'] )
{
$this->ipsclass->DB->query("SELECT arcade_skin FROM ".$this->ipsclass->vars['sql_tbl_prefix']."members WHERE id=".intval($this->ipsclass->member['id']));
$this->arcade->lib->user = $this->ipsclass->DB->fetch_row();
if( $this->arcade->lib->user['arcade_skin'] == 0) {
$this->ipsclass->load_template('skin_Arcade1');
}
if( $this->arcade->lib->user['arcade_skin'] == 1) {
$this->ipsclass->load_template('skin_Arcade2');
}
if( $this->arcade->lib->user['arcade_skin'] == 2) {
$this->ipsclass->load_template('skin_Arcade3');
}
}
if( !$this->ipsclass->cache['arcade_settings']['build'] )
{
$this->arcade->version = '';
}else
{
$this->arcade->version = '3.4.0';
}
$this->ipsclass->vars['arcade_dir'] = 'arcade';
$component_copyright = '<div class="copyright" align="center">ibProArcade '.$this->arcade->version.' © '.date('Y').'</div>';
$this->ipsclass->skin['_wrapper'] = str_replace("<% COPYRIGHT %>", $component_copyright . "<% COPYRIGHT %>", $this->ipsclass->skin['_wrapper']);
require ROOT_PATH.$this->ipsclass->vars['arcade_dir'].'/db/arcade_mysql.php';
$this->arcade->db = new arcade_db;
$this->arcade->db->ipsclass =& $this->ipsclass;
require ROOT_PATH.$this->ipsclass->vars['arcade_dir'].'/modules/arcadelib.php';
$this->arcade->lib = new arcadelib;
$this->arcade->lib->ipsclass =& $this->ipsclass;
$this->arcade->lib->arcade =& $this->arcade;
$this->arcade->lib->init();
require ROOT_PATH.$this->ipsclass->vars['arcade_dir'].'/modules/scoreboard.php';
$this->arcade->sb = new scoreboard;
$this->arcade->sb->ipsclass =& $this->ipsclass;
$this->arcade->sb->arcade =& $this->arcade;
require ROOT_PATH.$this->ipsclass->vars['arcade_dir'].'/modules/arcadeskin.php';
$this->arcade->skin = new arcadeskin;
$this->arcade->skin->ipsclass =& $this->ipsclass;
$this->arcade->skin->arcade =& $this->arcade;
require_once ROOT_PATH.'sources/api/api_topics_and_posts.php';
$this->arcade->api = new api_topics_and_posts();
$this->arcade->api->ipsclass =& $this->ipsclass;
if( $this->arcade->lib->settings['arcade_status'] )
{
$this->arcade->lib->arcade_error( array( LEVEL => 1, MSG => 'arcade_offlinemsg' ) );
}
$page = (isset($this->ipsclass->input['p'])) ? $this->ipsclass->txt_alphanumerical_clean( $this->ipsclass->input['p'] ) : 'default';
$code = (isset($this->ipsclass->input['code'])) ? $this->ipsclass->input['code'] : '';
// Backwords compatibility with older games
if( isset($this->ipsclass->input['do']) && ($this->ipsclass->input['do'] == 'newscore') )
{
$code = 'newscore';
}
if( isset($this->ipsclass->input['do']) && ($this->ipsclass->input['do'] == 'verifyscore') )
{
$code = 'verifyscore';
}
if( isset($this->ipsclass->input['do']) && ($this->ipsclass->input['do'] == 'savescore') )
{
$code = 'savescore';
}
$file = ROOT_PATH.$this->ipsclass->vars['arcade_dir'].'/modules/page_'.$page.'.php';
if( file_exists($file) )
{
require $file;
}
else
{
require ROOT_PATH.$this->ipsclass->vars['arcade_dir'].'/modules/page_default.php';
}
$runme = new arcade_page;
$runme->ipsclass =& $this->ipsclass;
$runme->arcade =& $this->arcade;
$runme->exec_page( $code );
}
}
You got that error if trying to access properties of unexistent objects, like this:
$arcade = null;
$arcade->version = '3.4.0';
In order to fix it, yours $this->arcade property should not be empty.
Upd.
First, remove the line with arcade definition/initialization entirely:
class component_public
{
var $ipsclass = '';
function run_component()
{
$this->ipsclass->load_language( 'lang_Arcade' );
Next, add this piece of code:
class SilentAssasin {
public function __get($property) {
return $this->{$property} = new static();
}
}
class component_public extends SilentAssasin
{
instead of this:
class component_public
{
That must fix that creating from empty error.
Ah, forgot to mention... That SilentAssasin is just a name for custom class, you actually can name it anything you like, like PathosErrorSuppressor or OversizedBanHammerForThatStupidError etc.

PHP check file size in via Internet [duplicate]

This question already has answers here:
Remote file size without downloading file
(15 answers)
Closed 9 years ago.
How to check file size in via Internet? The sample below is my code that does not work
echo filesize('http://localhost/wordpress-3.1.2.zip');
echo filesize('http://www.wordpress.com/wordpress-3.1.2.zip');
The filesize function is used to get size of files stored locally.* For remote files you must find other solution, for example:
<?php
function getSizeFile($url) {
if (substr($url,0,4)=='http') {
$x = array_change_key_case(get_headers($url, 1),CASE_LOWER);
if ( strcasecmp($x[0], 'HTTP/1.1 200 OK') != 0 ) { $x = $x['content-length'][1]; }
else { $x = $x['content-length']; }
}
else { $x = #filesize($url); }
return $x;
}
?>
Source: See the first post-comment in link below
http://php.net/manual/en/function.filesize.php
*Well, to be honest since PHP 5 there are some wrappers for file functions, see here:
http://www.php.net/manual/en/wrappers.php
You can find a lot more examples, even here on SO, this should satisfy your needs: PHP: Remote file size without downloading file
Try to use search function before asking question next time!
try this function
<?php
function remotefsize($url) {
$sch = parse_url($url, PHP_URL_SCHEME);
if (($sch != "http") && ($sch != "https") && ($sch != "ftp") && ($sch != "ftps")) {
return false;
}
if (($sch == "http") || ($sch == "https")) {
$headers = get_headers($url, 1);
if ((!array_key_exists("Content-Length", $headers))) { return false; }
return $headers["Content-Length"];
}
if (($sch == "ftp") || ($sch == "ftps")) {
$server = parse_url($url, PHP_URL_HOST);
$port = parse_url($url, PHP_URL_PORT);
$path = parse_url($url, PHP_URL_PATH);
$user = parse_url($url, PHP_URL_USER);
$pass = parse_url($url, PHP_URL_PASS);
if ((!$server) || (!$path)) { return false; }
if (!$port) { $port = 21; }
if (!$user) { $user = "anonymous"; }
if (!$pass) { $pass = "phpos#"; }
switch ($sch) {
case "ftp":
$ftpid = ftp_connect($server, $port);
break;
case "ftps":
$ftpid = ftp_ssl_connect($server, $port);
break;
}
if (!$ftpid) { return false; }
$login = ftp_login($ftpid, $user, $pass);
if (!$login) { return false; }
$ftpsize = ftp_size($ftpid, $path);
ftp_close($ftpid);
if ($ftpsize == -1) { return false; }
return $ftpsize;
}
}
?>
I think that's probably not possible. The best way is to download the file via file_get_contents and then use filesize over the file. You can later delete the file too!

Telnet to cisco switch using php

I need to telnet to cisco switch using php and execute show interface status command and get results. I tried some php classes I found on internet but none of them could connect to device. So I tried to write the script myself, but I have the same problem, I cant connect to device.
The host sends me banner message and then new line with username:.
I send my username with \r\n, wait some time and tries to read data, but it looks to me like host is just ignoring my new line characters. This is response I got (explode('\n') on response):
Array
(
[0] => %
[1] => User Access Verification
[2] => Username: timeout expired!
)
Why didn't I get prompt on password? I tried it with sending telnet headers, and without, no change. Can anyone please help me?
Here is my code
<?
$host = "switchName";
$name = "name";
$pass = "pass";
$port = 23;
$timeOut = 15;
$connected = false;
$skipNullLines = true;
$timeout = 125000;
$header1=chr(0xFF).chr(0xFB).chr(0x1F).chr(0xFF).chr(0xFB).chr(0x20).chr(0xFF).chr(0xFB).chr(0x18).chr(0xFF).chr(0xFB).chr(0x27).chr(0xFF).chr(0xFD).chr(0x01).chr(0xFF).chr(0xFB).chr(0x03).chr(0xFF).chr(0xFD).chr(0x03).chr(0xFF).chr(0xFC).chr(0x23).chr(0xFF).chr(0xFC).chr(0x24).chr(0xFF).chr(0xFA).chr(0x1F).chr(0x00).chr(0x50).chr(0x00).chr(0x18).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x20).chr(0x00).chr(0x33).chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0x2C).chr(0x33).chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x27).chr(0x00).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x18).chr(0x00).chr(0x41).chr(0x4E).chr(0x53).chr(0x49).chr(0xFF).chr(0xF0);
$header2=chr(0xFF).chr(0xFC).chr(0x01).chr(0xFF).chr(0xFC).chr(0x22).chr(0xFF).chr(0xFE).chr(0x05).chr(0xFF).chr(0xFC).chr(0x21);
function read_string()
{
global $fw,$host,$skipNullLines;
$string = "";
while( !feof($fw) )
{
$read = fgets($fw);
$string .= $read;
// Probably prompt, stop reading
if( strpos($read, ':') !== FALSE || strpos($read, '> (enable)') !== FALSE || strpos($read, $host.'#') !== FALSE)
{ break; }
}
$string = explode("\n", $string);
// Get rid of null lines
$ret = array();
for($i = 0; $i<count($string); $i++)
{
if( trim($string[$i]) == '' && $skipNullLines ) continue;
$ret[] = $string[$i];
}
return $ret;
}
function send_string($string, $force=false)
{
GLOBAL $timeout,$fw;
$string = trim($string);
// execute only strings that are preceded by "show" (if not forced)
if(!$force && strpos($string, 'show ') !== 0)
{
return 1;
}
fputs($fw, $string."\r\n");
echo("SEND:".$string."\r\n");
usleep($timeout);
}
$fw = fsockopen($host, $port, $errno, $errorstr, $timeOut);
if($fw == false)
{
echo("Cant connect");
}
else
{
echo("Connected<br>");
$connected = true;
stream_set_timeout($fw, $timeout);
// fputs($fw, $header1);
// usleep($timeout);
// fputs($fw, $header2);
// usleep($timeout);
print_r(read_string());
send_string("test", true);
print_r(read_string());
}
fclose($fw);
?>
UPDATE
If I send username at first, and then I read, I get password prompt. I dont understand it, why cant I firstly read messages from host and then send my response. The way it works to me now (send response and then read for prompt) is no-sense! (and I still got "% Authentication failed." message event with right password/name).
...
$connected = true;
stream_set_timeout($fw, $timeout);
send_string("name", true);
send_string("password", true);
print_r(read_string());
...
Okay, so I dont know what was the problem, but after "few" tests I was able to write this class that works for me. I dont know why other telnet classes dont work altough they do pretty much the same. So if anyone will have similar problem, you can try this:
class TELNET
{
private $host;
private $name;
private $pass;
private $port;
private $connected;
private $connect_timeout;
private $stream_timetout;
private $socket;
public function TELNET()
{
$this->port = 23;
$this->connected = false; // connected?
$this->connect_timeout = 10; // timeout while asking for connection
$this->stream_timeout = 380000; // timeout between I/O operations
}
public function __destruct()
{
if($this->connected) { fclose($this->socket); }
}
// Connects to host
// #$_host - addres (or hostname) of host
// #$_user - name of user to log in as
// $#_pass - password of user
//
// Return: TRUE on success, other way function will return error string got by fsockopen()
public function Connect($_host, $_user, $_pass)
{
// If connected successfully
if( ($this->socket = #fsockopen($_host, $this->port, $errno, $errorstr, $this->connect_timeout)) !== FALSE )
{
$this->host = $_host;
$this->user = $_user;
$this->pass = $_pass;
$this->connected = true;
stream_set_timeout($this->socket, 0, 380000);
stream_set_blocking($this->socket, 1);
return true;
}
// else if coulnt connect
else return $errorstr;
}
// LogIn to host
//
// RETURN: will return true on success, other way returns false
public function LogIn()
{
if(!$this->connected) return false;
// Send name and password
$this->SendString($this->user, true);
$this->SendString($this->pass, true);
// read answer
$data = $this->ReadTo(array('#'));
// did we get the prompt from host?
if( strtolower(trim($data[count($data)-1])) == strtolower($this->host).'#' ) return true;
else return false;
}
// Function will execute command on host and returns output
//
// #$_command - command to be executed, only commands beginning with "show " can be executed, you can change this by adding
// "true" (bool type) as the second argument for function SendString($command) inside this function (3rd line)
//
function GetOutputOf($_command)
{
if(!$this->connected) return false;
$this->SendString($_command);
$output = array();
$work = true;
//
// Read whole output
//
// read_to( array( STRINGS ) ), STRINGS are meant as possible endings of outputs
while( $work && $data = $this->ReadTo( array("--More--","#") ) )
{
// CHeck wheter we actually did read any data
$null_data = true;
foreach($data as $line)
{
if(trim($line) != "") {$null_data = false;break;}
}
if($null_data) { break;}
// if device is paging output, send space to get rest
if( trim($data[count($data)-1]) == '--More--')
{
// delete line with prompt (or "--More--")
unset($data[count($data)-1]);
// if second line is blank, delete it
if( trim($data[1]) == '' ) unset($data[1]);
// If first line contains send command, delete it
if( strpos($data[0], $_command)!==FALSE ) unset($data[0]);
// send space
fputs($this->socket, " ");
}
// ak ma vystup max dva riadky
// alebo sme uz nacitali prompt
// IF we got prompt (line ending with #)
// OR string that we've read has only one line
// THEN we reached end of data and stop reading
if( strpos($data[count($data)-1], '#')!==FALSE /* || (count($data) == 1 && $data[0] == "")*/ )
{
// delete line with prompt
unset($data[count($data)-1]);
// if second line is blank, delete it
if( trim($data[1]) == '' ) unset($data[1]);
// If first line contains send command, delete it
if( strpos($data[0], $_command)!==FALSE ) unset($data[0]);
// stop while cyclus
$work = false;
}
// get rid of empty lines at the end
for($i = count($data)-1; $i>0; $i--)
{
if(trim($data[$i]) == "") unset($data[$i]);
else break;
}
// add new data to $output
foreach($data as $v)
{ $output[] = $v; }
}
// return output
return $output;
}
// Read from host until occurence of any index from $array_of_stops
// #array_of_stops - array that contains strings of texts that may be at the end of output
// RETURNS: output of command as array of lines
function ReadTo($array_of_stops)
{
$ret = array();
$max_empty_lines = 3;
$count_empty_lines = 0;
while( !feof($this->socket) )
{
$read = fgets($this->socket);
$ret[] = $read;
//
// Stop reading after (int)"$max_empty_lines" empty lines
//
if(trim($read) == "")
{
if($count_empty_lines++ > $max_empty_lines) break;
}
else $count_empty_lines = 0;
//
// Does last line of readed data contain any of "Stop" strings ??
$found = false;
foreach($array_of_stops AS $stop)
{
if( strpos($read, $stop) !== FALSE ) { $found = true; break; }
}
// If so, stop reading
if($found) break;
}
return $ret;
}
// Send string to host
// If force is set to false (default), function sends to host only strings that begins with "show "
//
// #$string - command to be executed
// #$force - force command? Execute if not preceeded by "show " ?
// #$newLine - append character of new line at the end of command?
function SendString($string, $force=false, $newLine=true)
{
$t1 = microtime(true);
$string = trim($string);
// execute only strings that are preceded by "show"
// and execute only one command (no new line characters) !
if(!$force && strpos($string, 'show ') !== 0 && count(explode("\n", $string)) == 1)
{
return 1;
}
if($newLine) $string .= "\n";
fputs($this->socket, $string);
$t2 = microtime(true);
}
}
// EXAMPLE
$host = "hostname";
$name = "username";
$pass = "password";
$t = new TELNET();
echo("CONNECT:".$t->Connect($host, $name, $pass)."<br>");
echo("LOGIN:".(int)$t->LogIn());
echo("<br>OUTPUT:<br>");
print_r($t->GetOutputOf("show snmp"));
print_r($t->GetOutputOf("show users"));
print_r($t->GetOutputOf("show interface status"));
PS: my devices prompt is "hostname#", so you may need to edit Login function to make this code work with prompt of your device (so you may need in GetOutputOf() )

Categories