2013-06-11 212 views
0

我有2個PHP文件:index.php和search_server.php。 我需要從index.php文件訪問$ pilihdomain,然後用在search_server.php,在此線$resp = $uclassify->classify($tweet['text'], $pilihdomain, 'herlambangp');PHP - 如何從其他文件訪問其他變量?

最後一天,我使用需要昂全局變量,但它似乎是錯誤的。 在此先感謝。

//index.php

<head> 
    <title>Twitter Search</title> 
    <link href="search_client.css" type="text/css" rel="stylesheet" /> 
    <link href="tweet.css" type="text/css" rel="stylesheet" /> 
    <script src="jquery.min.js"></script> 
    <script src="search_client.js"></script> 
</head> 
<body> 
    <div id="search_box"> 
    <h1>Twitter Search</h1> 
    <input name="search_terms" autofocus="autofocus"/>  
<?php 
$dbHost = "localhost"; 
$dbUser = "root"; 
$dbPass = ""; 
$dbname = "skripsi"; 
$db = mysql_connect($dbHost,$dbUser,$dbPass); 
mysql_select_db($dbname,$db); 
$sql = mysql_query("SELECT * FROM namaklasifier"); 
while($row = mysql_fetch_array($sql)) { 
    $clsfr = $row['username']; 
    $sql = mysql_query("SELECT * FROM namaklasifier"); 
     echo '<select name="cmake" autofocus width="10">'; 
     echo '<option value="0">-Pilih Domain Klasifikasi-</option>'; 
     while($row = mysql_fetch_array($sql)) { 
      echo '<option ' . ($clsfr==$row['username']) . ' value="'.$row['username'].'">'.$row['username'].'</option>'; 
    } 
    echo '</select>'; 
} 
?> 
    <?php 
$pilihdomain=$_POST['cmake']; 
    ?> 

//search_server.php

<?php 
if (!empty($_GET['q'])) { 

    // Remove any hack attempts from input data 
    $search_terms = htmlspecialchars($_GET['q']).' -smartfrencare -siapkan -klaim'; 

    // Get the application OAuth tokens 
    require 'app_tokens.php'; 
    require_once("uClassify.php"); 
    $uclassify = new uClassify(); 
    // Set these values here 
    $uclassify->setReadApiKey('8DvvfxwKPdvjgRSrtsTSOawmQ0'); 
    $uclassify->setWriteApiKey('v4Us59yQFhf9Z0nGrQsrTtzBI5k'); 
// global $nilainet; 
// global $nilaineg; 
// global $nilaipos; 

    // Create an OAuth connection 
    require 'tmhOAuth.php'; 

    $connection = new tmhOAuth(array(
     'consumer_key' => $consumer_key, 
     'consumer_secret' => $consumer_secret, 
     'user_token'  => $user_token, 
     'user_secret'  => $user_secret 
    )); 

    // Request the most recent 100 matching tweets 
    $http_code = $connection->request('GET',$connection->url('1.1/search/tweets'), 
      array('q' => $search_terms, 
       'count' => 50, 
       'lang' => 'in', 
       'locale' => 'jakarta', 
       'type' => 'recent')); 

    // Search was successful 
    if ($http_code == 200) { 

     // Extract the tweets from the API response 
     $response = json_decode($connection->response['response'],true); 
     $tweet_data = $response['statuses']; 

     // Load the template for tweet display 
     $tweet_template= file_get_contents('tweet_template.html'); 

     // Load the library of tweet display functions 
     require 'display_lib.php'; 

     // Create a stream of formatted tweets as HTML 
     $tweet_stream = ''; 
     foreach($tweet_data as $tweet) { 

      // Ignore any retweets 
      if (isset($tweet['retweeted_status'])) { 
       continue; 
      } 
      // Get a fresh copy of the tweet template 
      $tweet_html = $tweet_template; 


      $resp = $uclassify->classify($tweet['text'], $pilihdomain, 'herlambangp');    
      $value = print_r($resp,true) ;   
      // Insert this tweet into the html 
      $tweet_html = str_replace('[screen_name]',$tweet['user']['screen_name'],$tweet_html); 
      $tweet_html = str_replace('[name]', $tweet['user']['name'],$tweet_html);   
      $tweet_html = str_replace('[profile_image_url]',$tweet['user']['profile_image_url'],$tweet_html); 
      $tweet_html = str_replace('[tweet_id]', $tweet['id'],$tweet_html); 
      $tweet_html = str_replace('[tweet_text]',linkify($tweet['text']),$tweet_html); 
      $tweet_html = str_replace('[tweet_class]',$value,$tweet_html); 
      $tweet_html = str_replace('[created_at]',twitter_time($tweet['created_at']),$tweet_html); 
      $tweet_html = str_replace('[retweet_count]',$tweet['retweet_count'],$tweet_html);   

      // Add the HTML for this tweet to the stream 
      $tweet_stream .= $tweet_html; 
     } 

     // Pass the tweets HTML back to the Ajax request 
     print $tweet_stream; 

    // Handle errors from API request 
    } else { 
     if ($http_code == 429) { 
      print 'Error: Twitter API rate limit reached'; 
     } else { 
      print 'Error: Twitter was not able to process that search'; 
     } 
    } 

} else { 
    //not implement anything 
} 

?> 
+0

不推薦使用'MySQL'函數,您可以使用'MySQLi'或(甚至更好的IMO)''PDO'函數。此外,嘗試將您的PHP邏輯從HTML中分離出來。 (Google:'關注點分離) –

+0

[您的代碼存在XSS漏洞。](https://en.wikipedia.org/wiki/Cross-site_scripting) – PeeHaa

+0

Hi @Luttekes,我必須更改MySql命令庫MySQLi?是所有?我的案例的任何例子?謝謝。 –

回答

2

你應該包含您在全局變量需要一個外部 「配置」 或 「設置」 文件的現場。然後,將該外部文件包含在所有需要這些配置設置的頁面中。

除了pilihdomain,我把你的數據庫設置爲你的這個文件,因爲你真的應該做這些共享設置,而不是在每個需要它們的腳本中重新定義它們。

的settings.php

<?php 
$dbHost = "localhost"; 
$dbUser = "root"; 
$dbPass = ""; 
$dbname = "skripsi"; 
$pilihdomain = isset($_POST['cmake']) ? $_POST['cmake'] : ''; 

的index.php

<?php require_once('settings.php'); ?> 
<head> 
    <title>Twitter Search</title> 
    <link href="search_client.css" type="text/css" rel="stylesheet" /> 
    <link href="tweet.css" type="text/css" rel="stylesheet" /> 
    <script src="jquery.min.js"></script> 
    <script src="search_client.js"></script> 
</head> 
<body> 
    <div id="search_box"> 
    <h1>Twitter Search</h1> 
    <input name="search_terms" autofocus="autofocus"/>  
<?php 
$db = mysql_connect($dbHost,$dbUser,$dbPass); 
mysql_select_db($dbname,$db); 
$sql = mysql_query("SELECT * FROM namaklasifier"); 
while($row = mysql_fetch_array($sql)) { 
    $clsfr = $row['username']; 
    $sql = mysql_query("SELECT * FROM namaklasifier"); 
     echo '<select name="cmake" autofocus width="10">'; 
     echo '<option value="0">-Pilih Domain Klasifikasi-</option>'; 
     while($row = mysql_fetch_array($sql)) { 
      echo '<option ' . ($clsfr==$row['username']) . ' value="'.$row['username'].'">'.$row['username'].'</option>'; 
    } 
    echo '</select>'; 
} 
?> 

search_server.php

<?php require_once('settings.php'); ?> 
<?php 
if (!empty($_GET['q'])) { 

    // Remove any hack attempts from input data 
    $search_terms = htmlspecialchars($_GET['q']).' -smartfrencare -siapkan -klaim'; 

    // Get the application OAuth tokens 
    require 'app_tokens.php'; 
    require_once("uClassify.php"); 
    $uclassify = new uClassify(); 
    // Set these values here 
    $uclassify->setReadApiKey('8DvvfxwKPdvjgRSrtsTSOawmQ0'); 
    $uclassify->setWriteApiKey('v4Us59yQFhf9Z0nGrQsrTtzBI5k'); 
// global $nilainet; 
// global $nilaineg; 
// global $nilaipos; 

    // Create an OAuth connection 
    require 'tmhOAuth.php'; 

    $connection = new tmhOAuth(array(
     'consumer_key' => $consumer_key, 
     'consumer_secret' => $consumer_secret, 
     'user_token'  => $user_token, 
     'user_secret'  => $user_secret 
    )); 

    // Request the most recent 100 matching tweets 
    $http_code = $connection->request('GET',$connection->url('1.1/search/tweets'), 
      array('q' => $search_terms, 
       'count' => 50, 
       'lang' => 'in', 
       'locale' => 'jakarta', 
       'type' => 'recent')); 

    // Search was successful 
    if ($http_code == 200) { 

     // Extract the tweets from the API response 
     $response = json_decode($connection->response['response'],true); 
     $tweet_data = $response['statuses']; 

     // Load the template for tweet display 
     $tweet_template= file_get_contents('tweet_template.html'); 

     // Load the library of tweet display functions 
     require 'display_lib.php'; 

     // Create a stream of formatted tweets as HTML 
     $tweet_stream = ''; 
     foreach($tweet_data as $tweet) { 

      // Ignore any retweets 
      if (isset($tweet['retweeted_status'])) { 
       continue; 
      } 
      // Get a fresh copy of the tweet template 
      $tweet_html = $tweet_template; 


      $resp = $uclassify->classify($tweet['text'], $pilihdomain, 'herlambangp');    
      $value = print_r($resp,true) ;   
      // Insert this tweet into the html 
      $tweet_html = str_replace('[screen_name]',$tweet['user']['screen_name'],$tweet_html); 
      $tweet_html = str_replace('[name]', $tweet['user']['name'],$tweet_html);   
      $tweet_html = str_replace('[profile_image_url]',$tweet['user']['profile_image_url'],$tweet_html); 
      $tweet_html = str_replace('[tweet_id]', $tweet['id'],$tweet_html); 
      $tweet_html = str_replace('[tweet_text]',linkify($tweet['text']),$tweet_html); 
      $tweet_html = str_replace('[tweet_class]',$value,$tweet_html); 
      $tweet_html = str_replace('[created_at]',twitter_time($tweet['created_at']),$tweet_html); 
      $tweet_html = str_replace('[retweet_count]',$tweet['retweet_count'],$tweet_html);   

      // Add the HTML for this tweet to the stream 
      $tweet_stream .= $tweet_html; 
     } 

     // Pass the tweets HTML back to the Ajax request 
     print $tweet_stream; 

    // Handle errors from API request 
    } else { 
     if ($http_code == 429) { 
      print 'Error: Twitter API rate limit reached'; 
     } else { 
      print 'Error: Twitter was not able to process that search'; 
     } 
    } 

} else { 
    //not implement anything 
} 

?> 
+0

對不起,遲到的迴應,我會盡快嘗試你的建議。謝謝:) –

