简体   繁体   中英

Echo PHP inside of string

I am running a simple chat application and it's powered by a process.php file, but the chat is on chat.php.

Basically people can search for a "Topic", and it'll take them to domain.tld/chat.php?topic=topicname (topicname being whatever they searched for)

I need my process.php file to echo

 <?php echo $_GET['topic']; ?>.txt 

instead of chat.txt, so that each topic has a unique text file (so that all chats aren't linked)

This is my process.php file:

<?php

$function = $_POST['function'];

$log = array();

switch($function) {

     case('getState'):
         if(file_exists('logs/chat.txt')){
           $lines = file('logs/chat.txt');
         }
         $log['state'] = count($lines); 
         break; 

     case('update'):
        $state = $_POST['state'];
        if(file_exists('logs/chat.txt')){
           $lines = file('logs/chat.txt');
         }
         $count =  count($lines);
         if($state == $count){
             $log['state'] = $state;
             $log['text'] = false;

             }
             else{
                 $text= array();
                 $log['state'] = $state + count($lines) - $state;
                 foreach ($lines as $line_num => $line)
                   {
                       if($line_num >= $state){
                     $text[] =  $line = str_replace("\n", "", $line);
                       }

                    }
                 $log['text'] = $text; 
             }

         break;

     case('send'):
      $nickname = htmlentities(strip_tags($_POST['nickname']));
         $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
          $message = htmlentities(strip_tags($_POST['message']));
     if(($message) != "\n"){

         if(preg_match($reg_exUrl, $message, $url)) {
            $message = preg_replace($reg_exUrl, '<a href="'.$url[0].'" target="_blank">'.$url[0].'</a>', $message);
            } 

            $message = preg_replace('/#(\w+)/', ' <a href="@$1" target="_blank">#$1</a>', $message);


         fwrite(fopen('logs/chat.txt', 'a'), "<span>". $nickname . "</span>" . $message = str_replace("\n", " ", $message) . "\n"); 
     }
         break;

}

echo json_encode($log);

?>

This is my chat.js file

/* 
Created by: Kenrick Beckett

Name: Chat Engine
*/

var instanse = false;
var state;
var mes;
var file;

function Chat () {
this.update = updateChat;
this.send = sendChat;
this.getState = getStateOfChat;
}

//gets the state of the chat
function getStateOfChat(){
if(!instanse){
     instanse = true;
     $.ajax({
           type: "POST",
           url: "process.php",
           data: {  
                    'function': 'getState',
                    'file': file
                    },
           dataType: "json",

           success: function(data){
               state = data.state;
               instanse = false;
           },
        });
}    
}

//Updates the chat
function updateChat(){
 if(!instanse){
     instanse = true;
     $.ajax({
           type: "POST",
           url: "process.php",
           data: {  
                    'function': 'update',
                    'state': state,
                    'file': file
                    },
           dataType: "json",
           success: function(data){
               if(data.text){
                    for (var i = 0; i < data.text.length; i++) {
                        $('#chat-area').append($("<p>"+ data.text[i] +"</p>"));
                    }                                 
               }
               document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
               instanse = false;
               state = data.state;
           },
        });
 }
 else {
     setTimeout(updateChat, 1500);
 }
}

//send the message
function sendChat(message, nickname)
{       
updateChat();
 $.ajax({
       type: "POST",
       url: "process.php",
       data: {  
                'function': 'send',
                'message': message,
                'nickname': nickname,
                'file': file
             },
       dataType: "json",
       success: function(data){
           updateChat();
       },
    });
   }

In theory this should create a unique topicname.txt file in /logs/ whenever somebody starts chatting in a topic that's nonexistent. I'm just having trouble adding the topicname in place of chat.txt in process.php. So far I know that it does create a chat.txt file by itself, so it should create a unique .txt file once I echo it correctly.

Also, I'm aware that a database is a better option when compared to storing messages in unique .txt files, but this is how I want to do it.

Here's an example of how I was trying to add it to my process.php a snippet from process.php)

 case('getState'):
         if(file_exists('logs/<?php echo $_GET['topic']; ?>.txt')){
           $lines = file('logs/<?php echo $_GET['topic']; ?>.txt');
         }

^ That probably isn't even the right format, as I'm new to PHP and make tons of mistakes, and it probably won't know what the GET is because it's not a part of chat.php ... it's a separate file.

Try with -

'logs/' . $filename . '.txt'

where ever you want.

Update

if (!empty($_GET['topic'])) {
    $filename = $_GET['topic'];
} else {
    $filename = 'something else';
}

 if(file_exists('logs/' . $filename . '.txt')){ $lines = file('logs/' . $filename . '.txt') ....

It is already in php. So no need to add <?php ?> and echo . Just simply concatenate them.

you are already in php tag.. no need to add extra php tags

case('getState'):
    if(file_exists("logs/".$_GET['topic'].".txt")){
    $lines = file("logs/".$_GET['topic'].".txt");
}

or Try this

case('getState'):
   if(isset($_GET['topic']){
       $filename = "logs/".$_GET['topic'].".txt";
        if(file_exists($filename)){
            $lines = file($filename);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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