...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
February 29, 2012

Prevent hotlinking to files using hashes?

Question by Andrew Butler

I am looking to have my files on my PHP site like so

http://mysite.com/files/file.exe?auth=qwe1245efmkrkn%$!e12 <– some generated hash…

I haven’t written any code, but I was wondering how I would implement the auth variable for a direct link to a file.. any ideas? Thanks!

Answer by Starx

You can do this, better with .htaccess

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?yourdomain.com [NC]
RewriteRule .(jpg|jpeg|png|gif)$ - [NC,F,L]

Copy and paste this code, rename it with .htaccess and save on the root.

As Gumbo mentioned, its true that some browsers, do not send any request header and forging a request is very easy, unless you apply CSRF protection on your website.
So an updated .htaccess to allow this

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?yourdomain.com/ [NC]
#Redirect to an image
RewriteCond %{REQUEST_URI} !hotlink.(gif|png) [NC]
RewriteRule .*.(gif|jpg|png)$ http://yourdomain.com/images/hotlink.png [NC] 

and adding

Header set X-Frame-Options DENY

ensures the website from being framed, even from the same website. Might be a little helpful against CSRF.

Alternative to this, might be redirecting an image request to a page to handle it.

Read more

The font is not being displayed at the bottom of the container?

Question by Beginner

This is my HTML code to display font with a background in a small container . .

here is the css

