1

I have a php file upload script which returns a json response. The issue is the url of the response contains odd characters.

I get a response that has \ / between the directories instead of just / or \ /\ / after the http: instead of just //

So I am getting this. http:\ / \ /www.mywebsite.com\ /uploads\ /myfile.jpg

But I need it to look like this. http://www.mywebsite.com/uploads/myfile.jpg

Based on my code below any thoughts on what I need to change?

<?php

header('Content-Type: application/json');
if(isset($_POST['album_name']))
{
$dir_name = $_POST['album_name'];
}
$json = array();
if(file_exists('uploads/'.$dir_name))
{
$handle = opendir('uploads/'.$dir_name);

while(false !== ($file = readdir($handle)))
{
    if($file != '.' && $file != '..')
    {


        $url= 'http://www.'.$_SERVER['SERVER_NAME'].'/uploads/'.$dir_name.'/'.$file;
    $data = array($type,$url);
        array_push($json,$data);
    }



}
}
echo json_encode($json);

?>
4
  • Could you post the actual url are getting back? Commented Dec 30, 2017 at 14:09
  • I tried to but stackoverflow is actually reformatting it to look correct. I am getting a response like: http:\ / \ /www.mywebsite.com\ /uploads\ /myfile.jpg Commented Dec 30, 2017 at 14:11
  • And is the URL you are getting from json_encode or echo? Commented Dec 30, 2017 at 14:12
  • This issue is in the echo json_encode Commented Dec 30, 2017 at 14:17

2 Answers 2

1

Add JSON_UNESCAPED_SLASHES to the json_encode options (available since PHP 5.4)

echo json_encode($json, JSON_UNESCAPED_SLASHES)

Sign up to request clarification or add additional context in comments.

Comments

0

This is caused by the json_encode function. It automatically adds backslashes, since in json it can cause problems if a / is after a <, since this is in HTML how you end a tag.

The best solution is probably to simply leave it as it is, and when parsing the JSON if the problem remains, that is if whatever json decoding method you use does not remove these backslashes, do a string replace, in php this would be str_replace Documentation here

Hope this solves your problem :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.