了解JSON编码响应中反斜杠的来源

时间:2014-11-19 18:49:41

标签: php

我有一个很长的脚本来裁剪图像,将其保存到服务器,将路径插入SQL,更多表单字段。我遇到了将文件路径保存到SQL的问题。这个剧本接近200行,我怀疑是否有人想透过它看,所以我试图麻烦拍摄。

脚本的结尾使用以下内容响应包含表单的页面:

            public function getResult() {
            return !empty($this -> data) ? $this -> dst : $this -> src;
        }

        public function getMsg() {
            return $this -> msg;
        }
    }
$crop = new CropAvatar($_POST['avatar_src'], $_POST['avatar_data'], $_FILES['avatar_file']);
    $response = array(
        'state'  => 200,
        'message' => $crop -> getMsg(),
        'result' => $crop -> getResult()
    );
    echo json_encode($response);
        }

当我查看Firebug中的响应数据时,我得到了这个:

{"state":200,"message":null,"result":"..\/0images\/listimg\/mod\/20141119183449.jpeg"}

反斜杠来自哪里?

我的PHP代码中没有任何反斜杠,如下所示:

<?php
require('../dbcon2.php');
//Connection 1
try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $conn->prepare("INSERT INTO listings (title, address, lot_size, zoning, build_size, sale_price, lease_price, comment, transaction, date_added) VALUES (:title, :address, :lot_size, :zoning, :build_size, :sale_price, :lease_price, :comment, :transaction, now())");
          $stmt->bindParam(':title', $_POST['title']); 
          $stmt->bindParam(':address', $_POST['address']);
          $stmt->bindParam(':lot_size', $_POST['lot_size']);
          $stmt->bindParam(':zoning', $_POST['zoning']);
          $stmt->bindParam(':build_size', $_POST['build_size']);
          $stmt->bindParam(':sale_price', $_POST['sale_price']);
          $stmt->bindParam(':lease_price', $_POST['lease_price']);
          $stmt->bindParam(':comment', $_POST['comment']);
          $stmt->bindParam(':transaction', $_POST['transaction']);
        $stmt->execute();
        $id = $conn->lastInsertId();
