php 自定义HTTP响应代码以及JSON返回

cunj1qz1  于 2023-01-24  发布在  PHP
关注(0)|答案(4)|浏览(161)

好的,我有一个基于Ajax的文件上传,它将文件发送到一个处理php代码。这一切都工作正常,它返回一个json_encoded数组。然而,这个数组返回的结果要么是“成功”要么是“错误”-然而,我希望能够实际更改HTTP状态代码(目前它们都返回200 OK,因为它从脚本获得响应)。
那么,有没有人有代码可以让PHP同时发送http_response_code()和json_encoded()消息?或者可以把我链接到某个有例子的地方?
我已经包含了process_upload. php文件的代码,很抱歉太长了(大约130行)--在接近结尾的时候,我试图包含一个http_status_code(415),但这没有任何作用。
更新了代码,因为我发现是我误判了触发http_status_code()的变量的位置。修复了这个问题,它工作了。

<?php
if (!session_id()) { session_start(); };
require_once('conf/config.php');
require_once('functions.php');
$returnmessage = json_encode(["content"=>"Error Error Error","infotype"=>"error"]);
$changereturnheader = 0;
if ((isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) || $allow_public == true) {
        if (isset($_FILES['file'])) {
            if (in_array('error', $_FILES['file'])) {
                switch ($_FILES['file']['error']) {
                    case 0:
                    $returnerror = false;
                    $returnerrorcontent = '';
                    break;
                    case 1:
                    $returnerror = true;
                    $returnerrorcontent = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                    break;
                    case 2:
                    $returnerror = true;        
                    $returnerrorcontent = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                    break;
                    case 3:
                    $returnerror = true;        
                    $returnerrorcontent = 'The uploaded file was only partially uploaded';
                    break;
                    case 4:
                    $returnerror = true;        
                    $returnerrorcontent = 'No file was selected';
                    break;
                    case 6:
                    $returnerror = true;        
                    $returnerrorcontent = 'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3';
                    break;
                    case 7:
                    $returnerror = true;      
                    $returnerrorcontent = 'Failed to write file to disk. Introduced in PHP 5.1.0';
                    break;
                    case 8:
                    $returnerror = true;        
                    $returnerrorcontent = 'A PHP extension stopped the file upload. Introduced in PHP 5.2.0';
                    break;
                    default:
                    $returnerror = false;
                    $returnerrorcontent = '';
                    break;
                }
            }
            if (isset($_FILES['file']) && $returnerror == false) {
                $allowed = '';
                $allowed_extensions = allowedExtensions('');
                $totalentries = count(allowedExtensions('')) -1;
                for ($i = 0; $i <= $totalentries; $i++) {
                    $allowed .= (($i == $totalentries) ? $allowed_extensions[$i] : $allowed_extensions[$i].', ');
                }
                if (($_FILES['file']['size'] + foldersize($userpath.$username) < $storage_limit)) {
                    if (in_array($_FILES['file']['type'], allowedMimeTypes(''))) {
                        if (in_array($_FILES['file']['type'], allowedMimeTypes('audio'))) {
                            $folder = 'music';
                        } elseif (in_array($_FILES['file']['type'], allowedMimeTypes('image'))) {
                            $folder = 'pictures';
                        } elseif (in_array($_FILES['file']['type'], allowedMimeTypes('video'))) {
                            $folder = 'video';
                        } elseif (in_array($_FILES['file']['type'], allowedMimeTypes('application'))) {
                            $folder = 'documents';
                        } elseif (in_array($_FILES['file']['type'], allowedMimeTypes('text'))) {
                            $folder = 'documents';
                        }
                        $filename = $_FILES['file']['name'];
                        if (file_exists(''.$userpath.$username.$folder.'/'.onlyValidChar($_FILES['file']['name']))) {
                            if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
                                // echo 'exist';
                                $returnmessage = json_encode(["content"=>"$filename already exist","infotype"=>"error"]);
                            }                       
                        } else {
                            move_uploaded_file($_FILES['file']['tmp_name'],''.$userpath.$username.$folder.'/'.onlyValidChar($_FILES['file']['name']));
                            if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
                                // echo 'uploaded file';
                                $returnmessage = json_encode(["content"=>"You uploaded $filename","infotype"=>"success"]);
                            }
                            $movedfile = pathinfo($_FILES['file']['name']);
                            if (in_array(strtolower($movedfile['extension']),allowedExtensions('')) && in_array($_FILES['file']['type'],allowedMimeTypes('image'))) {
                                // createThumbs($userpath.$username.$folder.'/',onlyValidChar($_FILES['file']['name']),200);
                                generate_image_thumbnail($userpath.$username.$folder.'/'.onlyValidChar($_FILES['file']['name']),$userpath.$username.$folder.'/thumbs/'.onlyValidChar($_FILES['file']['name']));
                            }
                            if (in_array(strtolower($movedfile['extension']),allowedExtensions('')) && in_array($_FILES['file']['type'],allowedMimeTypes('video'))) {
                                $video = $_SERVER['DOCUMENT_ROOT'].'/'.$userpath.$username.$folder.'/'.onlyValidChar($_FILES['file']['name']);
                                $thumbnail = $_SERVER['DOCUMENT_ROOT'].'/'.$userpath.$username.$folder.'/thumbs/'.onlyValidChar($_FILES['file']['name']).'.jpg';
                                $get_frames = shell_exec("/usr/local/bin/ffmpeg -nostats -i $video -vcodec copy -f rawvideo -y /dev/null 2>&1 | grep frame | awk '{split($0,a,\"fps\")}END{print a[1]}' | sed 's/.*= *//'");
                                $stills_number = floor($get_frames / 200);
                                $output = shell_exec("/usr/local/bin/ffmpeg -y -i $video -frames 1 -q:v 1 -vf 'select=not(mod(n\,$stills_number)),scale=-1:120,tile=100x1' $thumbnail");
                            }
                            updateCurrentUploads('current_uploads.php',$_FILES['file']['name']);
                        }
                    } else {
                        if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {                                
                            $changereturnheader = 1;
                            $returnmessage = json_encode(["content"=>"The filetype you tried to upload is not allowed","infotype"=>"error"]);
                        }
                    }
                } else {
                    echo 'exceeding diskspace';
                    $returnmessage = json_encode(["content"=>"The file will exceed your available diskspace. Delete some of the files already uploaded to make room","infotype"=>"error"]);
                }
            } elseif ($returnerror == true) {
                if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
                    // echo 'error-message return';
                    $returnmessage = json_encode(["content"=>"$returnerrorcontent","infotype"=>"error"]);
                }
            } else {
                if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
                    // echo 'filetype not allowed 2';
                    $changereturnheader = 1;
                    $returnmessage = json_encode(["content"=>"The filetype you tried to upload is not allowed","infotype"=>"error"]);
                }
            }
        }
    // echo returnCurrentUploads('current_uploads.php');
        if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            // echo 'returnmsg';
            if ($changereturnheader == 1) {
                http_response_code(415);
            }
            echo $returnmessage;
        } else {
            header('location: upload');
        }
    }
?>
9rygscc1

9rygscc11#

我可以发送http_response_code(415),也可以传递json:

<?php

$array = array(
  'one' => array(1, 2, 3),
  'two' => array(4, 5, 6),
  'three' => array(7, 8, 9),
);

http_response_code(415);
echo json_encode($array);

prdp8dxp

prdp8dxp2#

我相信你的php版本可能不支持这个功能。
请尝试使用 header 功能

header("HTTP/1.0 415 Unsupported Media Type");

代替

http_response_code(415);

看看能不能帮上忙

nukf8bse

nukf8bse3#

我很愚蠢,这是我的视力缺陷,而不是功能。我设置了两个不同的返回消息,一个用于通过 AJAX 完成的请求,另一个用于常规的非AJAX文件传输。我只应用了在非AJAX上传中启用http_status_code()的变量。在将其添加到应该的位置后,它工作得很好。我还修改了问题中的代码,所以它现在起作用了。

b5lpy0ml

b5lpy0ml4#

在我的例子中,我必须在echo json_encode(txt)之前调用http_response_code(xxx),如果我先调用json_encode,http_response_code(xxx)将被忽略,状态代码始终为200。

相关问题