How to use Php if statement when shortcode returns empty in WP

For all my AFC fields I’m using a php if statement so that if the field is empty, the entire section containing the field data won’t be loaded, for example:

                <?php if( get_field('client_intro') ): ?>
                <section id="client-intro">
                    <div class="wrapper">
                        <p><?php echo get_field('client_intro'); ?></p> 
                    </div>      
                </section>
                <?php endif; ?>

I wanted to do the same thing with a section that contains shortcode data but I can’t figure out what to use. The shortcode is used by a plugin that displays posts, so I tried this (and many others):

             <?php if( have_posts() ): ?>   
             <section id="client-posts">
                 <div class="wrapper">
                 <?php echo do_shortcode('[display-posts posts_per_page="10"]'); ?>
                 </div> 
             </section>
             <?php endif; ?>

Nothing works, the section still loads even without posts. Simply speaking I only want the #client-posts section to load if there are posts, if no posts, don’t load.

php failed to call curl command

I want to get the data from a curl command in php for further processing.

I am facing an issue with the code when I use it in php. The curl command looks good for me when I run it in the system.

My code is as follows:

<?php

function getJsonFromUrl($urlString) {
    $urlData = shell_exec('curl --silent --request GET --url '' . $urlString . '' --user 'root:password' --header 'Accept: application/json'');
    $jsonData = json_decode($urlData, true);
    return $jsonData;
}

$data = array(
    'id' => '',
    'parent' => '',
    'issueId' => '1931461',
    'issueType' => ''
);

$url = "https://jira.myorg.com/rest/dev-status/1.0/issue/detail?issueId={$data['issueId']}&applicationType=stash&dataType=repository";
$jsonData = getJsonFromUrl($url);
?>

I am getting the following errors:

‘applicationType’ is not recognized as an internal or external
command,
operable program or batch file.

‘dataType’ is not recognized as an internal or external command,
operable program or batch file.

Deprecated: json_decode(): Passing null to parameter #1 ($json) of
type string is deprecated in C:UsersAdministratorDocumentstest.php
on line 4

Please help me with it

How to integrate filament to existing API app

I have a production ready API with laravel 11 and I want to integrate filament for some pretty views, but I want to integrate filament (create,update,list) with my existing API and not to default filament CRUD operation directly with models. For example I want to send create submit form to my API
p.s

Route::post('/teachers', [TeacherController::class, 'store']);

and edit to

Route::put('/teachers/{id}', [TeacherController::class, 'update']);

How can I integrate it ?

Thanks you anyway!

I use filament for the first time and I have no idea how to customize filament with existing API endpoints

Passing dynamic component data Laravel

so i new in laravel, i have a table of products lists and i added a delete button and when i click it, it show a basic yes/no modal.

so my problem is when i try to pass url dan id data to my modal component, i already put my modal component inside a @forEach loop but for some reason when i log the the id data inside the modal component it only shows the first data id in every product and not showing other id when i click another product

this is my index.blade.php where i call modal component

    @foreach ($products as $product)
                        <tr
                            class="odd:bg-white odd:dark:bg-gray-900 even:bg-gray-50 even:dark:bg-gray-800 border-b dark:border-gray-700">
                            <td scope="row" class="px-6 py-4">{{ $loop->iteration }}</td>
                            <th scope="row"
                                class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
                                {{ $product->name }}
                            </th>
                            <td class="px-6 py-4">
                                {{ $product->color }}
                            </td>
                            <td class="px-6 py-4">
                                {{ $product->category->name }}
                            </td>
                            <td class="px-6 py-4">
                                Rp {{ number_format($product->unit_price, 0, ',', '.') }}
                            </td>
                            <td class="px-6 py-4 flex space-x-2">

                                <a href="/dashboard/products/{{ $product->name }}/edit" class="">
                                    <i class="bi bi-pencil-square"></i>
                                </a>
                                <x-modal url="/dashboard/products/" :id="$product->id" />

                                <button data-modal-target="popup-modal" data-modal-toggle="popup-modal"><i
                                        class="bi bi-x-circle"></i></button>
                            </td>
                        </tr>
                    @endforeach

this is my Modal class component

<?php

namespace AppViewComponents;

use IlluminateContractsViewView;
use IlluminateViewComponent;

class Modal extends Component
{
    /**
     * Create a new component instance.
     */
    public function __construct(
        public string $url,
        public string $id,
    ) {
        //
    }

    /**
     * Get the view / contents that represent the component.
     */
    public function render(): View
    {
        return view('components.modal');
    }
}

