上传到服务器后,Php生成了错误的格式url文件路径

问题描述 投票:0回答:2

下面是我生成每个上传图像的唯一文件Url并将其存储到数据库的代码。

    //create unique image file name based on micro time and date
    $now = DateTime::createFromFormat('U.u', microtime(true));
    $id = $now->format('YmdHisu');

    // Path to move uploaded files
    $target_path = "uploads";
    //the file name
    $path = "$target_path/$id.jpeg";

    // getting server ip address
    $server_ip = gethostbyname(gethostname());

    // final file url that is being uploaded
    $file_upload_url = 'http://'. $server_ip . '/' . 'abc' . '/' .$path;

我对此代码的期望应该生成json_encode中的url,如下所示:

http://111.111.11.1/abc/uploads/20170226041004809200.jpeg

但现在问题是它生成了Url但是在json_encode结果如下所示

http:\/\/111.111.11.1\/abc\/uploads\/20170226041004809200.jpeg

到目前为止我尝试过的,

$file_upload_url = 'http:'. $server_ip  . 'abc'  .$path;

但它不是我想要的,它变成了这个

http:111.111.11.1.1abcuploads\/20170226041515563600.jpeg

有人可以知道如何解决这个问题吗?或者有更好的建议?

php json image url
2个回答
0
投票

使用str_replace替换\

<?php
   $file_upload_url = "http:\/\/111.111.11.1\/abc\/uploads\/20170226041004809200.jpeg";
   $upload_path = str_replace('\\','',$file_upload_url);
   echo $upload_path;
?>

1
投票

如果您在同一台服务器上工作,那么为什么不尝试上传带有代码段的文件 -

 $file_upload_url = realpath($_SERVER["DOCUMENT_ROOT"]). '/abc' . '/' .$path;
// you can manage url by -
$base_url  = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
$base_url.=$_SERVER['SERVER_ADDR'];
$base_url.='/abc/'.$path
// now print your url-
echo $base_url;
© www.soinside.com 2019 - 2024. All rights reserved.