繁体   English   中英

自定义 HTTP 响应码连同 JSON 返回

[英]Custom HTTP Response code together with JSON return

好的,我有一个基于 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');
        }
    }
?>

我能够发送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);

在此处输入图片说明

我相信您的php版本可能不支持该功能。

可以请您尝试使用标头功能吗

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

代替

http_response_code(415);

看看是否有帮助

我很愚蠢,这是我眼中的错误,而不是功能。 我设置了两种不同的returnmessage,一种用于通过AJAX完成请求,另一种通过常规的非AJAX文件传输。 我只在非AJAX上传中应用了启用http_status_code()的变量。 将其添加到预期位置后,它可以正常工作。 我也修改了问题中的代码,因此现在可以使用了。

就我而言,我必须在 echo json_encode(txt) 之前调用 http_response_code(xxx)。 如果我先调用 json_encode,http_response_code(xxx) 将被忽略,状态码始终为 200。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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