...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
May 7, 2013

How exactly is PHP creating superglobal $_POST, $_GET, $_COOKIE and $_REQUEST?

Furicane’s Questions:

I’m sorry for confusing title of the question, I’ll try to clarify what the issue is.

I’m doing some work with Mongrel2 server and I’m writing a PHP handler that has access to raw HTTP request data. Because I have PHP behind Mongrel2, there is no automatic creation of $_POST, $_GET, $_COOKIE and $_REQUEST variables.

The question is – is there a way that I can send the raw HTTP request to a PHP function (or anything) that will produce the superglobal variables that are usually available when using Apache + PHP?

Note: I could parse the HTTP request manually and create those variables myself, but I wasn’t able to find any documentation on how exactly PHP does this HTTP parsing and importing into superglobals. If possible, I’d like to automate this process of superglobal creation without having to parse HTTP requests myself.

Thank you for any input.

Creating these variables is handled deep within the guts of PHP, in main/php_variables.c, in the php_auto_globals_create_get() and similar functions. From PHP 5.4.3:

static zend_bool php_auto_globals_create_get(const char *name, uint name_len TSRMLS_DC)
{
        zval *vars;

        if (PG(variables_order) && (strchr(PG(variables_order),'G') || strchr(PG(variables_order),'g'))) {
                sapi_module.treat_data(PARSE_GET, NULL, NULL TSRMLS_CC);
                vars = PG(http_globals)[TRACK_VARS_GET];
        } else {
                ALLOC_ZVAL(vars);
                array_init(vars);
                INIT_PZVAL(vars);
                if (PG(http_globals)[TRACK_VARS_GET]) {
                        zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_GET]);
                }
                PG(http_globals)[TRACK_VARS_GET] = vars;
        }

        zend_hash_update(&EG(symbol_table), name, name_len + 1, &vars, sizeof(zval *), NULL);
        Z_ADDREF_P(vars);

        return 0; /* don't rearm */
}

This ends up calling directly into the SAPI (e.g, Apache module / CGI / FastCGI / whatever) to fetch variables. I don’t think there’s any way you can alter the way this works if you’re in a weird environment where GET/POST/etc variables aren’t where PHP expects them to be.

I am trying to contribute to this question with the knowledge I know.

Sending a HTTP Request with such headers can duplicate POST variable

POST /somepage.php HTTP/1.1
Host: www.domain.com
User-Agent: Mozilla/12.0
Content-Length: 31
Content-Type: application/x-www-form-urlencoded

parameter=value&testcode=value1

Also you might want to check the HttpRequest libray of PHP. [Start here]. For POST data you can override the previous POST content using HttpRequest::setPostFields() and set your own data for it.

HttpRequest::setPostFields(array(
    "parameter" => "value"
));
Read more

Setting default content of container when page loads/refresh then changes after click event fires

Olubunmi’s Questions:

I am trying to set default content of a container when page loads/refresh, so that it does not look empty until click event that populates the container is fired.

The jQuery i’m working with looks like this

$(document).ready(function() {
$('[class^="question"]').on('click', function(e){
e.preventDefault();
var numb = this.className.replace('question', '');
$('[id^="answer"]').hide();
$('#answer' + numb).show();
});

});

My html makeup looks like this :

<div class="new_member_box">
     <a href="#" class="question1"><h4>Vision</h4></a>
</div> 

<div class="new_member_box_display" id="answer1">
    1
</div> 

  <div class="new_member_box_display" id="answer">
    Default
</div> 

When The page loads, Default text is shown, but when I clicked Vision link, 1 is shown then Default is shown in a box below it. What i want is that Default shows when page loads/refresh, then when a link is clicked default disappears and then the value for the clicked links is shown.

Lets break down your code:

$('[id^="answer"]').hide(); //This hids all the elements starting with answer as id

$('#answer' + numb).show(); // and show a particular answer

But the default content box in your demo has question as an id

<div id="question" class="new_member_box_display">
    Text will appear here when one of the tabs above is clicked
</div>

So your script will not effect this part. A valid solution would be to add a class to represent this div as a default box. Something like

<div id="question" class="new_member_box_display default">
                                          <!--    ^ I added a class here -->
    Text will appear here when one of the tabs above is clicked
</div>

