php 推送通知图像从React原生屏幕读取为null,但事实上它不是null,通过 Postman

gdx19jrr  于 2023-08-02  发布在  PHP
关注(0)|答案(1)|浏览(88)

感谢大家花时间尝试和帮助。我有一个应用程序,我内置在React Native Expo。一切正常,除了一个小bug。我有推送通知使用Expo的应用程序,我运行一个cron作业脚本在普通的php发送数据到应用程序和阅读推送通知。当我点击它打开伟大除了图像接收的数据是空。但是当我运行我的脚本,这是在线共享主机使用postman,到图像的链接是正确的,图像打开在应用程序和控制台图像值不是空,但它是一个链接。我似乎不知道这里可能是什么问题,因为当我手动或 Postman 运行脚本时图像是正确的,但当cron运行脚本时图像值为null。
我怀疑下面的部分是问题所在,因为根据我的经验,你不能在cron作业脚本中包含文件,你必须把所有文件都放在同一个文件中,而且我使用文档根来检查文件是否存在

$image_link_check = $documentRoot . "/admin/uploads/news/" .$latest_news['image'];

    if(file_exists($image_link_check)) {

        $image = $imageBaseUrl . "/news/" . $latest_news['image'];

    } else {

        $image = NULL;

    }

字符串
这里是我的页面,数据被接收,它被称为NewsDetailsScreen.js

import {
    StyleSheet,
    SafeAreaView,
    Image,
    Button,
    View,
    Platform,
    StatusBar,
    ScrollView,
    TouchableOpacity,
    Text,
} from 'react-native';
import React, { useState, useEffect, useContext } from 'react';
import AppText from '../components/AppText';
import colors from '../config/colors';
import { openBrowserAsync } from 'expo-web-browser';
import { CommonActions, useNavigation } from '@react-navigation/native';

import AsyncStorage from '@react-native-async-storage/async-storage';

import { useFocusEffect } from '@react-navigation/native';

import themeContext from '../theme/themeContext';

export default function NewsDetailsScreen({ route }) {
    const news = route.params;
    const navigation = useNavigation();

    const theme = useContext(themeContext);
    const [author, setAuthor] = useState();
    const [darkModeOn, setDarkModeOn] = useState(false);

    const retrieveDarkMode = async () => {
        try {
            const jsonValue = await AsyncStorage.getItem('darkModeOn');

            if (jsonValue !== null) {
                const parsedValue = JSON.parse(jsonValue);
                setDarkModeOn(parsedValue);
            }
        } catch (e) {
            // error reading value
            console.log('error: ', e);
        }
    };

    const displayAuthor = (author) => {
        if (
            author !== 'Editor' &&
            author !== 'F1 Desk' &&
            author !== 'Motorsport Network' &&
            author !== 'RACER Staff' &&
            author !== 'GPblog' &&
            author !== ''
        ) {
            setAuthor('By ' + author);
        } else {
            setAuthor('');
        }
    };

    useEffect(() => {
        displayAuthor(news.author);
        console.log(
            'news: ------------------------------------------------------------------ ',
            news.image
        );
        //navigation.navigate('Root', { screenName: 'NewsDetailsScreen' });
    });

    useFocusEffect(
        React.useCallback(() => {
            retrieveDarkMode();

            return () => {};
        }, [])
    );

    const styles = StyleSheet.create({
        author: {
            color: colors.lightBlue,
            marginTop: 10,
        },
        button: {
            marginTop: 20,
            marginBottom: 20,
        },
        date: {
            marginTop: 10,
            fontSize: 15,
            color: darkModeOn ? colors.white : colors.lightBlack,
        },
        description: {
            marginTop: 10,
            color: darkModeOn ? colors.white : colors.lightBlack,
        },
        detailsContainer: {
            padding: 20,
        },
        image: {
            width: '100%',
            height: 330,
        },
        // scrollView: {
        //     marginTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0,
        //     backgroundColor: darkModeOn ? colors.black : colors.white,
        // },
        mainContainer: {
            marginTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0,
            backgroundColor: theme.backgroundColor,
        },
        source: {
            marginTop: 10,
            color: darkModeOn ? colors.white : colors.lightBlack,
        },
        title: {
            fontSize: 24,
            fontWeight: '500',
            color: darkModeOn ? colors.white : colors.lightBlack,
        },
        backText: {
            color: darkModeOn ? colors.white : colors.lightBlack,
            fontSize: 35,
            paddingLeft: 5,
            paddingBottom: 10,
            position: 'absolute',
            left: 10,
            bottom: '-15%',
        },
    });

    return (
        <ScrollView style={styles.scrollView}>
            <SafeAreaView style={styles.mainContainer}>
                <TouchableOpacity
                    onPress={() => {
                        //navigation.navigate('Latest News');
                        navigation.dispatch(CommonActions.goBack());
                        // navigation.dispatch(
                        //     CommonActions.reset({
                        //         index: 0,
                        //         routes: [{ name: 'LatestNews' }],
                        //     })
                        // );
                    }}
                    style={{ width: '100%', height: 45, flexDirection: 'row' }}
                    activeOpacity={1}
                >
                    <Text style={styles.backText}>&#x2039;</Text>
                </TouchableOpacity>
                {/* <Image style={styles.image} source={news.image} /> */}
                {news.image !== null ? (
                    <Image
                        style={styles.image}
                        source={{
                            uri: news.image,
                        }}
                    />
                ) : (
                    <Image
                        style={styles.image}
                        source={require('../assets/f1ianIcon300x300.png')}
                    />
                )}

                <SafeAreaView style={styles.detailsContainer}>
                    <AppText style={styles.title}>{news.title}</AppText>
                    <AppText style={styles.description}>
                        {news.description}
                    </AppText>
                    {news.author !== null && (
                        <AppText style={styles.author}>{author}</AppText>
                    )}
                    <AppText style={styles.date}>{news.pubDate}</AppText>
                    <AppText style={styles.source}>
                        From {news.feedName}
                    </AppText>
                    <View style={styles.button}>
                        <Button
                            title="Read Full Article"
                            onPress={() => openBrowserAsync(news.link)}
                        />
                    </View>
                </SafeAreaView>
            </SafeAreaView>
        </ScrollView>
    );
}


