James_43 15 Junior Poster

Correct :) 10.0.0.0 for physical LAN, and ideally 10.0.1.0 for virtual LAN.

Though I also have a different subnet on my WAN adapter, 192.168.209.0. At the moment the Lan and Wan are passing packets through iptables.

James_43 15 Junior Poster

Hi all, I'm having a lot of trouble with building a network for my virtualised OS's.

The server has two physical NICs for LAN and WAN. The host has IP 10.0.0.1. I use the following iptables to bridge them.

iptables -t nat -A POSTROUTING -o wan -j MASQUERADE
iptables -A FORWARD -i wan -o lan -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i lan -o wan -j ACCEPT

I now also have a virtualised Windows Server. I have told the virtual server to use the virbr01 network adapter, which I define in /etc/network/interfaces as below:

# Virtual bridge dummy
auto virbr01-dummy
iface virbr01-dummy inet manual
        pre-up /sbin/ip link add virbr01-dummy type dummy
        up /sbin/ip link set virbr01-dummy address 52:54:00:77:a4:d6

# Virtual bridge
auto virbr01
iface virbr01 inet static
        bridge_ports virbr01-dummy
        bridge_stp on
        bridge_fd 2
        address 10.0.1.1
        netmask 255.255.255.0

From the linux host, I can ping 10.0.1.1 successfully, and for the meantime I've set the Windows guest to have a static ip of 10.0.1.2 and a default gateway of 10.0.1.1 (until I move to DHCP).

I'm now having issues connecting to the guest from the host, or the wider LAN network. The iptables I have used are below:

-A FORWARD -d 10.0.0.0/24 -o virbr01 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -s 10.0.0.0/24 -i virbr01 -j ACCEPT
-A FORWARD -i virbr01 -o virbr01 -j ACCEPT
-A POSTROUTING -s 10.0.1.0/24 ! -d 10.0.1.0/24 -j MASQUERADE

As far as I can see, this should forward my requests from the LAN …

James_43 15 Junior Poster

I'm confused here. Queries are not my strength...

So I do two queries, each getting 10 items from each table. Then I sort that table by date, giving me the most recent events. I can follow this much. Doing a left join will give me the rest of the data I want, no problem.

However, when it comes to offsetting the intermediate query, not sure what you mean. Effectively, I have an array of ids from different tables:

[] => 'item',
[] => 'item',
[] => 'item',
[] => 'item',
...

I can do a left join to get the data I need, but I cannot offset that query to get the 10 next recent queries. The only way I can think of is to find out how many items I took from table 1 and how many from table 2, and then passing that as the offset for the next "page two" query.

That would work, but really messy and means I would have to pass more than just the page number to a function. But are you saying there is an easier method?

James_43 15 Junior Poster

Yes, but what happens when I want to view "page 2" of this query? Will having an offset of 10 on the original queries be enough here?

James_43 15 Junior Poster

Hi all,

I'm using the Laravel framework to create an application, and have a database question.

I have a table called posts. I have been pulling the 10 most recent rows from here and making use of an offset variable for pagaination.

Now however I also have a table media that has a completely different table structure. What I want to be able to do it to pull the 10 most recent posts and media rows (10 in total, not 10 of each).

I can't merge two LIMIT 5 queries together, because it is possible that the first media row is older than the 6th posts row, and in that case it should take precedence and there would only be 4 items from the media table.

Does anyone know of anything I can try here>

James_43 15 Junior Poster

Hi all,

Say I have a table called "posts" with thousands of records. For each user, I want to display the top 10 most recent posts.

I would normally use:

select * from posts order by created_date desc limit 10

However, doesn't this select ALL records and then removes all but the top 10. For a huge database, this wouldn't be efficient.

Can anyone suggest an alternative?

Cheers!

James_43 15 Junior Poster

Hi all,

Submitting forms to PHP is easy with Ajax. But what if I wanted to design my website to allow for JS-free web browsers?

If I call a PHP file with Ajax, I might get an error message in return to dynamically add to the page, but if I POST data to a PHP form without Javascript, I need to get a whole page of HTML back. Therefore, to allow for both, i would need a way for the PHP code to detect whether a request was an AJAX request or not.

