Alexa289 Alexa289 - 3 years ago 358
PHP Question

failed when using str_replace

i am new in PHP, i am trying to delete a post with an image, before delete the image in the storage drive, I have to change the image path from http://localhost/Twitter/Post/52/POST-1F3D1ABB-D525-4107-BE08-B5F8B7B5E29B.jpeg to /Applications/XAMPP/xamppfiles/htdocs/Twitter/Post/52/POST-1F3D1ABB-D525-4107-BE08-B5F8B7B5E29B.jpeg"

thats why I use

to change the imagePath,but i got the error

Notice: Undefined variable: path in
/Applications/XAMPP/xamppfiles/htdocs/twitter/post.php on line 123

Warning: unlink(): No such file or directory in

/Applications/XAMPP/xamppfiles/htdocs/twitter/post.php on line 126

{"message":"successfully deleted","result":1,"status":"Image has been
failed to be deleted from drive"}

i got undefined path variable in this line

$path = str_replace("http://localhost/", "/Applications/XAMPP/xamppfiles/htdocs/", $path);

what went wrong in here ?

if (!empty($_REQUEST["uuid"]) && empty($_REQUEST["id"])) {

$uuid = htmlentities(strtolower(stripcslashes($_REQUEST["uuid"])));
$imagePath = htmlentities(($_REQUEST["imagePath"]));

$result = $access -> deletePost($uuid);

if (!empty($result)) {

$returnArray = [
"message" => "successfully deleted",
"result" => $result

if (!empty($imagePath)) {

$path = str_replace("http://localhost/", "/Applications/XAMPP/xamppfiles/htdocs/", $path);

if (unlink($path)) {
$returnArray["status"] = "Image has been deleted from drive";
} else {
$returnArray["status"] = "Image has been failed to be deleted from drive";


} else {

$returnArray = [
"message" => "Couldn't delete the post"



Answer Source

The following line:

$path = str_replace("http://localhost/", "/Applications/XAMPP/xamppfiles/htdocs/", $path);

Should be (switch $path for $imagePath)

$path = str_replace(

But using http://localhost/ and replacing with /Applications/XAMPP/xamppfiles/htdocs/ makes it 100% not portable, it will break once you move the code somewhere else.

Instead you should use parse_url to grab the path, and as /Applications/XAMPP/xamppfiles/htdocs/ simply looks like a path to your webroot, forget about using it.

$url = 'http://localhost/Twitter/Post/52/POST-1F3D1ABB-D525-4107-BE08-B5F8B7B5E29B.jpeg';

$path = parse_url($url, PHP_URL_PATH);

echo $path; //Twitter/Post/52/POST-1F3D1ABB-D525-4107-BE08-B5F8B7B5E29B.jpeg

Then just use unlink($path); it should work fine and it makes your code portable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download