PHP - 如何从另一个文件访问其他变量?

时间:2013-06-11 23:58:09

标签: php variables get

我有2个php文件:index.php和search_server.php。 我需要从index.php访问$ pilihdomain,然后在search_server.php中使用它,在这一行$resp = $uclassify->classify($tweet['text'], $pilihdomain, 'herlambangp');

最后一天,我使用了必需的全局变量,但似乎错了。 提前谢谢。

//的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
}   

?>

2 个答案:

答案 0 :(得分:2)

您应该有一个外部“配置”或“设置”文件,其中包含您网站中全局所需的变量。然后,在需要这些配置设置的所有页面中包含该外部文件。

除了pilihdomain之外,我还将db设置放在此文件中,因为您确实应该创建这些共享设置,而不是在需要它们的每个脚本中重新定义它们。

<强>的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
}   

?>

答案 1 :(得分:-2)

使用会话变量。 它们非常容易设置,您可以跨页面使用它们。