+0

嗨@Steven,我已經嘗試了代碼,但$ pilihdomain還沒有訪問,但這是錯誤味精「致命錯誤:未捕獲的異常'uClassifyException'帶有消息'文本應如何分類?沒有ClassiferName似乎指定!「在C:\ xampp \ htdocs \ kejar \ code \ uClassify.php:107堆棧跟蹤:#0 C:\ xampp \ htdocs \ kejar \ code \ search_server.php(62):uClassify-> classify(',,, lah myn ,,,「@ ...',NULL,'herlambangp')#1 {main}拋出C:\ xampp \ htdocs \ kejar \ code \ uClassify.php在第107行」 –

+0

@herlambangpermadi - 這個錯誤很可能由於沒有發佈數據來設置'$ pilihdomain.',所以我修改了上面的回答,如果沒有設置'$ _POST ['cmake']',將'$ pilihdomain'設置爲空字符串('') –

-2

使用會話變量。 他們很容易設置,他們可以跨頁面使用它們。

+0

嗨,有什麼例子在我的問題案例中使用會話? –

+0

你的例子中有很多代碼,所以我要避免給你的代碼提供一個例子。然而,這篇文章應該解釋你需要知道的有關會話變量的一切:http://w3schools.com/php/php_sessions.asp .as我說過,這些很容易設置,它值得理解它們是如何工作的,而不是我只是寫解決方案。教一個人釣魚等等。 –