Then, in our script we will hide that first.

$(function() {
    $('[class^="question"]').on('click', function(e){
        e.preventDefault();
        var numb = this.className.replace('question', '');
        $('.default').hide(); // Lets hide that first
        $('[id^="answer"]').hide();
        $('#answer' + numb).show();
    });
});
Read more

Accessing Object within Array

Viablepath’s Questions:

I have the following output:

Array (
  [0] => stdClass Object (
        [id] => 20
        [news_title] => Startup finance docs in GitHub
        [news_url] => http://venturebeat.com/2013/03/06/fenwick-west-github/
        [news_root_domain] => venturebeat.com
        [news_category] =>
        [news_submitter] => 4
        [news_time] => 2013-03-06 11:20:03
        [news_points] => 0
    )
    [1] => stdClass Object (
        [id] => 21
        [news_title] => The problems with righteous investing
        [news_url] => http://gigaom.com/2013/03/07/the-problems-with-righteous-investing/
        [news_root_domain] => gigaom.com
        [news_category] =>
        [news_submitter] => 4
        [news_time] => 2013-03-08 09:14:17
        [news_points] => 0
    )
)

How would I access something like news_url in these? I’ve tried this, but to no avail:

print_r $this->$record[0]->news_title;

Your code is a little incomplete, and hard to follow, but try this:

 $arr =    Array();

    $obj0 = new stdClass;
    $obj0->id = 123;
    $obj0->news_title = "some title 0";
    //etc...
    $obj1 = new stdClass;
    $obj1->id = 124;
    $obj1->news_title = "some title 1";
    //etc...

   $arr[0] = $obj0;
   $arr[1] = $obj1;

    print_r($arr);

or something like

print_r($arr[0]);

or even

 echo $arr[0]->id;

You are using class property, you might want to check if it is accessible first. While accessing the class property after using $this you dont need the additional $, just use $this - record. Like

echo $this -> record[0] -> title;

If record is a valid class property which is an array and it still does not work. Give this a try too:

echo {$this -> record[0]} -> title;
Read more

How can I dynamically print to another table with JQuery/Javascript?

Steve ‘s Questions:

I am a beginner in JQuery/Javascript, so I appreciate any help in advance.

I have two scripts/tasks. Using JQuery. the first script parses a file and report its contents in table form. The goal of the second script is to run an analysis and display results in a separate table.
The first task is successful, however, for the second task, instead of populating the second table, the data appends to the first table. What am I missing here?

file.html

<section id='results'>
  <p><span id='program'>no</span> program used.</p>
  <p><span id='match_count'>0</span> match(es) found.</p>
  <button name="resubmit" id="resubmit" type="submit">Save selected results</button>
  <table>
    <thead>
      <tr>
        <td>Save?</td>
        <td>DB</td>
        <td>Accession</td>
        <td>Description</td>
        <td>Score</td>
        <td>E-value</td>
        <td>Start</td>
        <td>Stop</td>
      </tr>
    </thead>
    <tbody>
      <!-- this will be filled in by javascript when there are results -->
    </tbody>
  </table>
</section>

<section id='dbresults'>
  <p><span id='db_count'>0</span> match(es) found.</p>
  <table>
    <thead>
      <tr>
        <td>Accession</td>
        <td>Description</td>
        <td>Structural</td>
      </tr>
    </thead>
    <tbody>
      <!-- this will be filled in by javascript when there are results -->
    </tbody>
  </table>

file.js

function processJSON( data ) {
// set the span that lists the match count
$('#match_count').text( data.match_count );
// set the span that lists the program used
$('#program').text( data.program );
var next_row_num = 1;
// iterate over each match and add a row to the result table for each
$.each( data.matches, function(i, item) {
        var this_row_id = 'result_row_' + next_row_num++;
        $('<tr/>', { "id" : this_row_id } ).appendTo('tbody');
        $('<td/>', { "text" : item.database } ).appendTo('#' + this_row_id);
        $('<td/>', { "text" : item.accession } ).appendTo('#' + this_row_id);
        $('<td/>', { "text" : item.description } ).appendTo('#' + this_row_id);
        $('<td/>', { "text" : item.score } ).appendTo('#' + this_row_id);
        $('<td/>', { "text" : item.evalue } ).appendTo('#' + this_row_id);
        $('<td/>', { "text" : item.start } ).appendTo('#' + this_row_id);
        $('<td/>', { "text" : item.stop } ).appendTo('#' + this_row_id);
    });
$('#results').show();
}