and my modal component just like this

          {{ $url }}{{ $id }}

any ideas?

Is there a way I can fix one side conversation in LARAVEL chatbot?

Following is the code. where in user is welcomed. its ID is verified and name & class is fetched from db. After class selection selected class displayed on same side rather I want it to display on right.

public function getUser(){

    $user = DB::table('users')->where('uid','=',20230005210)->first();
    
    
    if(!empty($user)){
        $this->say("Hi " . $user->name . " ( ID:". $user->uid .")...");
        $this->say("Welcome ENO!!");
        $this->couSelect($user->class);
        $this->couSelect($user->class);
        session(['uid' => $user->uid]);
        session(['class' => $user->class]);
    }else{
     
        $this->say("Sorry, Not Verified");
    }
}

public function getUserData(){

    $userData= new stdClass;
    $this->ask("Enter ID",function(Answer $answer)use ($userData){
        $this->name = $answer->getText();
            

            $this->selectClass();

            
        });
  
}

public function verifyUser($userdata){
   
    $moodleData =Http::post("http://localhost/......=". $userdata->name)->json();
    
    if(!empty($moodleData["users"])){
        $m_username = $moodleData["users"][0]["username"];
        $m_firstname = $moodleData["users"][0]["firstname"];
        $m_fullname = $moodleData["users"][0]["fullname"];
        $this->curr_username = $m_username;
        $this->curr_userclass = $userdata->class;


        $this->say("Hi.. " . $m_firstname . " (User ID:". $m_username .")...");
    
        $this->say("Welcome!!");
       
        $this->courseSelect( $this->curr_userclass);
        session(['uid' =>  $this->curr_username]);
        session(['class' => $this->curr_userclass]);
    }else{
        
        $this->say("Sorry, Not Verified");
    }

}

public function getUserID(){
    $user = DB::table('students')->where('uid','=',2022005332)->first();
    return $user->id;
}

public function selectClass(){

    $question = Question::create('Select Class')
                ->callbackId('class_select')
                ->addButtons([
                    Button::create('V')->value('V'),
                    Button::create('IV')->value('IV'),
                    Button::create('VI')->value('VI'),
                ]);

    $this->ask($question, function(Answer $answer) {
            
      
            if ($answer->isInteractiveMessageReply()) {
                $this->selectedClass = $answer->getValue();
                session(['class' => $this->selectedClass]);

                $this->say("Class Selected: " . $this->selectedClass);
                $this->checkUser();
            }

    });
}


public function checkUser(){
    $user = DB::table('users')->where([
        ['uid','=',$this->name],
        ['class', '=', $this->selectedClass],
        ])->first();
            
            if(!empty($user)){
               
                $this->say("Hi " . $user->name . " ( ID:". $user->uid .")... Welcome !!");
               
                $this->courseSelect($user->class);
                session(['uid' => $user->uid]);
                session(['class' => $user->class]);
            }else{
                // $this->typesAndWaits(1);
                $this->say("Did Not Verified");
            }
}
public function courseSelect($class){

    $course = DB::table('course')->where('class','=',$class)->get();


    $question = Question::create("Select Course:")->callbackId('course_select');

    foreach($course as $c){
       $question->addButtons([
            Button::create($c->curriculum)->value($c->course_id)
       ]);
    }

    $this->ask($question, function (Answer $answer){
       
        if ($answer->isInteractiveMessageReply()) {
            $selectedCourseID = $answer->getValue();
            session(['courseID' => $selectedCourseID]);

           
            $this->selectedCourseID = $selectedCourseID;//storing the course id globally
          

            $courseSelected = DB::table('course')->where('course_id','=',$selectedCourseID)->first();

            $this->courseName = $courseSelected->curriculum;
            $this->say("Course Selected: " . $this->courseName);
            $this->selectChapterRange($selectedCourseID);
        }
    });
}

