...

Hi! I’m Starx

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

Prevent links from auto hyperlinking in Outlook etc using PHP

Question by Ben Carey

I know that this can be done using settings in Outlook, but that only sorts the issue for myself.

What I would like to do is use PHP to prevent text from being hyperlinked just because there is an @ sign etc…

As far as I can see, the only option for me is to encode all @ signs to their HTML numeric entity like so:

Something like this:

$message = str_replace('@','@',$message);

However, if possible, I do not want this to happen if the @ sign is part of an email address.

Therefore I need something like this:

// SOME_REGEX will match any @ sign that is NOT part of an email address
$message = preg_replace('SOME_REGEX','@',$message);

Can anybody think of any other better methods? Are there any flaws in this plan? Can anyone suggest a good regular expression for this? I am struggling to write a regex that matches an @ sign if it is not part of an email address

Thanks in advance

Answer by Anthony

This will not work if the email address is wrapped in anything not defined in the trim list.

$chunked_message = explode(" ", $message);

foreach($chunked_message as $chunk) {
    $clean_chunked_message[] = 
               (!filter_var(trim($chunk, " -().?!trn", FILTER_VALIDATE_EMAIL)) 
               ? str_replace('@', '@' $chunk) : $chunk;
}

$clean_message = implode(" ", $clean_chunked_message);

Good luck.

Answer by Starx

This is a feature of mail application to detect link when it is found and make it click able.

A dirty trick to escape this situation is to use space in between the links.

Example:

http://ww w.you tube.com/v=.......
Read more

Run PHP code when user clicks link and pass variables

Question by user1323294

I need to run a PHP code from external server when user clicks a link. Link can’t lead directly to PHP file so I guess I need to use AJAX/jQuery to run the PHP? But how can I do it and how can I pass a variable to the link?

Something like this?

<a href="runcode.html?id=' + ID + '"> and then runcode.html will have an AJAX/jQuery code that will send that variable to PHP?

Answer by Anwar

use something like this in you page with link

Some text

in the same page put this somewhere on top

<script language='javascript'>
$(function(){
$('.myClass').click(function(){
var data1 = 'someString';
var data2 = 5;//some integer
var data3 = "<?php echo $somephpVariable?>";

$.ajax({

url : "phpfile.php (where you want to pass datas or run some php code)",
data: "d1="+data1+"&d2="+data2+"&d3="+data3,
type : "post",//can be get or post
success: function(){
        alert('success');//do something
    }

});
return false;
});
});

</script>

on the url mentioned in url: in ajax submission
you can fetch those datas passed
for examlple

<?php
$data1 =$_POST['d1'];
$data2 =$_POST['d2'];
$data3 =$_POST['d3'];
//now you can perform actions as you wish
?>

hope that helps

Answer by Starx

You can do this with an ajax request too. The basic idea is:

  1. Send ajax request to runcode.html
  2. Configure another AJAX to trigger from that page

Considering, this as the markup

<a id="link" href="runcode.html'">Test</a>

JS

$("#link").on("click", function() {
    $.get("runcode.html", { "id" : ID }, function(data) {
       //on success 
    });
    return false; //stop the navigation 
});
Read more

Dynamic Select list using sql data

Question by Baruch

I am trying to create a select drop-down list using php. Every time i try, i get an error.
Here is my code:

The function:

function dropDown(){


$options="<select>"; 
$connect = mysql_connect('localhost','id','pass') or die ("couldn't   connect!").mysql_error; 

mysql_select_db('db') or die('could not connect to database!');


$sql="SELECT * FROM DESC"; 
$result=mysql_query($sql); 


while ($row=mysql_fetch_array($result)) {  ****this is line 60

$name=$row["name"]; 

$options.="<option value="$name">".$name."</option>"; 
} 

$options.= "</SELECT>";
return "$options";
}

and then i just call it in my code

<?php  
 include ('includes/functions.php');
....



$list = dropDown();
echo "$list";


....
>

the error i get is:

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/garagenj/public_html/dispatch/includes/functions.php on line 60

Answer by JT Smith

If your table name is DESC then that’s your problem. It’s all about namespacing. You can’t even have a field named desc, I’ve tried. It errors everytime

Answer by Starx

SELECT * FROM DESC ??????

  • From what table
  • Or, if the table name is DESC. escape them with ticks

And You dont have start a new connection, every time you call the function. Put your connection part somewhere else

$connect = mysql_connect('localhost','id','pass') or die ("couldn't   connect!").mysql_error; 
mysql_select_db('db') or die('could not connect to database!');

function dropDown(){
    $options="<select>"; 
    $sql="SELECT * FROM `DESC`"; 
    $result=mysql_query($sql); 

    while ($row=mysql_fetch_array($result)) { 

        $name=$row["name"]; 

        $options.="<option value="$name">".$name."</option>"; 
    } 

    $options.= "</SELECT>";
    return $options;

}
Read more
April 19, 2012

How many vars should there be in a cookie?

Question by Ted

While using cURL with some site, I noticed that some files that I requested actually used several variables from the cookie I set up with curl.

Here’s a snapshot:

enter image description here

But when I check my cookie file all it reads is just one value for ASP.NET_SessionId:

www.*******.***  FALSE  /  FALSE  0  ASP.NET_SessionId  ddj24l55lfu11nb1lhuflw55

Of course, the values from the snapshot are taken from my browser (Internet Explorer F12), and that cookie contains Three variables (not one).
Internet Explorer F12 cookie variables Name/Values:

NAME  ASPSESSIONIDSACRDADD 
VALUE  LOONCEMDHCGEJOANEGHHFAFH 

NAME  ASPSESSIONIDSCBRABDC 
VALUE  CMONJEMDNICPNPNFICLAPMFM 

NAME  ASPSESSIONIDQACSBADC 
VALUE  MCBOGLCCKNIDDBOADNMPCLCD 

this is my CURL settings for cookies:

$cookiefile = "d:/cookie.txt";

curl_setopt($curl, CURLOPT_COOKIESESSION, 1);
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookiefile);
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookiefile); 