function processJSON_db( data ) {
$('#db_count').text( data.db_count );
var next_row_num = 1;
$.each( data.dbmatches, function(i, item) {
        var this_row_id = 'result_row_' + next_row_num++;
        $('<tr/>', { "id" : this_row_id } ).appendTo('tbody');
        $('<td/>', { "text" : item.accession } ).appendTo('#' + this_row_id);
        $('<td/>', { "text" : item.description } ).appendTo('#' + this_row_id);
        $('<td/>', { "text" : item.structural } ).appendTo('#' + this_row_id);
    });
$('#dbresults').show();
}

You have ambiguous row ids. IDs always have to be unique. If you must use common name between rows of two tables use class or else you have use a different row id.

Here are the illustration of both methods.

Using Unique ID:

var this_row_id = 'table_2_result_row_' + next_row_num++;

Differentiate your row id like above

Class:

$.each( data.dbmatches, function(i, item) {
    var this_row_id = 'result_row_' + next_row_num++;
    $('<tr/>', { "class" : this_row_id } ).appendTo('tbody');
    $('<td/>', { "text" : item.accession } ).appendTo('#tableid .' + this_row_id);
    $('<td/>', { "text" : item.description } ).appendTo('#tableid .' + this_row_id);
    $('<td/>', { "text" : item.structural } ).appendTo('#tableid .' + this_row_id);
});

or Choose to use class names instead

Read more
May 6, 2013

How to make a floating menu appear after you scroll past a certain point?

JonnyBravo’s Questions:

I want to make four menu tabs appear after you scroll past a certain point (ex: 1000px) on the page. I want them to slide in from left to right when they appear. This is what I’m going for, but on the left side of the browser. Any input is appreciated.

Thanks

First you’re going to want to start by tracking the scrolling of the page. Second you’re going to want to animate the divide from left to right when needed. To do this, you’ll need to use the scroll function, and a few others for the animating part.

Here’s a base to what you want, without the scroll.

function slider() {
    if (document.body.scrollTop > 100) //Show the slider after scrolling down 100px
        $('#slider').stop().animate({"margin-left": '0'});
    else
        $('#slider').stop().animate({"margin-left": '-200'}); //200 matches the width of the slider
}

Now you’ll want to fire this function while the user scrolls, using:

$(window).scroll(function () {
    slider();
});

And finally, you’ll also want to call the function when the user first arrives, incase the user starts half way down the page, using:

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

A few things to note:

I’ve hard coded the sliders width to 200px, and the start point to 100px.
The stop() function is very important and stops the animate function from being called redundantly.

Here’s a working jsfiddle with the matching CSS

You have to monitor the scroll position of the window as the user scrolls through the page.

Here is a basic explanation:

$(window).scroll(function() {
    //This gives the scroll position
    var scrollTop = $(window).scrollTop();
    if(scrollTop >= 1000) {
         //If user has scrolled about 1000 px below then

         // .... Your code to bring the links from left to right
    } 
});
Read more
April 29, 2013

Fade out a border with CSS

User2180108’s Questions:

I have a footer that has a dashed top border like so:

footer 
{
border-top:1px dashed #ddd;
color:#999;
}

I was wondering how I would be able to make the dashed line fade out from left to right. Thanks!

You can create this using CSS Gradients. Check here.

To make it as simple as possible, start off by creating two divs:

<div id="borderbox">
    <div id="box">
    </div>
</div>

We will use the outer box and give it a Gradient Background and then give a white background to the inner div, thus faking the border.

