PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 11, 2022

[FIXED] How to copy resource in new variable and destroy old resource?

 October 11, 2022     gd, php, resources     No comments   

Issue

Given the following code:

imagecopyresized($new_image, $product, $dst_x, $dst_y, $src_x, $src_y, $dst_width, $dst_height, $src_width, $src_height);

imagedestroy($product);
$product = $new_image;
imagedestroy($new_image);

The last line destroys $product, not just $new_image, as if $product is some sort of pointer to $new_image. Why does this happen and how can I effectively create a copy of *$new_image* within $product and then destroy the $new_image resource?


Solution

Why this happens:

PHP uses copy-on-write memory management, i.e., you will not allocate new space in memory for the variable --> just point to the same memory location.

How to avoid this:

imagecopyresized($new_image, $product, $dst_x, $dst_y, $src_x, $src_y, $dst_width, $dst_height, $src_width, $src_height);

imagedestroy($product);
$product = clone $new_image;
imagedestroy($new_image);

http://www.php.net/manual/en/language.oop5.cloning.php

About copy-on-write: http://www.research.ibm.com/trl/people/mich/pub/200901_popl2009phpsem.pdf



Answered By - Uirri
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing