2014-04-11 127 views
0

好後,得到幾乎每一件事情的工作在我的代碼laravel 4.1驗證URL輸入

和不錯

我需要幫助有關如何驗證用戶的URL輸入

,如果他沒有插入非網址如何將其前言404頁

,這裏是我的路線文件

Route::get('/', function() 
{ 
    return View::make('hello');  
}); 

Route::post('/', function() 
{ 
$url = Input::get('url'); 
$record = Url::where('urls', '=', $url)->first(); 
if ($record) { 
    return View::make('result') 
    ->with('shortend', $record->shortend); 
} 

function get_uniqe_short_url() 
{ 

    $shortend = base_convert(rand(1000,99999), 10, 36); 
    if (Url::where('shortend', '=' ,$shortend)->first()){ 
     get_uniqe_short_url(); 
    } 
    return $shortend; 
} 
$shortend = get_uniqe_short_url(); 

// otherwise add new row and return shortned url 
$row = new URl; 
    $row->urls = $url; 
    $row->shortend = $shortend; 
    $row->save(); 

// create a results view and present the short url to the usr 

if ($row){ 
    return View::make('result')->with('shortend',$shortend); 
} 
}); 


Route::get('{shortend}', function($shortend) 
    { 
    // query the DB For the row with that short url 
     $row = Url::where('shortend', '=', $shortend)->first(); 
    // if not found redirect to home page 
     if (is_null($row)) return Redirect::to('/'); 
    // else grab the url and redirect 
     return Redirect::to($row->urls); 

    }); 

原諒我的許多問題,但我是全新的laravel

回答

0

首先,作爲提示,您的routes.php中有這樣的邏輯。 URL路由器旨在接收HTTP請求並將它們「路由」到正確的控制器和方法。請參閱the documentation以開始使用控制器。

我從來不是「重定向到404頁面」的粉絲,而是我相信如果找不到頁面,它應該在那裏顯示404頁面。要使用laravel執行此操作,可以調用App::abort(404);,這將終止應用程序並返回404狀態給瀏覽器。您可以通過「聽」到404錯誤,並返回自己的自定義視圖藉此更進一步:

App::missing(function() 
{ 
    return View::make('errors/404'); 
}); 

讓我知道如果你需要更多的幫助,驗證一個URL,但我想你應該重組代碼開始通過使用控制器。您可以檢查this question以獲取正則表達式以匹配網址。這是你如何在PHP中使用正則表達式:

if(!preg_match('/expression/', $url)) { 
    App::abort(404); 
} 
+0

感謝您的幫助,現在我會嘗試,我也會在那個網址,你給我,謝謝你幫我 我會回來的,一旦正如我從測試代碼所做的那樣 – Jone

+0

讓我知道它是如何去的,我可以繼續提出問題的建議。 – Sam

+0

好山姆 對不起,我遲到重播,但我有我的辦公室裏這麼多的工作 我將重播其今天 – Jone