PHP search & replace img src - php

Ok, the situation is simple (i hope!)
I am working locally (xampp) and in my .php file i've got the following img elements :
<img src="http://example.com/images/project-1/image1.jpg"/>
<img src="http://example.com/images/project-1/image2.jpg" />
<img src="http://example.com/images/project-1/image3.jpg" />
How can I make it to run a search and replace function (with php if possible) that will fulfil the following:
1) On page load to scan the whole document and find all the above images that don't appear (broken links)
2) IF from the above we find broken images , then to replace only the part that says "http://example.com" with "http://127.0.0.1/projectfile".
So what I want is to scan the whole document for broken images and if I find x of them then to replace the src from this:
src="http://www.example.com/images/project-1/image1.jpg"
with this:
src="http://127.0.0.1/project/images/project-1/image1.jpg"
I want to do this for all the images automatic, and not manually.
Currently I am struggling to do this with jQuery but I probably I am gonna need PHP because I need to navigate to the previous folders,scan dir etc etc
Thank you for you support!
Any ideas or tips?
So far what I tried and succeeded partially as I said above is to search/replace with jQuery:
$('img').attr('src',function(i,e){
return e.replace("http://example.com","http://127.0.0.1");
})
,which ignores the live website src folder and sticks directly to the local folder but I need to make it a bit more clever :)