How do I do this?

James_43 15 Junior Poster

Yes. Not only did that fix it, but got rid of the .each() function :) Thank you very much!

James_43 15 Junior Poster

I realise this isn't about the DOM updating. I use the following functions to pull up the elements and process their click events:

$('.like').each(function(i, obj){

    $(this).click(function(e){

        var element = $(this);

        //stuff
        })
});

Obviously since the .each() function loads with the page, it doesn't take into account anything I add dynamically... How can I add the objects I add to the DOM dynamically?

James_43 15 Junior Poster

Hi all,

I have a text box. When users press enter, it triggers the submit function:

commentContent.keydown(function(e){
    if(commentContent.is(":focus") && (e.keyCode || e.which) == 13 && !e.shiftKey)
    {
        e.preventDefault();
        commentForm.submit();
    }
});

This then prepends the content of the text box into the HTML.

commentsHere.prepend(commentData);

However, when I search for this new element by id and class, it doesn't register. Do I need to tell JS to refresh the DOM so I can find it? I have read some discussions about using .on(), does that mean I need to register an event to listen for prepend events??

James_43 15 Junior Poster

Thank you,that's a MUCH cleaner way of doing this!

James_43 15 Junior Poster

Hi all,

I've been trying to create a friendly time function for a while, it's purpose should be quite obiovus from the code below. Currently, it outputs "expired" for everything.

I am so utterly confused from visualising the code and trying to figure out where the times lie in relation to each other, so I would really appreciate if some good soul could come along and make any suggestions.

public function generateFriendlyTime($time)
    {
        if(!is_numeric($time))
        {
            $time = strtotime($time);
        }

        $current_time = time();


        if($time < $current_time)
        {
            return 'expired';
        }

        //If less than a minute
        elseif($time < ($current_time + 60))
        {
            return "< " . 1 . "m";
        }

        //If less than an hour
        elseif($time < ($current_time + 3600))
        {
            return round(($time - $current_time) / 60) . "mins";
        }

        //If less than a day
        elseif($time < ($current_time + 86400))
        {
            return round(($time - $current_time) / 3600) . "h";
        }

        //If less than a week
        elseif($time <= ($current_time + 604800))
        {
            return round(($time - $current_time) / 86400) . "d";
        }

        //If less than a month
        elseif($current_time > 604800)
        {
            return round(($time - $current_time) / 604800) . "w";
        }

        else
        {
            return date('j F h:ia', $time);
        }
    }   
James_43 15 Junior Poster

Hi All,

Relatively new to JS, but something strange is happening.

I have one function:

var commentContent = $('textarea.comment-box#comment');

commentContent.keydown(function(e){
    if((e.keyCode || e.which) == 13 && !e.shiftKey && commentContent.is(":focus"))
    {
        e.preventDefault();
        commentForm.submit();
    }
});

Which works absolutely fine. If the object is focused and I press Enter, the submit function is called.

Going down the line, a completely unrelated function:

var loadComments = $('.btn#load');

loadComments.click(function(e){

    e.preventDefault();

        $.ajax({
            type: 'POST',
            url: '/comments/load',
            data: {'listing_id': listingID, 'comment': comment},
            dataType: 'JSON'
        });
    });

When I press this button, Chrome sends me this error: Uncaught TypeError: Cannot read property 'keyCode' of undefined and references the line if((e.keyCode || e.which) == 13 && !e.shiftKey && commentContent.is(":focus"))

I can't think why/how my second function would be firing the keydown event? Any ideas?

James_43 15 Junior Poster

