I am trying to call an URL with PHP to check if it exists and is reachable.
My initial code was
fopen('http://'.$this -> url, 'r');
But it throws the following errors every time an URL is unreachable:
fopen(http://dwzegdzgwedzgew.com): failed to open stream: php_network_getaddresses: getaddrinfo failed
php_network_getaddresses: getaddrinfo failed:
The error operator (#) is ignored in this case as the error isn't thrown by fopen itself but while resolving the asdress. So I thought that should do it:
#fopen(#'http://'.$this -> url, 'r');
but it also goes on throwing the error.
Is there a non-error-throwing possibility to check if an URL exists within PHP before opening it?
What is the error message with $ressource = #fopen('http://' . $this->url, 'r'); ?
<?php
$urls = array('kihgkighuhgkig.li', 'google.com', 'adsfafdf.fr');
foreach ($urls as $url)
{
if (gethostbyname($url) != $url)
{
$ressource = fopen('http://' . $url, 'r');
var_dump($url, $ressource);
}
}
The output is :
$> php test.php
string(10) "google.com"
resource(6) of type (stream)
Related
I am trying to auto sync my remote database with my local machine by using php file_get_contents and connecting to remote server with ftp_connect frequent intervals. I am using windows Task Scheduler from my local machine for that.
My php script works perfectly from the browser. But when Task Scheduler Triggers it, the command prompt window comes up showing error messages.
My script is
<?php
set_time_limit(0);
include('functions.php');
$root=$_SERVER['DOCUMENT_ROOT'];
$sitearr=array("indianchristians","mc","evaa","laveena","aita","kaazar","landshop");
$date=Date('Y-m-d H:i:s');
$vals="";
$msg="";
foreach($sitearr as $sa)
{
include('connnew.php');
if($sa=="landshop")
{
$remurl="dwggxtwa_landshoppe.sql";
$localurl="$root/$folder/Myadmin/download/sqlbackup/";
$backupserv=file_get_contents($url."/Myadmin/download/sqlbackup/backupserver.php");
}
else{
$remurl="$db.sql";
$localurl="$root/$folder/admin/download/sqlbackup/";
$backupserv=file_get_contents($url."/admin/download/sqlbackup/backupserver.php");
}
$savedb=$db.".sql";
$localdb=$localurl.$savedb;
// echo $localdb."<br>";
$conn = ftp_connect($ftp_server);
$login_result = ftp_login($conn, $ftp_user_name, $ftp_user_pass);
ftp_pasv($conn, true);
if($sa=="landshop"){
ftp_chdir($conn, '/public_html/Myadmin/download/sqlbackup/');
}else{
ftp_chdir($conn, '/admin/download/sqlbackup/');
}
if (ftp_get($conn, $localdb, $remurl, FTP_BINARY))
{
// echo "$sa saved locally<br>";
$query=$maindb->query("SHOW TABLES") or die("SHOW TABLES ERROR ".$maindb->error);
while($st=$query->fetch_array()){
$drop=$maindb->query("DROP TABLE $db.$st[0]");
//if($drop){echo "<br>$db.$st[0] DROPPED !<br>";}else{echo "<br>$db.$st[0] NOT DROPPED !
<br>";}
}
$templine = '';
// Read in entire file
$lines = file($localdb);
// Loop through each line
foreach ($lines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
continue;
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
// Perform the query
if(!empty($templine)){
$maindb->query($templine) or die('Error performing query
\'<strong>' . $templine . '\': ' . $maindb->error . '<br /><br />');
}
// Reset temp variable to empty
$templine = '';
}
}
ftp_close($conn);
$vals.="('$date','$sa'),";
$msg .="Updated $sa<br>";
}
}
if(!empty($vals)){
$vals=rtrim($vals,",");
$date=Date('Y-m-d H:i:s');
$link = mysqli_connect('127.0.0.1','admin','admin') or die ("Error connecting to
mysql : " . mysqli_connect_errno($link).'\r\n');
$connect=new mysqli('127.0.0.1','admin','admin','admin') or die("Database error
:".$connect->error);
$checktab=$connect->query("SELECT * FROM backuptimeline");
if(!$checktab)
{
$createsql = "CREATE TABLE backuptimeline
(
id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
Date datetime,
site varchar(500)
)";
$createtab=$connect->query($createsql) or die($connect->error);
}
$butlsql="INSERT INTO backuptimeline (Date,site) VALUES $vals";
// echo $butlsql."<br>";
$insbu=$connect->query($butlsql)or die($connect->error);
if($insbu){
//sendEmailAlerts("anitgopinath#gmail.com","anitgopinath#gmail.com","DB
$sa Backed Up","All DB $sa backed up at $date");
$msg.="<br>Timeline Updated<br>";
}
else{
$msg.= "<br>Timeline Not Updated<br>";
}
echo $msg."<br>";
sendEmailAlerts("anitgopinath#gmail.com","anitgopinath#gmail.com","DBs Back Up
Results",$msg);
}else{
echo $msg."<br>";
sendEmailAlerts("anitgopinath#gmail.com","anitgopinath#gmail.com","DBs Back Up
Failed",'DBs Back Up Failed');
}
?>
Task Scheduler entries;
Program / Script in Action field:
"C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\binaries\php\php_runningversion\php.exe"
Arguments field
"C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php"
Some error Messages
Warning: ftp_get(/matrimony/admin/download/sqlbackup/rotiraa1_mc.sql): failed to open stream: No such file or directory in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php on line 35 PHP Warning: ftp_get(): Error opening /matrimony/admin/download/sqlbackup/rotiraa1_mc.sql in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php on line 35
Warning: ftp_get(): Error opening
/matrimony/admin/download/sqlbackup/rotiraa1_mc.sql in C:\Program
Files
(x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php
on line 35 PHP Warning: file_get_contents(): SSL operation failed
with code 1. OpenSSL Error messages: error:1407742E:SSL
routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version in
C:\Program Files
(x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php
on line 21
Warning: file_get_contents(): SSL operation failed with code 1.
OpenSSL Error messages: error:1407742E:SSL
routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version in
C:\Program Files
(x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php
on line 21 PHP Warning: file_get_contents(): Failed to enable crypto
in C:\Program Files
(x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php
on line 21
Warning: file_get_contents(): Failed to enable crypto in C:\Program
Files
(x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php
on line 21 PHP Warning:
file_get_contents(https://www.evaa-ethnix.com/admin/download/sqlbackup/backupserver.php):
failed to open stream: operation failed in C:\Program Files
(x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php
on line 21
Warning:
file_get_contents(https://www.evaa-ethnix.com/admin/download/sqlbackup/backupserver.php):
f
I have tried using a batch file (.bat) too. I put it in system32 folder and tried. Still same errors appear.
I am not able identify whether it is a path issue or something else. I have been breaking my for a long time on this.
Any help will be greatly appreciated.
Finally after much googling and brainstorming I found I have two issues:
PHP file_get_contents was creating the SSL error. So I replaced it with Curl as follows;
function file_get_contents_curl( $url ) {
$ch = curl_init();
curl_setopt( $ch, CURLOPT_AUTOREFERER, TRUE );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, TRUE );
$data = curl_exec( $ch );
curl_close( $ch );
return $data;
}
The path local url path ftp_get() began with a variable $root which had
$root=$_SERVER['DOCUMENT_ROOT'];
This was not seen by the Windows Task Scheduler. So I simply replaced $root with the complete path
C:/Program Files (x86)/EasyPHP-DevServer-14.1VC9/data/localweb/$folder
All my problems disappeared ! My system is auto syncing my remote database to my local database on set schedules. I am a happy man now ! :)
I'm trying:
-to connect to the server
-to list all the files
-to read the files and echo the content.
The connection work well:
$conn_id = ssh2_connect('xxx.com', 22);
$login_result = ssh2_auth_password($conn_id, 'xxxxxx', 'xxxxxxxxx');
$sftp = ssh2_sftp($conn_id);
$dir = "ssh2.sftp://$sftp/home";
$ftp_contents = scanFilesystem($dir);
Then I loop over the directory and get all the filenames, work like a charm:
foreach($ftp_contents as $key => $currentFilename){
echo($currentFilename);
}
Then I try to get the content of the file.... And it doesn't work.
$stream = fopen("ssh2.sftp://$sftp/home/".$currentFilename, 'r');
echo($stream);
There is the output error:
Warning: fopen(ssh2.sftp://Resource id #4/home/myfile.xml) [function.fopen]: failed to open stream: operation failed in /home/xxxxxx/public_html/xxx.php on line 38
The line 38 is the end of the foreach.
I try with:
fopen("ssh2.sftp://$sftp/home/".$currentFilename, 'r');
fopen("ssh2.sftp://$sftp/".$currentFilename, 'r');
fopen("/home/".$currentFilename, 'r');
fopen("home/".$currentFilename, 'r');
Nothing work, always the same type of error, can some one help me please?
Thanks.
update: I try with : $stream = file_get_contents("ssh2.sftp://$sftp/home/$data"); does'nt work either ...
Still got the error :
Warning: file_get_contents() [function.file-get-contents]: Unable to open ssh2.sftp://Resource id #3/xxx.xml on remote host in /home/xxxxxx/public_html/xxxx.php on line 40
I don't have a clue ... can some one help me?
I had the same problem. Resolved by converting the $sftp resource to an integer before using it as a url, which is a string.
Should work like that:
$sftp = (int)$sftp;
$stream = fopen("ssh2.sftp://$sftp/home/".$currentFilename, 'r');
I'm using fopen to generate a price feed.
if (($handle = fopen("http://feedurl", "r")) !== FALSE) {
}
Is there a way to stop this warning if the feed fails:
Warning: fopen() [function.fopen]: php_network_getaddresses: getaddrinfo failed: Name or service not known in…
You can use # to suppress the warning:
if(($handle = #fopen("http://feedurl", "r")) !== FALSE){
}
This is suitable here because you are handling the error condition appropriately. Note that liberal use of the # sign, in general, to suppress errors and warnings is ill-advised.
Per the manual entry for fopen:
If the open fails, an error of level E_WARNING is generated. You may use # to suppress this warning.
here is another possible solution
$file_name = "http://feedurl";
if (file_exists($file_name) === false) {
return;
}
$handle = fopen($file_name, "r");
Or you can use
error_reporting(E_ALL ^ E_WARNING);
i load file from server:
$url = 'http://www.sample.com/test.xml';
$xml = simplexml_load_file($url);
And if servers is close i get error:
Warning: simplexml_load_file() [function.simplexml-load-file]: php_network_getaddresses: getaddrinfo failed:...
Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity
how to check if the file is reached?
From the manual page for simplexml_load_file
Returns an object of class SimpleXMLElement with properties containing the data held within the XML document. On errors, it will return FALSE.
which means you can do
$url = 'http://www.sample.com/test.xml';
$xml = simplexml_load_file($url);
// check what was returned
if(FALSE === $xml) {
echo 'could not open file';
}
In this code :
$path = "C:\NucServ\www\vv\static\arrays\news.php";
$fp = fopen($path, "w");
if(fwrite($fp=fopen($path,"w"),$text))
{
echo "ok";
}
fclose($fp);
I have this error message:
failed to open stream: Invalid argument
What is wrong in my code?
Your backslashes is converted into special chars by PHP. For instance, ...arrays\news.php gets turned into
...arrays
ews.php
You should escape them like this:
$path = "C:\\NucServ\\www\\vv\\static\\arrays\\news.php";
Or use singles, like this:
$path = 'C:\NucServ\www\vv\static\arrays\news.php';
Also, your if is messed up. You shouldn't fopen the file again. Just use your $fp which you already have.
path error:
$path = 'C:/NucServ/www/vv/static/arrays/news.php';
file lock:
user file_get_contents replace fopen