What is it that I may be missingin cURL ?

Thanks!

Answer by Starx

By the nature of the div collection, it looks to be like variables are from different browser sessions.

And Even if its not, its up to developer on how to create your application to set and read the data.

Read more

Table Layout Issue

Question by ic3b3rg

I have the following simplified layout:

jsfiddle: http://jsfiddle.net/rersW/

<table>
  <tr>
    <td style="border:1px solid black;height:300px;width:100px">A</td>
    <td style="border:1px solid black;height:100%">
      <div style="border:1px solid blue;height:100%;width:100px">B</div>
    </td>
  </tr>
</table>

I need the blue outlined div to fill its cell. I’ve tried box-sizing on the div and the cell as well as changing the display of both (inline-block, etc.). Nothing I try is working.

The contents of cell “A” determine the height of the table.

The contents of cell “B” determine the width of its cell.

It must work identically in Chrome, Firefox, Safari, Opera & IE 8+

TIA

Answer by user1289347

Height:100% requires that the parent has an explicit height. Set the same height in cell b as you do in cell a, which is determining the table height, in this case 300px and the child div will expland.

EDIT
If you can’t explicitly define any of the parent heights you will need to use JS/Jquery. See here http://jsfiddle.net/rersW/3/

Answer by Starx

The reason is height: 100%; needs to be have a parent with height defined , or else you have to

  • either fix the height.
  • or Chain height: 100% all the up to body, if no height is fixed anywhere

TO illustrate my point upgrade your markup to this

<td valign="top" style="border:1px solid black; height: 300px;">
  <div style="border:1px solid blue;height:100%; display: block;width:100px">B</div>
</td>

Demo

Read more

Text box with default text

Question by anna

I have a text box with a default text. I am using javascript to dissapear it when the user clicks in this, but i want to make it work without javascript. Is there any way to do that in html or php? Thank you!

Answer by zellio

It can be done in flat HTML5 using the placeholder attribute of the <input> tag

<input type="text" placeholder="Default Text" />

Answer by Starx

In HTML5, there has been the introduction of new attribute called placeholder

You can use it like this

<input type="text" placeholder="text to show and hide" />
Read more

$_GET with Switch Statement

Question by Mor Sela

i have alot of get values that define the page the user gonna see , for example for “profile” i will show the profile page and so on..

to find out what page to display i tried to do something like that:

