php 脚本未正确设置内容类型
我有以下在验证后运行的 php 代码:
try {
if (isset($filtered) && !isset($errors)){
$p['email']=$filtered['email'];
# check if email exists
if ($user->userExists($p)){
$msg['error'] = false;
$msg['msg'] = 'This email address is already in our database';
} else {
# insert user data into database
$user->saveUser($filtered);
$msg['error'] = false;
$msg['msg'] = 'Successful! Go back to our homepage.';
}
} else {
# echo errors back
foreach ($errors as $value) {
$msg['error'] = true;
$msg['msg'] = $value;
}
}
我按如下方式准备 json 数据:
# header encode
header('Content-type: application/json');
# return json encoded data
echo $encoded = json_encode($msg);
像下面这样的直接数组工作正常。
header('Content-type: application/json');
$msg['error'] = true;
$msg['msg'] = 'Please enter an email address.';
echo $encoded = json_encode($msg);
我似乎无法弄清楚我的 php 逻辑有什么问题。请帮忙。
I have the following php code that runs after validation:
try {
if (isset($filtered) && !isset($errors)){
$p['email']=$filtered['email'];
# check if email exists
if ($user->userExists($p)){
$msg['error'] = false;
$msg['msg'] = 'This email address is already in our database';
} else {
# insert user data into database
$user->saveUser($filtered);
$msg['error'] = false;
$msg['msg'] = 'Successful! Go back to our homepage.';
}
} else {
# echo errors back
foreach ($errors as $value) {
$msg['error'] = true;
$msg['msg'] = $value;
}
}
I prepare the json data as follows:
# header encode
header('Content-type: application/json');
# return json encoded data
echo $encoded = json_encode($msg);
A direct array like this one below works fine.
header('Content-type: application/json');
$msg['error'] = true;
$msg['msg'] = 'Please enter an email address.';
echo $encoded = json_encode($msg);
I can't seem to figure out what the problem with my php logic could be. Kindly help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我能看到的唯一区别是,在有效的版本中,您在执行其他操作之前调用
header()
。尝试移动
到 try/catch 上方。我怀疑您遇到此问题的原因是因为您在创建数组
$msg
之前隐式访问它,这会引发E_NOTICE
(或者可能会是E_STRICT
,我不记得了)并导致某些内容被写入输出缓冲区,因此标头被发送,并且您无法再操作它们 - 尽管如果是这种情况我希望它也会破坏你的 JSON...无论如何,请尝试上述操作并报告回来。
The only difference I can see there is that in the version that works, you call
header()
before anything else.Try moving
above the try/catch. I have a suspicion that the reason you are getting this problem is because you are implicitly accessing the array
$msg
before you have created it, which throws anE_NOTICE
(or it might beE_STRICT
, I can't remember) and causes something to be written to the output buffer, so the headers are sent, and you can no longer manipulate them - although if this were the case I would expect it to break your JSON as well...Regardless, try the above and report back.