下面是我的php脚本(不能共享所有脚本,因为它包含数据库信息和凭据:

if(array_key_exists('HTTPS', $_SERVER) && $_SERVER["HTTPS"] == "on") {
    $site_link = "https://".$_SERVER['HTTP_HOST'] . "" . $base_directory;
} else {
    $site_link = "http://".$_SERVER['HTTP_HOST'] . "" . $base_directory;
}

$base_directory = "";

$imageBaseUrl = $site_link . "/admin/uploads";


$latest_news = find_the_latest_single_news_by_subject_id($f1_subject);

// array_push($latest_news_array, $latest_news);

$found_feed = find_feed_info_by_feed_id($latest_news['feed_id']);

while($found_devices_assoc = mysqli_fetch_assoc($found_devices)) {

    $token = $found_devices_assoc['token'];

    $title = $latest_news['title'];
    $title = str_replace("&#39;", "'", $title);
    $title = str_replace("&#34;", "'", $title);

    $source = ucwords($found_feed['feed_name']);

    $author = str_replace("&#34;", '"', $latest_news['author']);
    $author = str_replace("&#39;", "'", $author);
    $author = str_replace(".com", "", $author);
    $author = trim($author);
    if(strtolower($author) != strtolower($found_feed['feed_name'])) {
        $author = $author;
    } else {
        $author = NULL;
    }

    $description = str_replace("&#34;", '"', $latest_news['description']);
    $description = str_replace("&#39;", "'", $description);
    $description = str_replace("\n", " ", $description);

    $pubDate = date("F j, Y", $latest_news['pubDate']) . " at " . date("g:i a", $latest_news['pubDate']);
    $insertDateTime = date("F j, Y", $latest_news['insert_date']) . " at " . date("g:i a", $latest_news['insert_date']);

    $image = "";

    if($latest_news['image'] === NULL || $latest_news['image'] === "") {

        $image = NULL;

    } else {

        $image_link_check = $documentRoot . "/admin/uploads/news/" . $latest_news['image'];
        echo "image_link_check: " . $image_link_check . "<br><br>";
        if(file_exists($image_link_check)) {

            $image = $imageBaseUrl . "/news/" . $latest_news['image'];

        } else {

            $image = NULL;

        }

    }

    if($found_devices_assoc['notificationOn'] == 1) {
        $json_payload = array(
            'to' => $token,
            'sound' => 'default',
            'title' => $source,
            'body' => $title,
            "data" => [
                "screen" => "NewsDetailsScreen",
                "id" => $latest_news['id'],
                "feedName" => $source,
                "pubDate" => $pubDate,
                "title" => $title,
                "description" => $description,
                "link" => $latest_news['link'],
                "author" => $author,
                "image" => $image,
                "insertDate" => $insertDateTime
                
            ]
           
        );

        $data = json_encode($json_payload);
        var_dump($data);
        //FCM API end-point
        $url = 'https://exp.host/--/api/v2/push/send';
        //CURL request to route notification to FCM connection server (provided by Google)
        $ch = curl_init();

        curl_setopt_array($ch, array(
            CURLOPT_URL => "https://exp.host/--/api/v2/push/send",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $data,
            CURLOPT_HTTPHEADER => array(
                "Accept: application/json",
                "Accept-Encoding: gzip, deflate",
                "Content-Type: application/json",
                "cache-control: no-cache",
                "host: exp.host"
            ),
        ));

        $response = curl_exec($ch);
        $err = curl_error($ch);
        if ($response === FALSE) {
            die('Oops! FCM Send Error: ' . curl_error($ch));
        }
        curl_close($ch);
        
        if ($err) {
            echo "cURL Error #:" . $err;
        } else {
            echo $response;
        }
    }
}

sbdsn5lh

sbdsn5lh1#

问题出在这些行中,当我从cron job运行脚本时,它们不起作用

if(array_key_exists('HTTPS', $_SERVER) && $_SERVER["HTTPS"] == "on") {
    $site_link = "https://".$_SERVER['HTTP_HOST'] . "" . $base_directory;
} else {
    $site_link = "http://".$_SERVER['HTTP_HOST'] . "" . $base_directory;
}

字符串
因此,我将其替换为:

$site_link = "https://site-domain.com"


这些行取代:
$image_link_check = $documentRoot。“/admin/uploads/news/”。$latest_news ['image']; echo“image_link_check:“. $image_link_check。“
“; if(file_exists($image_link_check))

$image = $imageBaseUrl . "/news/" . $latest_news['image'];

        } else {

            $image = NULL;

        }


替换为:

$image_url = $imageBaseUrl . "/news/" . $latest_news['image'];

        $image_type_check = @exif_imagetype($image_url);
        if (strpos($http_response_header[0], "200")) {
            $image = $imageBaseUrl . "/news/" . $latest_news['image'];
        } else {
            $image = NULL;
        }


如果有人请有一个答案为什么上面的代码不工作当你运行脚本从一个cron作业请分享它.谢谢你的好意

相关问题