#borderbox {
    background-color: #eee; /* fallback color if gradients are not supported */
    background-image: -webkit-linear-gradient(to right, #000, #fff); /* For Chrome and Safari */
    background-image:    -moz-linear-gradient(to right, #000, #fff); /* For old Fx (3.6 to 15) */
    background-image:     -ms-linear-gradient(to right, #000, #fff); /* For pre-releases of IE 10*/
    background-image:      -o-linear-gradient(to right, #000, #fff); /* For old Opera (11.1 to 12.0) */
    background-image:         linear-gradient(to right, #000, #fff); /* Standard syntax; must be last */    
    width: 500px;
    height: 200px;
    display: block;
    padding: 1px 0 0 0;
    opacity: 0.5;
    border-top: 1px dashed #ccc;
}
#box { background: #fff; width: 500px; height: 200px;  margin-top: -1px; }

Demo: http://jsfiddle.net/XwJEB/1

Read more
April 22, 2013

PHP – Can I shift an array from a specific key?

Sebastian’s Questions:

I was having a little trouble with my array in PHP.

I have the following the array:

Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
    [3] => kiwi
    [4] => cherry
    [5] => nuts
)

But I want to kick out ‘kiwi’ and shift all other keys up, to get the following…

Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
    [3] => cherry
    [4] => nuts
)

I am sure someone here knows how to get it done, php’s shift only takes to first key and not something specific.

Thanks in advance

This is what array_splice does for you. It even lets you insert new entries there if you so choose.

AFAIK, There is not any inbuilt function to do this, but you can create one. What you have to do is, delete an specific element and then recalculate the keys.

function a_shift($index, $array) {
     unset($array[$index));
     return array_values($array);
}
Read more

How to replace text with links using javascript?

Hick’s Questions:

This is what I do to take out texts from a html usng Jquery:

$(".text").each(function(){

        var texts = items[textCount]['data']['title'];
        $(this).text(texts);
         textCount = textCount + 1;
      });

My problem if I want the texts to be a url, then it doesn’t show up as link but also a string added to the texts variable. How do I show a link? How can add it as a href to the texts?

Output should be something like this:

Text + url

and not text being linked as url: "<a href=""+link+"">"+texts+"</a>"

Using .attr() function like this.

$(this).attr("href", "your link");

But this will only work, if you have an anchor tag if not you can create an anchor tag on the fly.

$(this).html("<a href=""+link+"">"+texts+"</a>");
Read more

For loop not creating Div

Fstephen07’s Questions:

I’m attempting to create multiple divs on the fly by using a for loop. This code does not give any results. My expectation is for it to create separate divs with the id a1,a2,a3, etc. Can anyone explain why it doesn’t? I understand there are other solutions to this on SO, but this is a learning experience for me and I want to know why my solution does not work.

function createDiv(divid,divcontent){
  this.div = document.createElement("div");
  this.div.setAttribute("id",divid);
  this.div.innerHTML = divcontent;
}

var keys = [1,2,3,4,5,6,7,8,9,0];
for (i=0; i<keys.length;i++){
    createDiv("a"+i,i);
}

You’ll have to append the node to a parent – existing – node in the document to make it appear. Like this:

function createDiv(divid,divcontent){
  this.div = document.createElement("div");
  this.div.setAttribute("id",divid);
  this.div.innerHTML = divcontent;

  var parent = document.getElementById('mydiv');
  parent.appendChild(this.div);
}

Your function only creates the div you have to add it to the DOM

function createDiv(divid,divcontent){
  this.div = document.createElement("div");
  this.div.setAttribute("id",divid);
  this.div.innerHTML = divcontent;
}

var keys = [1,2,3,4,5,6,7,8,9,0];
for (i=0; i<keys.length;i++){
    var newDiv = createDiv("a"+i,i); //Store the div you just created here
    document.getElementById('yourdivcontainer').appendChild(newDiv); //And add it to the DOM
}
Read more
April 21, 2013

HTML File Upload action – can this be hacked to spam endless file uploads

Adam’s Questions:

I have a question about hacking file uploads. Below shows the kind of setup I’m using and my concern is around the action that gives the full path to the upload script:

<form action="http://www.mydomain.com/scripts/php/photo_processing.php?page=join method="post" enctype="multipart/form-data">
  <input type="file" name="file" class="fileProfile"><br>
</form>

Can someone use the full path to send repetitive files constantly and then fill a web server disk space etc? eg: can you send files using this path outside the website and/or in a way that allows automated constant uploads?

Note: the php file has the following at the top – it is set to only this domain name – needed because of AWS Cloudfront POST limitation

header("Access-Control-Allow-Origin: http://www.mydomain.com");

No, they are basically prevented by cross domain policy. Unless the mydomain.com gives you access to it.

Read more
...

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