Issues with ldd

I tried to compile php and integrate it into apache on solaris.
It compiled ok and I created a package. If I install it on a system that has the libpng from sunfreeware, it wants to use that library instead of the system SUNWpng. It doesn't run using SMCpng, but it runs using the system SUNWpng.

If SMCpng is not installed:
bash-3.00# ldd libphp5.so | grep png
libpng12.so.0 => /usr/lib/libpng12.so.0

If SMCpng is installed:
# ldd libphp5.so | grep png
libpng12.so.0 => /usr/local/lib/libpng12.so.0

I configured the package with the below options.
LDFLAGS="-L/usr/sfw/lib -R/usr/sfw/lib -L/usr/lib -R/usr/lib -L/lib -R/lib -L/usr/local/lib -R/usr/local/lib"
LIBS="-L/usr/sfw/lib -L/usr/lib -L/lib -L/usr/local/lib"
CPPFLAGS="-I/usr/sfw/lib -I/usr/lib -I/lib -I/usr/local/lib"
PATH="/opt/SUNWspro/bin:/usr/ccs/bin:/usr/bin:/usr/sbin:/usr/sfw/bin"
export LDFLAGS LIBS PATH CPPFLAGS
./configure --prefix=/opt/php \
--with-apxs2=/opt/apache2/bin/apxs \
--with-config-file-path=/opt/apache2/etc \
--enable-dbase \
--with-jpeg-dir=/usr \
--with-png-dir=/usr \
--with-zlib \
--enable-mbstring \
--with-libxml-dir=/usr/local \
--with-xpm-dir=/usr \
--with-gd \
--with-tiff-dir=/usr \
--with-bz2=/usr/lib \
--enable-calendar \
--enable-bcmath \
--enable-ftp \
--enable-exif

exit $?

Thanks in advance for your help.

Have you tried setting the LD_LIBRARY_PATH variable with /usr/lib before /usr/local/lib?

If that does the job then the set the LD_LIBRARY_PATH in the script that starts apache.

Whenever possible- try to use `crle` instead of setting LD_LIBRARY_PATH.

On that point this looks helpful:
Managing Library Paths with crle | ITworld

It'd probably be easier to rearrange the -L and -R options in the linker environment variables and put /usr/sfw/lib last instead of first.