.cons_save h4{font:bold 22px/60px Arial,Helvetica, sans-serif;margin:20px 0px -15px 20px; color:#f78d1d;vertical-align: bottom; background:url(../images/save_bg_cons.png) no-repeat; width:151px; height:69px;}

im not able to put it ! in the bottom of that container whatever the other content above it in the container remains

My HTML CODE

<div id ="<?php echo $store->branch_id;?>Collect" style="display:block">    
 <span class="cons_save fl clr">
  <h4><?php echo $save. " %"; ?> </h4>
 </span>
</div> 

Answer by Starx

Don’t put heading tags insides spans

<div id ="<?php echo $store->branch_id;?>Collect" style="display:block">    
     <div class="cons_save fl clr">
        <h4><?php echo $save. " %"; ?> </h4>
     </div>
</div>

And also heading having a lot of margin & padding by default. So might be the reason to come in the bottom. Be sure to clear it

.cons_save h4 { margin: 0;padding:0; }

It works without the reset too, check here

Read more

how do you find the non-computed css width with JQuery

Question by coder

I know I can use .width() and .css('width') to get the computed width of an element, but how do I get the value that is set on the element for the width attribute? This is not the same value as the computed width and I need to know dynamically what the intended width is.

Answer by Starx

style attributes are changed, once you manipulate it using jQuery. So it cannot be retrieved later on. The best way, I think would be backing up at load if you need it.

$(function() {
   var backup = $("#element").attr("style");
   // do others
});

See this demo to get my point.

Later you can use .split() method to extract info like this

sp = backup.split(";");
$.each(sp, function(k,v) {
    var params = v.split(":");
    var att = params[0];
    var val = params[1];
    //alert(att+val);
});

Demo

Read more

Difference between normal cookies and Zend_http_cookies in PHP

Question by Kunal

I am learning a Zend Framework. Its going really difficult to me as compare to CodeIgniter. I have a problem of the difference between normal cookies(php) and zend_http_cookies. I am using normal cookies in my Zend application, it works but I want to understand Zend_http_cookies and its pure concept, can anyone tell me this..
thnx in advance.

Answer by Kunal

PHP cookie :

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

In PHP you can set cookie like this :

Example :

setcookie("user", "username", time()+3600);
//For getting cookie write:
echo $_COOKIE["user"];

Zend_Http_Cookie:

Zend_Http_Cookie is a class that represents an HTTP cookie. It provides methods for parsing HTTP response strings, collecting cookies, and easily accessing their properties.

You can instantiate it using :

$cookie = new Zend_Http_Cookie('user',
                               'user demo',
                               '.example.com',
                               time() + 3600,
                               '/path');

A cookie object can be transferred back into a string, using the __toString() magic method. This method will produce a HTTP request “Cookie” header string, showing the cookie’s name and value, and terminated by a semicolon (‘;’). The value will be URL encoded, as expected in a Cookie header:

Example:

// Will print out 'user=user+demo;' :

echo $cookie->__toString();

echo (string) $cookie;

echo $cookie;

For advance you should read zend documentation from framework.zend.com

Answer by Starx

Zend_Http_Cookie is not related to normal cookies. It is a part of Zend_Http_Client and is a class that represents an HTTP cookie.

It provides methods for parsing HTTP response strings, collecting cookies, and easily accessing their properties. It also allows checking if a cookie matches against a specific scenario, IE a request URL, expiration time, secure connection, etc.

Reference

Read more

Recursive data retrieval from database in Zend framework similar to CakePHP

Question by waseem

In CakePHP, we can provide recursive option while retrieving data from database, which automatically fetches the data from all the dependent tables.

We can also provide option for recursive e.g recursive=2, which fetches dependent tables of the dependent tables.

How can we achieve the same functionality in Zend framework?

Answer by Starx

If you have defined Table Relationship on your model before, you can use findDependentRowset() to retrieve records from multiple related table. For more details, see this.

But i am not sure of limiting the recursion.

Read more
February 28, 2012

jquery – leaving the hover state

Question by Marc

I have 2 div tag. The first contains a table. The second contains some text. When the page is loaded both div have no background-color. When there is an hover on a td of the first div, the second div background-color is set to yellow (see code below). My problem is that when I leave the table with the mouse, the background of the second div stays yellow. I would like the color to be remove on leaving the hover state. Hope someone can help. Thank you in advance for your replies. Cheers. Marc.

My HTML :

​<div id="div-one">
    <table>
        <tr><td>1</td><td>2</td></tr>
        <tr><td>3</td><td>4</td></tr>
        <tr><td>5</td><td>6</td></tr>
        <tr><td>7</td><td>8</td></tr>                   
    </table>
</div>

​<div id="div-two">
    some text
</div>

My JS:

$(document).on("hover", "#div-one td", function() { 

    $("#div-two").css("background-color":"yellow");
});​

Answer by Didier Ghys

Use mouseenter and mouseleave events separately – which is actually a “hover” event:

$(document).on({
    mouseenter: function() {
        $("#div-two").css("background-color", "yellow");
    },
    mouseleave: function() {
        $("#div-two").css("background-color", "");
    }
}, "#div-one td");​

DEMO

Answer by Starx

There is an error, you are using : when defining single property.
When defining a single property you should use ,

// For single property
$("#selector").css("property", "value");

//Define multiple properties
$("#anotherselector").css({
  property1: value1,
  property2: value2,
});

Solution

Use this

$("#div-one td").mouseover(function() {
    $("#div-two").css("background-color","yellow");
}).mouseout(function() {
    $("#div-two").css("background-color","white");
});

Or, if you want to keep on using .on() method

$(document).on("hover", "#div-one td", function() {
    $("#div-two").css("background-color", "yellow");
}).on("mouseout", "#div-one td", function() {
    $("#div-two").css("background-color", "white");
});

Demo

Read more

PHP : Cannot assign an Object to array

Question by Merianos Nikos

I have create the following class :

Main class file

class NativeTabs
{
    private $tabs = array();

    public function __construct()
    {
        require_once('/options_elements.php');
    }

    public function add_tab($key = '', $name = '')
    {
        // ...

        $this->tabs[$key] = $name;
        $this->tabs[$key][] = new OptionsElements();

        // ...

    }
}

$nt = new NativeTabs();
$nt->add_tab('tabname', "Tab Name");

options_elements.php File

class OptionsElements
{
    public function __construct()
    {
    }
}

And when I execute that code I get the following error :

Fatal error: [] operator not supported for strings in PATH/TO/MY/FILEnative_tabs.php on line THE_LINE_THAT_CONTAIN_THE_CODE($this->tabs[$key][] = new OptionsElements();)

Why I can’t assing the object in $this->tabs[$key][] ?

Any idea please ?

Answer by Nicola Peluchetti

You should do

$this->tabs[$key] = array();
 $this->tabs[$key][] = new OptionsElements();

otherwise you use [] with a string (you assigned $this->tabs[$key] = $name; on the line above so $this->tabs[$key] is a string)

Answer by Starx

This will work without errors.

$this->tabs[$key] = array("name");
$this->tabs[$key][] = new OptionsElements();
Read more

Better Way to write this to escape HTML content

Question by Viren

I have string which rich text content

something like this for example

<p>Hello</p>

<br/>

<p> Christian </p>

<pre> Don't Know what to do </pre>

Now I want dont want script to be present in the above content and if present esape it

so If I have content which look like this

<p>Hello</p>

<br/>

<p> Christian </p>
<script type="text/javascript"> alert("Hello")</script>
<pre> Don't Know what to do </pre>

Need to be replace with

<p>Hello</p>

<br/>

<p> Christian </p>
&lt;script type="text/javascript"&gt; alert("Hello")&lt;/script&gt;
<pre> Don't Know what to do </pre>

I have currently developed regex for it

so my code look something like this

if content.match(/<script(.+?)>/) {
  content = content.replace(content.match(/<script(.+?)>/)[0],content.match(/<script(.+?)>/)[0].replace("<","&lt;").replace(">","&gt;"))
}
if content.match(/<scripts*>/)
 {
content = content.replace(content.match(/</scripts*>/)[0],content.match(/</scripts*>/)[0].replace("<","&lt;").replace(">","&gt;"))
}

so the result content will have script tag escaped

Can anyone suggest me cleaner way to achieve this?

Answer by jensgram

Cleaner:

content = content.replace(/<(script[^>]*|/script)>/g, '&lt;$1&gt;');

However, this is probably not the way to go about this. Why are these <script> tags in the JS string in the first place?

Answer by Starx

Not the answer you are looking for but what if javascript is disabled? Are you going to let the unescaped content show up on the page. Hopefully NOT

Escaping must be done using a server side scripting like PHP, ASP.NET etc.

As in PHP, the htmlentities()[docs here] will do just fine

$escaped = htmlentities($content)
Read more

How to upload a file using a simple jquery-ajax call

Question by Alon

I am searching for a simple client-side script to upload a file using ajax.
Searching for the web for this script only brought up a lot of plugins with multi-features. I don’t need multi-feautres – just to be able to upload it as simple as possible using ajax

Is it possible to write something simple as:

$.get('server/upload.php?file = ' + $('#uploadInput').val(), function(data) {
   $('.result').html(data);    
 });

If it is possible – how should I write it right ($('#uploadInput').val() won’t give me the right directory path – so what do I need to do to pass the location using Ajax).

aside from that – in order to get drag&drop for files – Is there a simple script for that or do I need to use plugin (and is there a really tiny and simple one without multi-features)

Answer by Starx

Uploadify is another great solution for ajax upload. Its

  • extremely easy to setup,
  • very stylish, and
  • cross broswer.

See demos

Read more

Hover image and show it next to the cursor

Question by Johan

I would like to know if there is a way to show the same image as you are hovering, with a different size, next to the cursor? And on mouseout, it should disappear.

Answer by elclanrs

Something like this will work. Adjust to your needs. http://jsfiddle.net/elclanrs/jF27b/

var $img = $('img');
$img.hide();
$('div').mousemove(function(e) {
    $img.stop(1, 1).fadeIn();
    $('img').offset({
        top: e.pageY - $img.outerHeight(),
        left: e.pageX - $img.outerWidth()
    });
}).mouseleave(function() {
    $img.fadeOut();
});

Answer by Starx

Here is a simple way you can do it.

Markup Structure

<li class="thumb">
    <img class="small" src="http://stackoverflow.com/" />
    <img class="large" src="someimage.jpg" />
</li>

jQuery Snippet

$(".thumb").mouseover(function() {    
   $(this).children(".large").show();
}).mouseout(function() {
   $(this).children(".large").hide();
});

P.S: I am not going to test this code to work, because I completely agree with @OptimusCrime

Demo

Read more
...

Please fill the form - I will response as fast as I can!