Use jquery error event to detect missing images and replace them. Following code should do the trick
$(document).ready(function(){
$('img').on('error',function(){
// Avoid endless loop for noexistant images
if($(this).data('alreadyChecked')) return;
$(this).data('alreadyChecked',true);
//Replace src
$(this).attr('src', $(this).attr('src').replace("http://example.com","http://127.0.0.1"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="http://example.com/images/project-1/image1.jpg"/>
<img src="http://example.com/images/project-1/image2.jpg" />
<img src="http://example.com/images/project-1/image3.jpg" />

A solution with .htaccess is the best approach for this. PHP wont do it because PHP executes before the page loads. By the time these elements are on your page, it's already too late for PHP to touch them. I'm sure a hack with jQuery could work on this but it wont be reliable and it will slow down your loads and you will likely have flicker because jQuery can't touch the items until after the page loads, and at that point your broken links will already be showing until jQuery replaces them.
Try this in your .htaccess file:
RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteCond %{REQUEST_URI} \.(gif|jpg|jpeg|png)$
RewriteRule ^.*/images/(.*)/(.*)$ http://127.0.0.1/project/images/$1/$2 [L,R=301]
.htaccess will replace the URLs at the request level before PHP or jQuery ever even see the content.

The best way to achieve what you want is to use javascript/jquery and replace the href value when the condition (broken link) is met.

Thank you guys!!
Although I was initially looking for a PHP way to do this, apparently JQuery worked as well!
Thanks #Nadeem Manzoor and the rest! :)

Related

URL rewrite problems

I wanted to pass the parameters to my PHP page in a friendly fashion, so here's what I wrote in .htaccess file
RewriteRule ^confirm\/(([a-z0-9]).+)\/(([a-z0-9]).+)$ www.example.com/confirm.php?email=$1&order=$2
its working well, and I can get the parameters in PHP using
explode('/', $_SERVER['REQUEST_URI'])
I have 2 problems though,
1- when I submit this page, I need it to go directly to confirmation.php, instead it submits to www.example.com/confirm/example#mail.com/12-HDYF/confirmaction.php !!! how can this be changed.
2- the page was originally working perfectly, but when I type the friendly URL all jquery files give me the below error, which really seems unrelated.
That is because the client (the browser) sees the page it is browsing as www.example.com/confirm/example#mail.com/12-HDYF/ and when it analyzes it and parses the html, it sees it something like:
<script src="jquery.js"></script>
<form action="confirmation.php"... >
So the browser sees relative urls to the page he is at the moment. So if you tell him to search the jquery.js file in the same folder as the one he currently is, he is going to try to download from www.example.com/confirm/example#mail.com/12-HDYF/jquery.js, and the same thing happens when you submit the form.
To avoid this, use absolute URLs (note the leading slash):
<script src="/jquery.js"></script>
<form action="/confirmation.php"... >
If you have your files in a subfolder of the DocumentRoot, put that subfolder at the beginning of the URL.
Change your url structure to avoid ^confirm for both raw and friendly URL, that should make things easier to debug (and avoid loops). This is a guess since you haven't posted your input that fails.
RewriteRule ^orderconf\/(([a-z0-9]).+)\/(([a-z0-9]).+)$ www.example.com/confirm.php?email=$1&order=$2

Can I modify anchor tag href in htaccess?

Not sure if this is possible but wanted to know if htaccess has a trick...
Say I have anchor tag href like this -
Click here
I have changed the URL structure using mod_rewrite but wanted to know if i can hide the actual URL in href using htaccess.
i.e when a user hover over the anchor tag, the browser displays http://example.com/index.php?id=12345 at the bottom. All I want the browser to display is http://example.com/index/12345 without changing it manually on all my pages.
Thanks for the help !
Why don't you change the link to the following?
Click here
As you can change the .htaccess I expect that you own or adminstrate this domain. So it should be possible.
If the links are generated by PHP code, then I suggest you to implement and use a translation function like:
function beautify($ugly) {
// your logic comes here
return $nice; // ;)
}
... and wrap it around the existing code that currently outputs the urls. This would have two advantages:
It's easy and more failsafe to migrate to the new url scheme
From now on you have control over all url related code using a single function
I agree, htaccess can't help you. I guess you'll have to change them manually.
I wish I could be of more help
No. htaccess is for processing input to the web server, not data sent back from the server.
If you use jQuery you could have it rewrite the href when the page loads using something like this.
$(function(){
$("a").each(function() {
this.href = 'some_new_url that you made based on the one in this.href';
});
});

Use mod_rewrite to change directories to variables... does this work?

If I have a link, for example: dashboard/xyz/fff/ and I use modrewrite to change it to dashboard/?loc=xyz&action=fff when the page loads are loc and action available as variables to use?
If so, then here's a specific example I can't seem to get to work. My rule as it sits:
RewriteRule ^getclients/([a-z\-]+)$ /dashboard/?action=getclients&module=$1
And the link that is sending them to that url:
<li>SEO Analysis</li>
I want now to be at .com/dashboard/?action=getclients&module=$1 and use those variables to load the page content that's needed.
However: Now the page redirects to what I believe is the "right page" but the CSS is all broken. I only have plain text. Feel free to suggest another way to achieve the same effect as well perhaps using jQuery and Ajax or something to load up sections of the site.
Thanks!
If you don't want to use absolute paths, you can try rewriting the requests for images, javascript, and css. Maybe something like this:
RewriteCond %{REQUEST_FILENAME} \.(js|css|png|jpe?g|gif)$ [NC]
RewriteRule ^getclients/(.+)$ /dashboard/$1 [L]
Make sure that the file locations are exact, or the server might send the data from the wrong relative directory.
For loading css, images, js files properly from a different relative path you should specify a base URL for all relative URLs on a page like this:
<base href="http://www.example.com/dashboard/" />

how can i make script like this: <script src="mysite.com/dir/"></script>

i know, this looks stupid, but i am a new one in scripting so please help, i want my src not be ending with file with extension. like:
<script src="mysite.com/dir/"></script>
and NOT like this:
<script src="mysite.com/dir/script.js"></script>
is this done with HTACCESS or with what?
P.S. I want to create something like a hitcounter and dont want athers to see my script code
here is an sample:
<script type="text/javascript" src="http://topsite.ucoz.com/stats"></script>
if you run this in html it will sent a mini banner and an hiden iframe with that page.
Use url rewrites in your .htaccess like this:
RewriteEngine On
RewriteRule ^dir/$ /dir/script.js [NC]
The problem with this is that /dir/ cannot be used for anything else.
What you could do is something like this:
RewriteEngine On
RewriteRule ^script/$ /dir/script.js [NC]
However this does not solve the problem of people seeing your code at all.
The only solution to that is either code obfuscation or using php (or some other server-side language)
You can configure your web server to have a default page when you call a directory.
This is usually done for index.html, index.php, ...
And here say this default is script.js the server should then deliver it by default
The first one is to a directory and not a file. It doesn't really make sense unless your thinking how on most servers http://abc/index.html goes to http://abc/
Cant really do it and cant see why you'd want to.
Either use the htaccess code listed to rewrite your url or simply fill your index.php with javascript.
and actually, using a url-rewrite would make it pointless having an index.php/index.html there in the first place.
mysite.com/page.php:
<script type="text/javascript" src="/dir/"></script>
mysite.com/dir/index.php:
alert('hello world');
also the sample you listed shows an example of someone using a file, not a whole directory. they simply leave off the extension to their file. Extensions only have semantic value.
I think the main goal here is 'to hide javascript from the user' right?
If you want to hide a javascript, you may want to lookup for 'javascript obfuscation'.
You can't really hide javascript, because it must be able to run on the client browser.
Even if you set the default url, as answers stated above, the javascript file will be downloaded.
However, you can obfuscate javascript files so that it will be hard for humans to read while machines can execute it.
There is a question in SO that ask about it.
How can I obfuscate (protect) JavaScript?

How to use htaccess to change image paths?

I have a html file that has an image:
<img src="../smilies/happy.gif" />
Is it possible to redirect this path to another using .htaccess?
So the above example would become equivalent to
<img src="http://static.example.com/smilies/happy.gif" />
Well, you might get away with redirecting all calls that end with /smilies/happy.gif to that directory, so it wouldn't matter where the call came from. That does mean you should not wish to call this to some other subedirectory, but I imagine you don't.
something like this (guessing here, cann't test, so read up on the rwriting there :)
RewriteRule ^(.*)/images/$(.*) http://static.example.com/smilies/$2 [L,R=301]
basically you are rewriting everything that has '/images/' in it to that static adress, pasting whatever was after images after the new asdress (the $2 thingy) and then indicating that this is the last command to parse (to stop strange things in the htaccess) and that you want a 301 (permanently moved) code to be sent.
I think its easier to set a variable in your config
<?php
$static_url = "http://static.example.com/";
?>
<img src="<?php echo $static_url; ?>/smilies/happy.gif" alt="" />
Its better then you have the control what came from static and the rewrite engine is slow when you call it everytime its not sooo good.
RewriteRule ^(smilies/.*)$ http://static.example.com/$1 [R]

Categories