public function selectChapterRange($selectedCourseID){

    $question = Question::create('Select Chapter Range')
                ->callbackId('chapter_range_select')
                ->addButtons([
                    Button::create('Chapter 1 - 6')->value('Chapter 1 - 6'),
                    Button::create('Chapter 7 - 12')->value('Chapter 7 - 12'),
                   
                ]);

    $this->ask($question, function(Answer $answer) {
            

            if ($answer->isInteractiveMessageReply()) {
                $this->selectedChapterRange = $answer->getValue();
                // session(['class' => $this->selectedClass]);

                $this->say("Selected Range: " . $this->selectedChapterRange);
                // $this->checkUser();

                if($this->selectedChapterRange === "Chapter 1 - 6"){
                    // $this->typesAndWaits(1);
                    $this->chapterSelect($this->selectedCourseID, 1, 6);  
                }elseif($this->selectedChapterRange === "Chapter 7 - 12"){
                    $this->chapterSelect($this->selectedCourseID, 7, 12);
                
                }else{
            }
        }

    });
}`

enter image description here
Initially the conversation looks sender and receiver.
Later it comes on one side only

enter image description here

Plz help.

Php8.1-pgsql package is not found

I am trying to create a docker compose image file with php8.1, but I am getting this error.

I am trying to build image for Laravel server. I have tried running the Dockerfile as root as well.

How can I fix this, turns out php8.1 uses Debian base image.

I have tried

  • using www-user from base image and then its says permissions error
  • using root user I get package not found error. But in ubuntu server that i am using I am finding the package from apt.
  • If I try to add php apt repository it bring up error of public key
FROM serversideup/php:8.1-fpm-nginx

ENV SSL_MODE "off"

USER root

RUN add-apt-repository ppa:ondrej/php
RUN apt update

RUN apt-get install -y --no-install-recommends git curl wget php8.1-pgsql libxrender1 cron fonts-freefont-ttf  
    && apt autoclean && apt autoremove 
    && rm -rf /tmp/* /var/tmp/* /usr/share/doc/*

USER www-data

COPY --chown=webuser:webgroup . /var/www/html/

RUN composer install
RUN composer du
RUN chown -R webuser:webgroup .

RUN chmod +x ./scripts/start.sh
RUN sh ./scripts/start.sh

ubuntu@ip-172-31-0-58:~/Morgenland-Search-Backend$ sudo docker compose -f docker-compose-prod.yml up -d --build
[+] Building 3.5s (6/12)                                                                                                                                                                         docker:default
 => [app internal] load build definition from Dockerfile.prod                                                                                                                                              0.0s
 => => transferring dockerfile: 523B                                                                                                                                                                       0.0s
 => [app internal] load .dockerignore                                                                                                                                                                      0.0s
 => => transferring context: 2B                                                                                                                                                                            0.0s
 => [app internal] load metadata for docker.io/serversideup/php:8.1-fpm-nginx                                                                                                                              0.4s
 => CACHED [app 1/8] FROM docker.io/serversideup/php:8.1-fpm-nginx@sha256:812c9d05672415f88b0d9ec7a871d50f30c6a8bfae6ea01f6da363c0bc822c38                                                                 0.0s
 => [app internal] load build context                                                                                                                                                                      0.2s
 => => transferring context: 321.85kB                                                                                                                                                                      0.2s
 => ERROR [app 2/8] RUN apt update     && apt install -y --no-install-recommends git curl wget php8.1-pgsql libxrender1 cron fonts-freefont-ttf      && apt autoclean && apt autoremove     && rm -rf /tm  3.1s
------
 > [app 2/8] RUN apt update     && apt install -y --no-install-recommends git curl wget php8.1-pgsql libxrender1 cron fonts-freefont-ttf      && apt autoclean && apt autoremove     && rm -rf /tmp/* /var/tmp/* /usr/share/doc/*:
0.300
0.300 WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
0.300
0.329 Get:1 http://deb.debian.org/debian bookworm InRelease [151 kB]
0.330 Get:2 http://nginx.org/packages/debian bookworm InRelease [2860 B]
0.338 Get:3 http://deb.debian.org/debian bookworm-updates InRelease [55.4 kB]
0.338 Get:4 http://deb.debian.org/debian-security bookworm-security InRelease [48.0 kB]
0.391 Get:5 http://nginx.org/packages/debian bookworm/nginx amd64 Packages [7975 B]
0.463 Get:6 http://deb.debian.org/debian bookworm/main amd64 Packages [8786 kB]
0.539 Get:7 http://deb.debian.org/debian bookworm-updates/main amd64 Packages [13.8 kB]
0.585 Get:8 http://deb.debian.org/debian-security bookworm-security/main amd64 Packages [158 kB]
1.409 Fetched 9223 kB in 1s (8465 kB/s)
1.409 Reading package lists...
2.004 Building dependency tree...
2.164 Reading state information...
2.190 5 packages can be upgraded. Run 'apt list --upgradable' to see them.
2.195
2.195 WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
2.195
2.198 Reading package lists...
2.780 Building dependency tree...
2.932 Reading state information...
2.958 E: Unable to locate package php8.1-pgsql
2.958 E: Couldn't find any package by glob 'php8.1-pgsql'
------
failed to solve: process "/bin/sh -c apt update     && apt install -y --no-install-recommends git curl wget php8.1-pgsql libxrender1 cron fonts-freefont-ttf      && apt autoclean && apt autoremove     && rm -rf /tmp/* /var/tmp/* /usr/share/doc/*" did not complete successfully: exit code: 100

Set WooCommerce orders as cancelled NOT failed when a payment doesn’t go through

Basically, I am using WooCommerce with YITH Booking and whenever a failed payment happens, it creates a booking slot with the “failed” status, but this booking slot then becomes not-bookable.

So to avoid this, I would like to automatically create “cancelled” booking statuses instead of “failed” so if someones payment doesnt work, it the order status goes straight to “cancelled”

I’ve looked for custom php snippets but currently cannot find anything sufficient.

Fetching data from a page which i’m not the owner of

I find the Facebook developers API documentation a bit confusing.
I’m building a small app using PHP and I would like to fetch/scrape data from a page which isn’t belong to me.

is it possible using the API or i will need to scrape the data manually?
If it’s possible, is it possible if i’m not the owner of the page as well?

Implement redirect in the webhook response

probably very simple question, but having no knowledge, it remains difficult for me to implement this thing in my project.

I have a custom webhook, implemented on WordPress, which allows me to receive responses from Apple, based on in-app purchases.

The webhook works, correctly receives and saves all the requested values.

The only problem remains the redirect.

Below they explained to me that I should load the load_url, to be able to redirect the user to the desired page at the end of the purchase in the app.

this is my code:

Front end:

– I call my product to purchase using a js function, where there is product_id and user_email:

<button onclick="twinr_iap_purchase('PRODUCT_ID','EMAIL_USER')">Product</button>

when pressed, the entire applem flow opens which allows me to make the purchase correctly.

Backend:

– webhook data, which I receive perfectly:

// Definizione dell'azione per il webhook
function custom_webhook_action() {
    // Controlla se la richiesta è una richiesta POST
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Ottieni i dati inviati con la richiesta
        $data = json_decode(file_get_contents('php://input'), true);

        // Verifica se sono presenti i dati richiesti
        if (isset($data['twinr_product_id']) && isset($data['store_product_id']) && isset($data['platform']) && isset($data['purchase_token']) && isset($data['success']) && isset($data['user_info'])) {
            // Esegui qui le azioni necessarie con i dati ricevuti dal webhook
            // Ad esempio, puoi salvare i dati nel database, inviare notifiche, ecc.

            // Esempio: Salvataggio dei dati nel database
            global $wpdb;

            // Estrai i dati dalla richiesta
            $twinr_product_id = $data['twinr_product_id'];
            $store_product_id = $data['store_product_id'];
            $platform = $data['platform'];
            $purchase_token = $data['purchase_token'];
            $success = $data['success'];
            $user_info = $data['user_info'];

            // Prepara il messaggio di log per la risposta
            $response_message = "Funzione twinr_iap_purchase chiamata per il prodotto Twinr con ID: $twinr_product_id";

            // Prepara i dati per l'inserimento nel database
            $data_to_insert = array(
                'twinr_product_id' => $twinr_product_id,
                'store_product_id' => $store_product_id,
                'platform' => $platform,
                'purchase_token' => $purchase_token,
                'success' => $success,
                'user_info' => $user_info,
                'response' => $response_message, // Messaggio di log inserito nel campo response
            );

            // Esegui l'inserimento dei dati nella tabella del database
            $wpdb->insert('swh_tlk_webhook_requests', $data_to_insert);

            // Ottieni l'ID dell'inserimento appena effettuato
            $request_id = $wpdb->insert_id;

            // Chiamata alla funzione twinr_iap_purchase
            twinr_iap_purchase($twinr_product_id);

            // Cambia la risposta in base ai dati ricevuti
            if ($success) {
                // Se l'acquisto ha avuto successo, invia una risposta di successo a Twinr
                $response_data = array(
                    'success' => true,
                    'data' => 'Purchase completed successfully.',
                    'load_url' => 'https://www.yourwebsite.xxx/' // Includi il campo load_url solo se l'acquisto è completato con successo
                );
            } else {
                // Se l'acquisto ha fallito, invia una risposta di errore a Twinr
                $response_data = array(
                    'success' => false,
                    'data' => 'Purchase failed.'
                );
            }

            // Aggiorna la colonna 'response' nella tabella con il messaggio di risposta
            $wpdb->update('swh_tlk_webhook_requests', array('response' => json_encode($response_data)), array('id' => $request_id));

            // Invia una risposta al webhook
            wp_send_json_success($response_data);


        } else {
            // Invia un messaggio di errore se i dati richiesti non sono presenti
            wp_send_json_error('Missing required data in the webhook request.');
        }
    } else {
        // Invia un messaggio di errore se la richiesta non è una richiesta POST
        wp_send_json_error('Invalid request method. Only POST requests are allowed.');
    }
}

// Registra l'azione per il webhook
add_action('wp_ajax_custom_webhook', 'custom_webhook_action');
add_action('wp_ajax_nopriv_custom_webhook', 'custom_webhook_action');

the response data is provided to me in this json:

{
      "twinr_product_id": "TWINR_PRODUCT_ID",
      "store_product_id": "STORE_PRODUCT_ID",
      "platform": "android or ios",
      "purchase_token": "PURCHASE_RECEIPT",
      "success":  true //true or false,
      "user_info": "USERNAME",
}

e mi hanno spiegato che la risposta dovrebbe essere da:

{
    "success": true,
    "data": "Purchase completed successfully."
}

to

{
    "success": true,
    "data": "Purchase completed successfully.",
    "load_url": "https://www.redirect.yoursite/"
}

I tried to redirect to load_url, in the inserted code but without success.

What am I doing wrong?

if I try with postman, I get:

{
    "success": true,
    "data": {
        "success": true,
        "data": "Purchase completed successfully.",
        "load_url": "https://www.yourwebsite.xxx/"
    }
}

therefore positive feedback, but no redirect in the app

How to print Customer bill and KOT bill separately in one click in php

Below is that the variables of customer bill kot bill which I’m passing it to the view page.
enter image description here
Here I have used embed tag to get the generated pdf source path.
enter image description here
After clicking the print button Customer bill and KOT bill is showing with print option separately like the below attachment
enter image description here

The only thing I need is in One click I need to print both Customer bill and KOT bill but it should be printed separately How can I acheive this by php codeigniter

Request that does not give CORS error in PHP gives CORS error in Javascript

Example URL: https://instagram.fcgh39-1.fna.fbcdn.net/v/t51.2885-19/11325708_957431864315767_713722537_a.jpg?_nc_ht=instagram.fcgh39-1.fna.fbcdn.net&_nc_cat=107&_nc_ohc=JCVs3rovMeYQ7kNvgEYo4HG&edm=AOQ1c0wBAAAA&ccb=7-5&oh=00_AfB8OyDajHtp6bU_RJcf0hr5ZF3h9mvuJ2G2RMBR-RTlhg&oe=66411D90&_nc_sid=8b3546

curl_setopt_array($curl, [
        CURLOPT_URL => "SECRETig=$test1",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => [
            "X-RapidAPI-Host: "SECRET",
            "X-RapidAPI-Key: "SECRET"
        ],
    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);
    $res=json_decode($response,1);
    $tobased=$res[0]['hd_profile_pic_url_info']['url'];
        
    if($res[0]['hd_profile_pic_url_info']['url'])
    {

            $newArr="data:image/png;base64,".base64_encode(file_get_contents($imageurl));
        echo $newArr;

The code above is PHP code and when used in this way, I can use the Instagram profile photo without CORS error.

But I need to do my work in Javascript, so I am sending a request in Javascript as follows:


let getProfileFhoto = (inputUsername) => {

let fetchURL = `SECRET?ig=${inputUsername}`
let fetchHeaders = {
  "X-RapidAPI-Host": "SECRET",
  "X-RapidAPI-Key": "SECRET"
}

return fetch(fetchURL, {headers: fetchHeaders}).then(response => response.json()).then(data => data[0]["hd_profile_pic_url_info"]["url"]).catch(error => 0)

}

if(usernameProfileFhotoURL.startsWith("http")){
      usernameProfileFhoto.src = usernameProfileFhotoURL
}else{
      usernameProfileFhoto.src = "images/logoig.png"
}

But when I add it to img in javascript, net::ERR_BLOCKED_BY_RESPONSE.NotSameOrigin 200 (OK) I am getting an error

In WooCommerce how to sort products by category on shop page?

In my woocommerce shop page I use the following function for product sorting by category. The first 4 attributes should be sorted by the newest product first. For the 5th the oldest product should appear first.

In addition I use the StoreCustomizer Plugin. I use the default WooCommerce Widget to filter Products by Attribute.

The following function has no impact at all.
Problem 1: With this function the category ‘pentalogs’ is on top and not ascending.
Problem 2: The sorting by category is not correct, it should be as in the function.

Thanks for any help 🙂

/**
* Add WooCommerce shop page default sorting by category
*/
function custom_product_sorting( $query ) {
    if ( $query->is_main_query() && is_shop() ) {
        $query->set( 'orderby', 'date' );
        $query->set( 'order', 'DESC' );

        $tax_query = array(
            'relation' => 'OR',
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'slug',
                'terms'    => 'paintings',
                'orderby'  => 'date',
                'order'    => 'DESC',
            ),
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'slug',
                'terms'    => 'limited-edition-art-prints',
                'orderby'  => 'date',
                'order'    => 'DESC',
            ),
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'slug',
                'terms'    => 'posters',
                'orderby'  => 'date',
                'order'    => 'DESC',
            ),
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'slug',
                'terms'    => 'limited-edition-photos',
                'orderby'  => 'date',
                'order'    => 'DESC',
            ),
             array(
                'taxonomy' => 'product_cat',
                'field'    => 'slug',
                'terms'    => 'pentalogs',
                'orderby'  => 'date',
                'order'    => 'ASC',
            ),
        );

        $query->set( 'tax_query', $tax_query );
    }
}
add_action( 'pre_get_posts', 'custom_product_sorting' );

Why do I always get a bad password message when trying to log in to PHP, even though my passwords in MySQL are correctly hashed?

I tried to print the hash obtained from the database and it is the expected hash. Here is the original php:

/*<?php
include 'conexion.php';

$usuario = $_POST['usuario'];
$pass = $_POST['pass'];

$sql = "SELECT * FROM usuarios WHERE usuario='$usuario'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if ($result->num_rows > 0) {
        if (password_verify($pass, $row['pass'])) {
        echo "Inicio de sesión exitoso.";
        } else {
        echo "Contraseña incorrecta. Por favor,      inténtalo de nuevo.";
        }
     } else {
        echo "Usuario no encontrado. Por favor,     regístrate si aún no tienes una cuenta.";
    }
}
?>

*/

Myriad, PHP, & Text Files: Very Strange Interactions

I work on a website that has a link to our radio system. Myriad is the software running the radio, and it outputs the current presenter to a file on our web server via ftp. Let’s call the presenter Joe Bloggs.

This text file – permissions, group, & owner all correct – never changes apart from Myriad periodically updating the presenter name. There is a second txt file in the same location for testing purposes. This file only get’s changed manually by myself, and again is correct for permissions, group, & owner.

I have PHP code that extracts the data from the text file via file_get_contents() and then uses string manipulation to create the Dir & URL paths to the image file that associates with the presenter.

Example:

Presenter in file: Joe Bloggs
$presImgDir: /home/dir/path/further/path/img/presenters/joe_bloggs_1.png
$presImgURL: https://my.website/further/path/img/presenters/joe_bloggs_1.png

My PHP code then does a simple:

if(!file_exists($presImgDir)) {
     $presentersImgURL = DIR_ROOT_CONST_INC_DS . 'further/path/img/presenters/fallback.png';
}

So that if – for any reason – the presenters image doesn’t exist, it falls back to a generic black silhouette of two people.

I have checked every line of code, every result of every php function, & my methods. When both the live Myriad changing text file & spoof file have the exact same presenter name, in the same format, case, spacing, characters – to the point of copying and pasting from one to the other (both ways) – they somehow change the result of the file_exists() check.

When using the live file (Myriad FTP connected) – file_exists returns false.
When using the spoof file (Manual edit file) – file_exists returns true.

I am at a loss. I am proud of my skills, whilst knowing you can never stop learning from sources or peers, but my somewhat autistic brain is now having a meltdown at the seemingly sheer illogic nature of this problem.

Why would a difference in text file containing the exact same data, change the result of a PHP file_exists() check, especially when all it receives is a string, and doesn’t interact with the text file otherwise?

Thanks for reading, I look forward to the responses. Happy to answer all questions. Please throw everything basic and advanced at me, even if it would seem silly not to assume I have done something. I’d rather be checked with a fine tooth comb at this point.

I tried: Logic.
I expected: Logic.

I received: The world ending.

(Not helpful I know but it made me feel better).