So according to the test I just ran (and I'm completely unfamilair with memoery testing so for all I know my method was just pointless). But it seems there is definitely an improvement in using the latter method.

Calling the variable multiple times = 349616

Calling the variable once = 348600

James_43 15 Junior Poster

Hi all,

In PHP just wondering if anyone knows whether one method of creating multiple indexes within an array is more efficient / preferable to another?

`

$listing['one'] = $x;
$listing['two'] = $y;
$listing['three'] = $z;

`

or:

    $listing = [
                    ['one'] => $x,
                    ['two'] => $y,
                    ['three'] => $z
                ];

Most of the time I unthinkingly do the former, but it occured to me that it's quite possible the latter is more efficient.

Any thoughts?

James_43 15 Junior Poster

The Exchange server is hosted through a subscription with Office 365, so I can administrate the server, but am not exactly in control of it.

...Could I use IMAP, this seems like a pretty neat solution? http://php.net/manual/en/book.imap.php

James_43 15 Junior Poster

Hi all, wondering if the following is possible.

A MS Exchange server is connected to an Outlook client. Would it be possible to capture sent/recieved emails and add them to a database using PHP.

I would like to investigate whether I could use this functionality to create a small email ticketing system, however, i would also like to retain use of the mailbox.

James_43 15 Junior Poster

An update, but a disturbing one, I have temporaily fixed the issue by setting the Session data based upon the $_GET['state'] parameter in my callback.php ... But surely it is not supposed to work like this?

$helper = $fb->getRedirectLoginHelper();

$_SESSION['FBRLH_state'] = $_GET['state'];
James_43 15 Junior Poster

Hi all,

Problems trying to login with Facebook on a website. The issue is that it works for me, but when I add other tests in the App settings, it doesn't work for them, they are getting the error: Facebook SDK returned an error: Cross-site request forgery validation failed. The "state" param from the URL and session do not match.

But this is not TRUE! My session data is:

Array
(
    [FBRLH_state] => 31ac6aa90aa1a7e4eaf18f5103a29bad
)

And the URL: https://www.facebook.com/v2.5/dialog/oauth?client_id=134812913531966&state=31ac6aa90aa1a7e4eaf18f5103a29bad&response_type=code&sdk=php-sdk-5.1.2&redirect_uri=http%3A%2F%2Fvicdeals.co.nz%2Ffb-callback.php&scope=email%2Cpublic_profile%2Cuser_location%2Cuser_education_history3

Note that the STATE is the same for both. So the error message is surely false.

I am setting my sessions at the top of all scripts:

if(!session_id()) {
    session_start();
}

And like I said, this works absolutely fine for me, but not for any other user.... Any idea?!

James_43 15 Junior Poster

Well, I've fixed the issue, insomuch as it's no longer replicatable.

I altered my NGINX config after some research and got rid of using an IF statement to check for existing files, instead opting for: try_files $uri $uri/ /index.php?page=$uri;

This means that if the file doesn't exist as a file or as a directory, it tries as a GET request which I can then handle through my PHP script. It's no longer downloading RAW php.

Despite this, it seems like there is a lot more to learn with NGINX and what I've currently got would not be secure enought to go live.

James_43 15 Junior Poster

Ah, I dislike how we can't delete posts on here. I was looking at the wrong object, the one actually at fault was indeed a bool value.

James_43 15 Junior Poster

Hi all, I'm running into a problem with PHP and mysql. I run a mySQL query, which returns the following object:

mysqli_result Object ( [current_field] => 0 [field_count] => 2 [lengths] => Array ( [0] => 1 [1] => 186 ) [num_rows] => 1 [type] => 0 )

I then try to fetch the data with $object->fetch_array(MYSQLI_ASSOC) but get this error: Call to a member function fetch_array() on boolean

I am very confused because I am calling the function on an object, not a bool... any ideas?

James_43 15 Junior Poster

There is definitely an extension on all the PHP files.

I've looked at the rewrite rule, and I am still somewhat a beginner wit NGINX, but my understanding of that rule is:

IF (file does not exist)
{
    rewrite URL to index.php/?page=$file
}

Using this, I tried to call files I know exist in my URL, for example my style.css file stored on the server.... and it replicated the issue! Calling http://link.org/style.css returned the raw PHP content!

So that concludes that the issue is nothing to do with JavaScript, but how the web server handles requests... However, I have no idea how to diagnose the issue further. I am quite suprised that the web server isn't processing the PHP like it should.

James_43 15 Junior Poster

More on this. Using the follow javascript:

$('a[href="sentiment"]').click(function(e){

    var id = $(this).attr('id');
    var sentiment = $(this).attr('class');

    e.preventDefault();
    alert(id + ' ' + sentiment);    
}); 

And the following HTML:

                        <a href="sentiment " id="{status_id}" class="hope">
                        <div class="box">
                        Hope
                        </div>
                        </a>

You'll note a space in the HREF attribute. In combination with the JS, clicking this link returns the RAW PHP of my index.php file.

When the space is correct the JS behaves as expected.

This must be a serious vulnerability. If someone spoofed the HTML to add a tiny space in the link, they could get their hands on server side code... Seriously, what is going on here?

James_43 15 Junior Poster

Thanks - I'll take a look. I realise that it could be dangerous, but interesting to try as an experiment.

James_43 15 Junior Poster

Hi all, my apologies, I pasted the Likes table wrong. It is in fact:

+----+----------+--------+------+---------------------+
| ID | type     | status | iker | iked                |
+----+----------+--------+------+---------------------+
|  1 | likes    |      6 |    1 | 2010-06-23 00:15:32 |
|  2 | dislikes |      6 |    2 | 2010-06-23 00:15:32 |
|  3 | likes    |      6 |    3 | 2010-06-23 00:15:38 |
|  4 | likes    |      3 |    1 | 2010-06-23 00:15:22 |
|  5 | dislikes |      3 |    1 | 2010-06-23 00:15:22 |
|  6 | dislikes |      3 |    2 | 2010-06-23 00:15:22 |
|  7 | supports |      3 |    2 | 2010-06-23 00:15:22 |
+----+----------+--------+------+---------------------+

`

However, your suggested query SELECT DISTINCT C.ID, L.ID FROM comments C, likes L WHERE C.approved = 1 AND C.profile_post = L.status ORDER BY C.ID, L.ID;

Yields a very similar result:

+----+----+
| ID | ID |
+----+----+
|  1 |  4 |
|  1 |  5 |
|  1 |  6 |
|  1 |  7 |
|  4 |  4 |
|  4 |  5 |
|  4 |  6 |
|  4 |  7 |
+----+----+
James_43 15 Junior Poster

Hi all,

I currently have two tables that look like this:

COMMENTS
+----+-------------------------+--------------+---------+---------------------+----------+
| ID | comment                 | profile_post | creator | created             | approved |
+----+-------------------------+--------------+---------+---------------------+----------+
|  1 | This is a test comment  |            3 |       1 | 2016-02-26 12:26:36 |        1 |
|  2 | 0                       |            0 |       0 | 0000-00-00 00:00:00 |        1 |
|  3 | TEST TES TEST TEST ETST |            3 |       0 | 2016-02-26 12:34:34 |        1 |
|  4 | TEST TES TEST TEST ETST |            3 |       1 | 2016-02-26 12:34:34 |        1 |
+----+-------------------------+--------------+---------+---------------------+----------+


LIKES

+----+-------------------------+--------------+---------+---------------------+----------+
| ID | comment                 | profile_post | creator | created             | approved |
+----+-------------------------+--------------+---------+---------------------+----------+
|  1 | This is a test comment  |            3 |       1 | 2016-02-26 12:26:36 |        1 |
|  2 | 0                       |            0 |       0 | 0000-00-00 00:00:00 |        1 |
|  3 | TEST TES TEST TEST ETST |            3 |       0 | 2016-02-26 12:34:34 |        1 |
|  4 | TEST TES TEST TEST ETST |            3 |       1 | 2016-02-26 12:34:34 |        1 |
+----+-------------------------+--------------+---------+---------------------+----------+

I use two queries to get the number of likes and comments in relation to any profile post:
SELECTIDFROM comments WHERE profile_post = {value} and SElECTIDFROM likes WHERE profile = {value}

I have been trying to combine these into one query. However, I get repeated values using:
SELECT c.ID, l.ID FROM comments c, likes l WHERE c.profile_post = 3 and c.approved = 1 and l.status = 3;
This outputs:

+----+---------+
| ID | ID      |
+----+---------+
|  3 |       4 |
|  1 |       4 |
|  4 |       4 |
|  3 |       5 |
|  1 |       5 |
|  4 |       5 |
|  3 |       6 |
|  1 |       6 |
|  4 |       6 |
|  3 |       7 |
|  1 |       7 |
|  4 |       7 |
+----+---------+ 

`
As you may have noticed, this outputs the CORRECT values, but repeats them 4 times... Any idea why?

James_43 15 Junior Poster

We need more information than this. Are you trying to make this process asynchronous during user interaction with JavaScript, or are you POSTing the data to a PHP script or something similar?

James_43 15 Junior Poster

It looks like the PHP code may not be executing. Does your file have the .PHP extension, not .HTML or anything else?

Either that or there's an issue with your variables. if($user != $my_id), none of these are defined in your script, for example, so all your mySQL queries would be failing. However, that should give a fatal error, so if you are seeing something it's unlikely to be this. Check your error logs to be sure.

James_43 15 Junior Poster

I'm more looking at how I can adapt the IRC network for legitimate purposes, so there would be no need to run on a destructible virtual machine.

I've looked at setting up IRC servers and clients, however, what I cannot find out is how to make the client take the IRC messages and execute them as a terminal command.

James_43 15 Junior Poster

Hi all,

I was recently reading an interesting article about setting up an SSH honeypot to track malicious activity (article avaliable here http://www.symantec.com/connect/articles/analyzing-malicious-ssh-login-attempts)

The article mentions that after an attacker gained SSH access to a server, they installed an IRC bot. Now, my knowledge of IRC is very limited, but I imagine that this allows the compromised server to listen for future commands.

After thinking about this for a while I realised how clever this is, since it would remain active even if the SSH credentials were altered or the port closed completely. However, the main benifit would be that the attacker could issue a single command to multiple compromised servers simultaneously, and that could be incredibly useful in a non-malicous enviroment.

For example, I have a moderate sized Internet of Things network at home. Being able to communicate with each one at the same time would be amazing compared to open up individual SSH connections. But I am still confused about how this works.

Am I right in thinking that:

  1. There is a central IRC server
  2. Each client can connect to the server and listen for commands
  3. The client grabs the command and executes it as a linux command.

I.e., if I 'said' in my message, "free -m", each client would read the message and copy it to the command console, execute the command, and then maybe send the result back as another message.

If this is the case, does anyone know of any tutorials for …

James_43 15 Junior Poster

Hi all, thanks for the good responses. I actually realised that even though I had created a swap drive, there was a spelling mistake in /etc/fstab so it wasn't mounting on restart. Now that the swap file is back online, it seems to have no further issues.

I will look at increasing the buffer size, since 128 does seem too small.

Cheers!

James_43 15 Junior Poster

Hi all, I am running a mySQL database on a webserver hosting multiple Wordpress installations.

It seems that database is getting swamped with memory and going into a continual loop of shutting down and restarting. A reboot fixes the issue temporarily, but I have no idea what I can do to fix this.

When the issue presented itself a month ago I realise I had not created a swap drive. I have now done so, but web traffick has increased since then and I suspect this may be the cause.

Interestingly, when I SSH into my Ubuntu Server, I get a readout of my memory usage. It always says 0% SWAP usage, which I cannot explain.

The full log is below, please help!

160317 14:16:09 mysqld_safe mysqld restarted
2016-03-17 14:16:09 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see $
2016-03-17 14:16:09 0 [Note] /usr/sbin/mysqld (mysqld 5.6.28-0ubuntu0.15.10.1) starting as process 11889 ...
2016-03-17 14:16:09 11889 [Warning] Buffered warning: Changed limits: max_open_files: 1024 (requested 5000)

2016-03-17 14:16:09 11889 [Warning] Buffered warning: Changed limits: table_open_cache: 431 (requested 2000)

2016-03-17 14:16:09 11889 [Warning] Using unique option prefix myisam-recover instead of myisam-recover-options is deprecated and will be removed in $
2016-03-17 14:16:09 11889 [Note] Plugin 'FEDERATED' is disabled.
2016-03-17 14:16:09 11889 [ERROR] Function 'innodb' already exists
2016-03-17 14:16:09 11889 [Warning] Couldn't load plugin named 'innodb' with soname 'ha_innodb.so'.
2016-03-17 14:16:09 11889 [ERROR] Function 'federated' already exists
2016-03-17 14:16:09 11889 [Warning] Couldn't load plugin named 'federated' with soname …
James_43 15 Junior Poster

Interesting question. Most of the answers tend to bring morals into it. In my part of the world (New Zealand) prostitution is legal, regulated, and there is a growing acceptance that it is contributing positively to society (providing employment, tearing down gender/sexual divisions, increasing awareness of safe sex, etc.).

So from a moral perspective, I would not have a problem accepting such a contract here in New Zealand. However, even with this moral aspect resolved, there are still ethical considerations in regards to constructing the website. These would include making sure that content is not easily accessible by underage people, and that relevant ethical advertising standards are not breached. For example, from the NZ advertising standards:

Advertisements should not employ sexual appeal in a manner which is exploitative and degrading of any individual or group of people in society to promote the sale of products or services.

So as far as I can see, if you are satisfied on a moral basis that what you are doing is not explotative or perpetuating an exploitative industry, AND you feel you are able to meet certain ethical obligations (which in this case also means that the prostitution agency is also willing to meet those obligations), then I see no reason why this shouldn't be a great oppurtunity for you to add a website to your portfolio.

In terms of explaining this to family/friends, well, I can only say that if you are satified at both a moral and an ethical …

James_43 15 Junior Poster

It's peculiar. I eventually figured out that my AJAX call was flawed due to PHP logic (problems with the POST data processing). For some reason, when my PHP logic was incorrect, AJAX was returning the raw PHP code.

I can't duplicate the issue any more since fixing my PHP, but I remain quite concerned over this. It makes me think that my code is somehow really insecure.

On second thought, I will experiment with making a bogus AJAX request that deliverabley contains POST data that my PHP code won't know how to handle. I'll report what that comes back with.

James_43 15 Junior Poster

You created a dupicate post. I posted a reponse on the first one asking for more evidence of your requirements. In case you missed it:

What solutions have you looked at so far? What's your knowledge / experience with PHP? Have you thought about where your client data will be stored, and do you know how to access that through PHP?

We would love to help you, but without a little more information and some evidence that you've already attempted something, it's very difficult for anyone to give you ideas or working code.

James_43 15 Junior Poster

What solutions have you looked at so far? What's your knowledge / experience with PHP? Have you thought about where your client data will be stored, and do you know how to access that through PHP?

We would love to help you, but without a little more information and some evidence that you've already attempted something, it's very difficult for anyone to give you ideas or working code.

James_43 15 Junior Poster

Some good points. Perhaps I'm more unfamiliar with Tor protocols than I thought, but I don't understand some of things you mentioned.

2 & 3. Yes, but isn't this all an obvious given since the database server is hosted on a hidden service? The server will need a Tor node to accept incoming connections, and the client will need a node to contact the server. Likewise, setting up a hidden server will create the private & public keys, so I'm unsure why you mentioned it?

Four. My understanding was that the Tor network handled this automatically through Introduction points. https://www.torproject.org/docs/hidden-services.html.en

Six. How will the database or application server be any more vulnerable to injection attacks on Tor vs. clearnet? Also, I'm not sure someone could track a connection back to the server, because of the relays forming the connection. As we know, tracing the location of hidden services require a consistant and dedicated attack. At most, the application server would just reveal the .onion address and the location of the first relay in the network. In order to attempt to find the destination, and attacker would need to own at least one relay in the network at any given time. Unless you are meaning that a SQL injection attack could somehow compromise the SQL server into releasing its real IP? I'm unfamiliar with injections generally, so unsure if this is possible / how it would work.

Latency is obviously the biggest downside here. And I think if someone …

James_43 15 Junior Poster

A theoretical question about connecting to hidden services through PHP.

Say I am writing an application on the clearnet that relies on data stored within a mySQL database that is hosted on a hidden Tor service. How would I initiate this connection?

Some brief research has pointed me towards the documentation on opening sockets http://php.net/manual/en/book.sockets.php, however, I haven't come across this area before so am quite unsure where to get started.

Anyone have any ideas?

James_43 15 Junior Poster

TexWiller is correct, this code seems to be accurate since you only want one value from the radio button, or you would be using a checkbox. You can only select one radio button within a form, so the value is unset when you POST the data.

If you give them different names, you can identify which was seleteted.

if(isset($_POST['upgrade1']))
{
    $upgrade = $_POST['upgrade1'];
}
elseif(isset($_POST['upgrade2']))
{
    $upgrade = $_POST['upgrade2'];
}

if(isset($_POST['upgrade3']))
{
    $upgrade = $_POST['upgrade3'];
}

Also, a general note, it's good practice to also validate your form data server side in addition to client side with JavaScript. It can be very easy to POST data direct to the server, which will then bypass any sort of validation.

James_43 15 Junior Poster

The consensus here is on point. Your orginal code only checks once to see if the date is within the parameters or not, so in order for this to work you need to execute the script every minute (via a cron job).

Theoretically, you could use a sleep(60) command and ask the script to check again in a loop, but it's terribly inefficient since you know the sript only needs to be executed once every day. Still, if you are bent at doing it within a single execution, it's the only way I know.

$break = FALSE;

while($break == FALSE)
    {
        if($now != $base)
        {
            sleep(60);
        }
        elseif($now == $base)
        {
            mail($to, $subject, $message, $headers);
            sleep(60); //In order to make the next execution == FALSE
        }
    }
James_43 15 Junior Poster

My experience is that many providers don't support it right now, but it's very easy to set up yourself in a VPS enviroment.

I imagine once 7.0 is accepted into the official linux packages it will start to become more widely avaliable, but I'm unsure if there's a date target for this.

James_43 15 Junior Poster

Thanks for your responses, that's really helpful. But how come the variable I used in my example is a string, not an array or an object?

James_43 15 Junior Poster

Correct, I am getting the PHP file as depicted above.

There is a rewrite rule in place with NGINX, could this be causing it? The strange thing for me is that I can navigate to the page manually and get HTML, but when making the call through AJAX I get the PHP code returned.

If it's relevant, below if my NGINX config:

server {
        listen 80 default_server;
        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.php;

        server_name server.org;

        error_page 404 /index.php;

        location /
        {
                if (!-e $request_filename)
                {
                rewrite ^(.*)$ /index.php?page=$1 break;
                }
        }
        location ~ \.php$ {

                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;

                fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        }

        location ~ /\.ht {
                deny all;
        }
}
James_43 15 Junior Poster

Look up PHPMailer, in my experience it really is the best option. You can of course use the php mail() function, however, it does depend on a local mail server, wheras PHPMailer can connect through SMTP. https://github.com/PHPMailer/PHPMailer

Once configured correctly, you can easily make calls to PHPMailer to construct a message. Simply place that code once your database function returns true.

James_43 15 Junior Poster

ryantroop is correct (as far as my limited knowledge goes) when he mentions that SSL is the way to go. Regardless of whether you use POST or GET, data is transmitted in plain text unless encrypted with an SSL.

The code you have above is very pointless, because the client web browser has already passed this information across to the PHP server in plaintext. All you are doing here is encrypting the data and checking it against a hash.

This is what you would do if you were storing passwords, however, because you are likely to need the unencrypted value of articleID it is a exercise that doesn't offer any extra security.

As far as the PHP code you pasted goes, I imagine it is failing because your link_check function has flaws in it. In order to validate a hash against a given variable, you need to hash and salt it in the same way. However, you are hashing the link with the hash already generated: $hash = crypt($link, $existing_hash); whereas you need to hash it against an existing salt: $hash = crypt($link, $existing_salt); before comparing it against the original hashed value.

I should also point out that that value returned by generate_salt() isn't actually used in the link_encrypt() function.

James_43 15 Junior Poster

The Wordpress templating engine allows full use of PHP, so you have the power (and responsability) of adding code like this.

There are effectively two ways to add this code to a page. You either edit or create a general template such as index.php or page.php. May themes use these to render the page content from the database.

Alternatively, you can define a template to use with only certain pages, which must be manually selected.

Either way, it sounds like your understanding of how Wordpress renders pages is a bit lacking. I really recommend you look at some of the developer material out there (there is a lot). Here's a good templating start point: https://developer.wordpress.org/themes/template-files-section/

Best of luck!

James_43 15 Junior Poster

Hi all,

In all my time with PHP I have only ever seen one way of adding a variable onto the end of the string:

$string = "hello" . $variable;

However, recently I came across another method, which was used in the context of constructing a mySQL query. Can someone explain the difference? It seems like a much easier way to achieve the same result:

$sql = "SELECT * FROM {$table}";
James_43 15 Junior Poster

Hi all,

Something disturbing is happening... I make an AJAX call to a page and it returns unprocessed PHP, not HTML. However, when I navigate to the page manually, the PHP is processing as expected. This must be a huge security vulnerability?

My AJAX call is:

$('#forgot').click(function(e){
    e.preventDefault();
    lFormContainer.load("ajax/?page=authenticate/username");
});

The PHP code itself is too huge to paste here, so it's difficult to see what is relevant. However, the AJAX call returns only the content for index.php, and none of the code referenced in the classes index.php makes calls to.

I have pasted index.php below, it may reveal something:

<?php

session_start();

unset($_SESSION);

define("FRAMEWORK_PATH", dirname(__FILE__) . "/");

require __DIR__ . '/vendor/autoload.php';

require('registry/registry.php');
$registry = new Registry();

//Setup our core registry objects
$registry->createAndStoreObject('template', 'template');
$registry->createAndStoreObject('mysql', 'db');
$registry->createAndStoreObject('authenticate', 'authenticate');
$registry->createAndStoreObject('urlprocessor', 'url');
$registry->createAndStoreObject('mailout', 'mail');

//Database settings
include (FRAMEWORK_PATH . 'config.php');

//Create database connection
$registry->getObject('db')->newConnection($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config['mysql_name']);

//Process URL
$registry->getObject('url')->getURLData();

//Process Authentication
$registry->getObject('authenticate')->checkForAuthentication();

//Store settings in our registry
$settingsSQL = "SELECT * FROM settings";
$registry->getObject('db')->executeQuery($settingsSQL);
while($setting = $registry->getObject('db')->getRows())
{
    $registry->storeSetting($setting['value'], $setting['key']);
}

$registry->getObject('template')->getPage()->addTag( 'siteurl', $registry->getSetting('siteurl') );
$registry->getObject('template')->buildFromTemplates('header.php', 'main.php', 'footer.php');

//Is the user authenticated?
if($registry->getObject('authenticate')->isLoggedIn())
{

}

else
{
    // Grab Templates for no-login
    $registry->getObject('template')->buildFromTemplates('header-no_log.php', 'main-no_log.php', 'footer.php');

    //Set default greeting
    $registry->getObject('template')->getPage()->addTag( 'greeting', '<h1 class="text-center" id="greeting">hello</h1>' );
}

$controllers = array();
$controllersSQL = "SELECT * FROM controllers WHERE active=1";
$registry->getObject('db')->executeQuery( $controllersSQL );
while( $controller = $registry->getObject('db')->getRows() )
{
    $controllers[] = $controller['controller'];
}


//Which controller should we delegate to? 
//?page=$controller
$controller = $registry->getObject('url')->getURLBit(0);


if( in_array( $controller, $controllers ) )
{
    require_once( FRAMEWORK_PATH . 'controllers/' . …
James_43 15 Junior Poster

Hi all,

I just have a question about how PHP works.

Say I have several classes that I call but don't unset() once I've finished with them, how long will the server hang onto that data. Is it completely dependant on the client connection to the server?

Similarly, I understand a little about PHP pools - does this create a new 'instance' of php to serve every client connection?