//Create class
    class CropAvatar {
        private $src;
        private $data;
        private $file;
        private $dst;
        private $type;
        private $extension;
        private $srcDir = '../0images/listimg/orig';
        private $dstDir = '../0images/listimg/mod';
        private $msg;

function __construct($src, $data, $file, $id, $ad_link, $listing_img) {
    $this -> setSrc($src);
    $this -> setData($data);
    $this -> setFile($file);
    $this -> setId($id);
    $this -> setAd_link($ad_link);
    $this -> setListing_img($listing_img);
    $this -> crop($this -> src, $this -> dst, $this -> data, $this -> id, $this -> ad_link, $this -> listing_img);
}
        private $id;
        public function setId($id) {
                 $this->id = $id;
}
            private $ad_link;
        public function setAd_link($ad_link) {
                 $this->ad_link = $ad_link;
}
            private $listing_img;
        public function setListing_img($listing_img) {
                 $this->listing_img = $listing_img;
}
        private function setSrc($src) {
            if (!empty($src)) {
                $type = exif_imagetype($src);
                if ($type) {
                    $this -> src = $src;
                    $this -> type = $type;
                    $this -> extension = image_type_to_extension($type);
                    $this -> setDst();
                }
            }
        }
        private function setData($data) {
            if (!empty($data)) {
                $this -> data = json_decode(stripslashes($data));
            }
        }
        private function setFile($file) {
            $errorCode = $file['error'];
            if ($errorCode === UPLOAD_ERR_OK) {
                $type = exif_imagetype($file['tmp_name']);
                if ($type) {
                    $dir = $this -> srcDir;
                    if (!file_exists($dir)) {
                        mkdir($dir, 0777);
                    }
                    $currdate=date('YmdHis');
                    $extension = image_type_to_extension($type);
                    $src = $dir . '/' . $currdate . $extension;
                    if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_JPEG || $type == IMAGETYPE_PNG) {
                        if (file_exists($src)) {
                            unlink($src);
                        }
                        $result = move_uploaded_file($file['tmp_name'], $src);
                        $listing_img="http://www.website.com/0images/listimg/mod/" . $currdate . $extension;
 //Process file upload 
                        $allowedExtsf = array("pdf");
                            $tempf = explode(".", $_FILES["flyer"]["name"]);
                        $extensionf = end($tempf);
                        if (($_FILES["flyer"]["type"] == "application/pdf")
                        && ($_FILES["flyer"]["type"] <2000000000)
                        && in_array($extensionf, $allowedExtsf)) 
                        {
                            $flyername=$_FILES["flyer"]["name"];
                            if ($_FILES["flyer"]["error"] > 0) 
                            {
                            echo "Return Code: " . $_FILES["flyer"]["error"] . "<br>";
                            }   
                                else 
                                {
                                    if (file_exists("../flyers/" . $_FILES["flyer"]["name"])) 
                                    {
                                     unlink("../flyers/" . $_FILES["flyer"]["name"]);
                                    }

                                        move_uploaded_file($_FILES["flyer"]["tmp_name"],"../flyers/" . $_FILES["flyer"]["name"]);
                                        $ad_link="http://www.website.com/flyers/" . $_FILES["flyer"]["name"];
                        //Error handling
                            require('../dbcon2.php');
                            try {
                                $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
                                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                                $sql="UPDATE listings SET ad_link='$this->ad_link', listing_img='$this->listing_img' WHERE id='$this->id'";
                                $conn->exec($sql);
                                }
                            catch(PDOException $e)
                                {
                                echo $sql . "<br>" . $e->getMessage();
                                }
                            $conn = null;
                                           }}
                //Error handling
                        if ($result) {
                            $this -> src = $src;
                            $this -> type = $type;
                            $this -> extension = $extension;
                            $this -> setDst();
                        } else {
                             $this -> msg = 'Failed to save file';
                        }
                    } else {
                        $this -> msg = 'Please upload image with the following types: JPG, PNG, GIF';
                    }
                } else {
                    $this -> msg = 'Please upload image file';
                }
            } else {
                $this -> msg = $this -> codeToMessage($errorCode);
            }
        }

        private function setDst() {
            $dir = $this -> dstDir;

            if (!file_exists($dir)) {
                mkdir($dir, 0777);
            }

            $this -> dst = $dir . '/' . date('YmdHis') . $this -> extension;
        }

        private function crop($src, $dst, $data) {
            if (!empty($src) && !empty($dst) && !empty($data)) {
                switch ($this -> type) {
                    case IMAGETYPE_GIF:
                        $src_img = imagecreatefromgif($src);
                        break;

                    case IMAGETYPE_JPEG:
                        $src_img = imagecreatefromjpeg($src);
                        break;

                    case IMAGETYPE_PNG:
                        $src_img = imagecreatefrompng($src);
                        break;
                }

                if (!$src_img) {
                    $this -> msg = "Failed to read the image file";
                    return;
                }

                $dst_img = imagecreatetruecolor(220, 220);
                $result = imagecopyresampled($dst_img, $src_img, 0, 0, $data -> x, $data -> y, 220, 220, $data -> width, $data -> height);

                if ($result) {
                    switch ($this -> type) {
                        case IMAGETYPE_GIF:
                            $result = imagegif($dst_img, $dst);
                            break;

                        case IMAGETYPE_JPEG:
                            $result = imagejpeg($dst_img, $dst);
                            break;

                        case IMAGETYPE_PNG:
                            $result = imagepng($dst_img, $dst);
                            break;
                    }

                    if (!$result) {
                        $this -> msg = "Failed to save the cropped image file";
                    }
                } else {
                    $this -> msg = "Failed to crop the image file";
                }

                imagedestroy($src_img);
                imagedestroy($dst_img);
            }
        }
        private function codeToMessage($code) {
            switch ($code) {
                case UPLOAD_ERR_INI_SIZE:
                    $message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                    break;

                case UPLOAD_ERR_FORM_SIZE:
                    $message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                    break;

                case UPLOAD_ERR_PARTIAL:
                    $message = 'The uploaded file was only partially uploaded';
                    break;

                case UPLOAD_ERR_NO_FILE:
                    $message = 'No file was uploaded';
                    break;

                case UPLOAD_ERR_NO_TMP_DIR:
                    $message = 'Missing a temporary folder';
                    break;

                case UPLOAD_ERR_CANT_WRITE:
                    $message = 'Failed to write file to disk';
                    break;

                case UPLOAD_ERR_EXTENSION:
                    $message = 'File upload stopped by extension';
                    break;

                default:
                    $message = 'Unknown upload error';
            }

            return $message;
        }

        public function getResult() {
            return !empty($this -> data) ? $this -> dst : $this -> src;
        }

        public function getMsg() {
            return $this -> msg;
        }
    }
$crop = new CropAvatar($_POST['avatar_src'], $_POST['avatar_data'], $_FILES['avatar_file']);
    $response = array(
        'state'  => 200,
        'message' => $crop -> getMsg(),
        'result' => $crop -> getResult()
    );
    echo json_encode($response);
        }
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;

?>

1 个答案:

答案 0 :(得分:3)

PHP的json_encode函数正在转义斜杠(如果使用最新的PHP版本,请参阅http://php.net/manual/en/json.constants.php了解JSON_UNESCAPED_SLASHES常量。

使用反斜杠转义斜杠是完全有效的JSON(请参阅http://json.org/上的字符串的定义),因此无论如何解码器应该处理它。

转义斜杠的原因是避免必须永远不会出现在JSON对象的字符串表示形式中的字符序列</script>,因此当前一个字符为{时,许多JSON编码器仅编码/ {1}}(但不是PHP&#39;))。