switch ($_GET) {
    case 'profile':
        require_once('function/profile.php');
        break;
    case 'team':
        require_once('function/team.php');
        break;

but it shows no result..

i send the GET request like that : index.php?profile , for example..

what is the problem here and how can i can manage to do something similar that work as well. thank you in advance!

Answer by stewe

To make your example work, you could replace $_GET with key($_GET)

Answer by Starx

$_GET is a super global variable, where the data are sent as stored as array. So you have to
access it using Index

Assuming you page you are trying to include a page when the data are sent like this:

domain.com?page=product

Then you have to use switch like this

switch($_GET['page']) {
   ....
}

Note: May be I dont have to remind you how vulnerable this code towards injection.

Read more

delete table row with javascript

Question by Craig

currently I have a table for information called episodes. The table has fields consisting of title, air date, episode number, and plot. I use javascript to clone the fields and also to delete them. My problem is the delete function deletes only the title, airdate, and episode number; however the plot box remains. The problem from what I can tell is that the plot is wrapped in a different <tr></tr> tag. How do i get the delete function to delete both sets?

Here is the table

<table id="template" style="display: none">
<tr class="line">
    <td width="50%">
    <label><?php _e('Episode Title'); ?></label>
    <p>
      <input type="text" name="episode_title[]" id="episode_title[]" value="" class="title regular-text" style="width:100%;" />
    </p>    
    </td>

    <td width"10%">        
    <label><?php _e('Airdate'); ?></label>
    <p>
      <input type="text" name="episode_airdate[]" id="episode_airdate[]" value="" class="airdate regular-text" style="width:100%" />
    </p>
    </td>

     <td width="10%">        
    <label><?php _e('Season:'); ?></label>
    <p>
          <?php

            for($i=1; $i<=50; $i++)
                $season_nums[]=$i;

            echo '<select name="episode_season[]" select id="episode_season[]" class="season regular-text" style="100%">';
                echo '<option value="">' . __("Season" ) . '</option>';
                foreach($season_nums as $season_num){
                    $selected = '';
                    echo '<option value="' . $season_num . '" ' . $selected . '>' . $season_num . '</option>';
                }
            echo '</select>';
            ?>
    </p>
    </td>

    <td width="10%">        
    <label><?php _e('Episode:'); ?></label>
    <p>
      <input type="text" name="episode_number[]" id="episode_number[]" value="" class="number regular-text" style="width: 100%" />
    </p>
    </td>



    <td width="10%" class="commands">
        <a rel="delete" class="button">-</a> <a rel="add" class="button">+</a>
    </td>


</tr>

<tr class="line2"> 
   <td width="100%">       
    <label><?php _e('Plot:'); ?></label>
      <textarea name="episode_plot[]" id="episode_plot[]" class="plot regular-text"value="" cols="100%" rows="10" tabindex="4" ><?php echo $_POST['episode_season'] ?></textarea>
    </td>
</tr>

Here is the JavaScript

        // Delete the "-" button in first row
    $('#attachments tr:first-child .commands a[rel="delete"]').remove();
}

function items_add()
{
    obj = $('#template tr').clone().appendTo('#attachments');
    lines++;

    if (arguments.length > 0) {
        options = arguments[0];

        $('.title', obj).val( options.title );
        $('.airdate',   obj).val( options.airdate );
        $('.season',   obj).val( options.season );
        $('.number',   obj).val( options.number );
        $('.plot',   obj).val( options.plot );
    }
}

$('#attachments').delegate('.commands a', 'click', function()
{
    var action = $(this).attr('rel');
    var confirm_delete = true;

    // Add action
    if ('add' == action) {
        items_add();
    }

    // Delete action
    if ('delete' == action) {
        // La TR en la tabla
        var oTr = $(this).parent().parent();
        var episode_name = $('.title', oTr).val();
        var episode_airdate = $('.airdate', oTr).val();
        var episode_season = $('.season', oTr).val();
        var episode_number  = $('.number', oTr).val();
        var episode_plot  = $('.plot', oTr).val();


        if (episode_name != '' || episode_number != '' || episode_plot != '') {
            if ( !confirm('Are you sure you want to delete ' + episode_name + '?') ) {
                confirm_delete = false;
            }
        }

        if (confirm_delete) {
            oTr.remove();
            lines--;
        }
    }
});

$(document).ready(function()
{
    items_init();
});

})(jQuery);

Your help will be greatly appreciated

Answer by Starx

Change this line

var oTr = $(this).parent().parent();

to

var oTr = $(this).closest("tr");

Then use oTr.remove()

Read more

How to get all input fields which aren't selects

Question by Hard worker

var $inputs = $('.add-item-form :input');

This gets all the input fields but also picks up the select fields which I do not want.

e.g.

<select><option>example</option></select>

Answer by T.J. Crowder

:input is a jQuery-specific pseudo-selector for input, textarea, button, and select elements. So you could do this:

var $inputs = $('.add-item-form :input:not(select)');

…but you can also just call out specifically what you want:

var $inputs = $('.add-item-form input, .add-item-form textarea, .add-item-form button');

…which would have the advantage that if the browser supports querySelectorAll (and nearly all do, in standards mode), jQuery can just hand off to native handling (whereas :input is specific to jQuery, so can’t be handled by the browser’s native stuff).

Or, of course, if you don’t want textarea and button elements, it’s really simple:

var $inputs = $('.add-item-form input');

…and again that has the advantage of being handled by the browser’s optimized stuff where possible.

Answer by Starx

Use a .not() to omit the select boxes

var $inputs = $('.add-item-form :input').not("select")

Or use CSS style :not selector

var $inputs = $('.add-item-form :input:not(select)');
Read more
...

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