简体   繁体   English

使用PHP检查MySQL数据库中URL的可用性吗?

[英]Check availability of URLs in a MySQL Database using PHP?

I have three filed in my mysql table they are: id, url, status 我在mysql表中有三个文件,分别是:id,url,状态

How to check all urls from the column url and write either 1 (available) or 0 (unavailable) to the status column? 如何检查列URL中的所有URL,并将1(可用)或0(不可用)写入状态列?

To just check urls manualy in php w/o mysql I could use this: 要仅在不带mysql的php中手动检查网址,我可以使用以下命令:

<?php
    function Visit($url){
    $agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL,$url );
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch,CURLOPT_VERBOSE,false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $page=curl_exec($ch);
    //echo curl_error($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if($httpcode >= 200 && $httpcode < 300){ 
        return true;
    }
    else {
        return false;
    }
}
    if(Visit("http://www.google.com")){//maybe make it a variable from a result of a mysql select, but how to process it one by one?  
        echo "Website OK"; //maybe somesql here to wtite '1'
    }
    else{
        echo "Website DOWN";//maybe somesql here to wtite '0'
    }
?> 

This is bad in terms of performance as doing queries in a loop is bad design, you should instead build a batch update and run the query in the end, but I've not enough time now to elaborate that. 就性能而言,这是很糟糕的,因为在循环中进行查询是错误的设计,您应该构建一个批处理更新并最后运行查询,但是现在我没有足够的时间来详细说明这一点。 This is just to get you started: 这只是让您入门:

$sql = "SELECT id,url FROM mytable";
$res = mysql_query($sql) or die(mysql_error());
if($res)
{
  while($row = mysql_fetch_assoc($res))
  {
    $status = visit($row['url']) ? '1' : '0';
    $id = $row['id'];
    $update = "UPDATE mytable SET status = $status WHERE id = $id";
    $res = mysql_query($update) or die(mysql_error());
  }
}
echo mysql_num_rows($result) ? '1' : '0';

You can use sql queries for example: 您可以使用sql查询为例:

select id, url from urltable;
update urltable set status=1 where id=99;

So, how about use this code with your Visit function: 因此,如何将此代码与Visit函数一起使用:

$link = mysql_connect('localhost', 'test', 'pppppp');
$db_selected = mysql_select_db('test', $link);
$query = "select id, url from urltable";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
    $visitid =  $row['id'];
    $visiturl =  $row['url'];
    $visitstatus = Visit($visiturl)? 1: 0;
    $upquery = sprintf("update urltable set status=%d where id=%d", $visitstatus, $visitid);
    $upresult = mysql_query($upquery);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM