[英]How to check if a variable contains a valid url using PHP and jQuery?
[英]How to check if a URL contains a date in PHP
我想構建一個自動功能,以在一天結束時自動從該URL上傳報告。 我的問題是URL每天都隨着日期變化。 如何獲取URL是否帶有日期? 我在這里粘貼需要從中提取數據的網址
www.bseindia.com/download/BhavCopy/Equity/EQ140316_CSV.ZIP
因此,“ Equity /”之后的字符串需要驗證,因為它包含日期。 如何在php中建立一個函數。這將是一個很大的幫助。 提前致謝
這是我要遵循的代碼,
<?php
$url = 'http://www.bseindia.com/download/BhavCopy/Equity/EQ140316_CSV.ZIP';
if ( preg_match("/\/EQ\d{6}_CSV\.ZIP/", $url, $matches)) {
$path = '/upload/';
$headers = getHeaders($url);
if ($headers['http_code'] === 200 and $headers['download_content_length'] < 1024*1024) {
if (download($url, $path)){
echo 'Download complete!';
}
}
}
/**
* Get Headers function
* @param str #url
* @return array
*/
function getHeaders($url)
{
$ch = curl_init($url);
curl_setopt( $ch, CURLOPT_NOBODY, true );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, false );
curl_setopt( $ch, CURLOPT_HEADER, false );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_MAXREDIRS, 3 );
curl_exec( $ch );
$headers = curl_getinfo( $ch );
curl_close( $ch );
return $headers;
}
/**
* Download
* @param str $url, $path
* @return bool || void
*/
function download($url, $path)
{
# open file to write
$fp = fopen ($path, 'w+');
# start curl
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
# set return transfer to false
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, false );
curl_setopt( $ch, CURLOPT_BINARYTRANSFER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
# increase timeout to download big file
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
# write data to local file
curl_setopt( $ch, CURLOPT_FILE, $fp );
# execute curl
curl_exec( $ch );
# close curl
curl_close( $ch );
# close local file
fclose( $fp );
if (filesize($path) > 0)
return true;
}
?>
您可以使用preg_match:
preg_match('/EQ([0-9]+)_/'), $url, $matches);
$date = $matches[1];
要每天運行一個cron來執行此操作,您只需要在shell上鍵入crontab -e
。
以下是每天凌晨4點運行的cronline示例:
0 4 * * * php /home/user/website/bin/your_script.php
# leave an empty line on the bottom of the crontab
在此處找到幫助: http : //www.thegeekstuff.com/2011/07/php-cron-job/
試試這個功能:
function containsDate($url){
preg_match("/\/EQ\d{6}_CSV\.ZIP/", $url, $matches);
return !empty($matches[0]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.