...

Hi! I’m Starx

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

unordered HTML list with unordered list inside. Wrapped next each other

Question by JohannesM

I get an unordered list by a cms that I want to style.
It works well, but only for the first <li id="link-18"> element. My goal is it to style the <ul> blocks all the way trough, like the first one. See http://jsfiddle.net/UyrdS/3/ (the second and third link shows the toggled <ul> block not on top)

goal

If the second link (level 2 two) is clicked, the toggled new <ul> block shows beside the navigation, but not on top like the level 1 one links does it with his children element <ul>

Answer by JohannesM

I gave up. I’m a pretty worse inquirer 🙂
Thanks for the answers. Kudos to you all for spending your time. This fiddle is the closest to my question.

http://jsfiddle.net/UyrdS/6/

But it’s not dynamic. It has a static width. That is still the problem.

Answer by Starx

I think this is what you wanted

alllinks = $("ul>li>ul");
$('nav a').on('click', function(e) {
    alllinks.hide(); //First hide all the links
    e.preventDefault();
    if ($(this).parent().children('ul').size() > 0) {
        $(this).parent().children('ul').toggle();
    }
});
Read more

Using .htaccess and mod_rewrite

Question by InVert

I’m having some mod_rewrite problems with my .htaccess..

RewriteBase /folder

RewriteEngine on
Rewrit­eRule ^(.*)$ basic.p­hp?­url=$1 [L]

Above is what I’m current using .. However I have no idea what I’m doing to be honest as I’m just cycling through the internet trying to figure this out.

Basically, for my website, if you type in

“www.domain.com/folder/xxx/”

I want it to basically be “www.domain.com/folder/basic.php?url=xxx”
For some reason, all that does is cause a 404 error :/

So can someone please politely point me in the right direction?

Answer by Starx

Ok, I will explain using your htaccess.

RewriteEngine on

Turn on the Rewrite Module to enable URL rewriting

RewriteBase /folder

Rewrite the Base Directory to directory name folder

RewriteRule ^folder/(.*)$ basic.php?url=$1 [L]

Remap every request make using the folder/***** to basic.php?url=********

Note: RewriteEngine On Should be the first statement on your case

Read more

PHP require_once error

Question by Garrett

I am using CODA, MAMP and am working out of my HTdocs folder all locally. I am learning PHP and MVC structure and an coming across the following error when using require_once. I have read many of the other posts on this topic and no solution has worked.

The error I am receiving is:

Warning: require_once(UserModel.php): failed to open stream:
No such file or directory in - on line 13 Fatal error: require_once():
Failed opening required 'UserModel.php' (include_path='.:') in - on line 13

My file structure is:

database
----bdfdatabase.sql
index.php
UserModel.php

My code is as follows

<?php   
    require_once('UserModel.php');

    $dsn = "mysql:host=127.0.0.1;port=8889;dbname=bdfdatabase";
    $db_user= "root";
    $db_pass= "root";
    $model = new UserModel($dsn, $db_user, $db_pass);
    $rows = $model->displayUsers();

        foreach($rows as $row){
            echo "<h3><a href='details.php'>";
            echo "${row['user_name']}";
            echo "</a></h3>";
        }

?>

Any suggestions would be much appreciated.

Answer by Starx

Most probably, The problem is once again the Path.

  1. Make sure UserModel.php lies in the same folder as the one from which you are running the above code.

  2. Make sure you have access to read that file. The file must be readable by owners, group, and others, to be included as such. Change the mode of the file to 0774 to confirm this.

Read more

Email Sending from Local Server in PHP

Question by Samir

I have my file mail.php :

<html>
<body>

<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
  {
  //send email
  $email = $_REQUEST['email'] ;
  $subject = $_REQUEST['subject'] ;
  $message = $_REQUEST['message'] ;
  mail("syedsamiruddin29@gmail.com", $subject,
  $message, "From:" . $email);
  echo "Thank you for using our mail form";
  }
else
//if "email" is not filled out, display the form
  {
  echo "<form method='post' action='mail.php'>
  Email: <input name='email' type='text' /><br />
  Subject: <input name='subject' type='text' /><br />
  Message:<br />
  <textarea name='message' rows='15' cols='40'>
  </textarea><br />
  <input type='submit' />
  </form>";
  }
?>

</body>
</html>

but when i run it. i get this error :

Warning: mail() [function.mail]: Failed to connect to mailserver at "127.0.0.1" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:Program FilesEasyPHP-5.3.8.1wwwsafepay247mail.php on line 13
Thank you for using our mail form

what im trying to do is to send an email to my email id : syedsamiruddin29@gmail.com using php to the person’s email written in the input type.

Ive gone through many videos but none help me solve the php.ini problem.

Answer by Starx

Its not that complicated

  1. Open the php.ini.

  2. Search for the attribute called SMTP in the php.ini file. Generally you can find the line SMTP=localhost. change the localhost to the smtp server name of your ISP. And the set the port of 25.

    SMTP = smtp.gmail.com #user your smtp address here
    smtp_port = 25
    
  3. Restart the apache server or wamp or xammp. Whatever you are using.

  4. Now try to send the mail using the mail() function

Read more

Jquery: Append/Remove items on hidden field on click

Question by user1056998

I have a program that allows you to record absence when a grid is clicked 1 time. When you click it the second time, it will record the grid as late. When you click it for the third time, the status will revert to the original. I am able to append absences to a hidden field to be posted on another php. However, I can’t seem to append the late records to another hidden field. When I look at my other php file, the absence is still recorded even if it should have been removed from the list. Worst part is, nothing is being appended to the late hidden field.

I badly need help with this. Also, I hope you could explain where I made a fault so I could understand the code. Thanks!

Here’s the code: http://jsfiddle.net/Ms6FP/2/

Answer by Magneon

A better way to do this would be to create the contents of the hidden fields on submit.

Assuming your submit button is given the id mySubmitButton and you have a hidden field with an id lateHiddenField, you can do something like:

$("#mySubmitButton").submit(function(){
  $(".late").each(function(index,value){  //iterate through each late student
    //append the late student's name
    $("#lateHiddenField").text($("#lateHiddenField").text()+value.text()+"n");
  })

  //do the same for the absent students
}

The advantages are:

  • Faster processing- this only runs once
  • Simpler code- you don’t have
    to revise anything

Answer by Starx

I am guessing you are trying to give out the total number of students who are late through different state of clicks.

On that case here is an working solution

Slight change to markup, to make it more manipulative

<div id="collect1">
    late: <span>0</span>
</div>

Then, count the length of your already maintained array and update

$("#collect1").children("span").html(late.length);
Read more
March 11, 2012

Problems with reading and searching thru txt file with PHP

Question by andreicek

I am writing a small script which checks if a users has his username in file called whitelist.txt or not. If the username is not found its added. This is the script:

$fh = @fopen("whitelist.txt", 'a+');
$stringData = $_POST[usr]. "n";
if ($fh)
    {
        while (!feof($fh))
        {
            $buffer = fgets($fh);
            if (strpos($buffer, $stringData) == TRUE)
                echo "This username is already whitelisted.";
            elseif (strpos($buffer, $stringData) == FALSE) {
                    fwrite($fh, $stringData);
                    echo "Username ". $stringData. " is now whitelisted.";
                    }
        }
        fclose($fh);
    }

What I get now if I enter a new username first time, all is ok. The second time I enter a new username it gets dubbled. Problems go on: if I enter an existing username it gets added twice and the message “This username is already whitelisted.” is not shown. Every username is in a new row.

Thank you for your time and help!

Answer by marramgrass

EDIT TO ADD: The accepted answer is great. As a counterpoint, I’ve modified your code below in the event that you want to continue to read line by line instead of all it once – the file is unlikely to get so big that doing it in one chunk is ever a problem, but making that kind of assumption always makes me very slightly nervous.


I see a couple of issues, here:

Even when you find the username in the file, you carry on through the rest of the file, getting false negatives. Try:

if (strpos($buffer, $stringData) == TRUE) {
    echo "This username is already whitelisted.";
    break;
}

Your else if will trigger whenever the script finds a line that doesn’t match the submitted username, rather than when it gets to the end of the file. You’ll need to move that check outside of the loop so that the new username is only added once. Altogether, now:

$fh = @fopen("whitelist.txt", 'a+');
$stringData = $_POST[usr]. "n";
if ($fh)
    {
        $found = false;
        while (!feof($fh))
        {
            $buffer = fgets($fh);
            if (strpos($buffer, $stringData) == TRUE) {
                echo "This username is already whitelisted.";
                $found = true;
                break;
        }
        if (!$found) {
            fwrite($fh, $stringData);
            echo "Username ". $stringData. " is now whitelisted.";
        }
        fclose($fh);
    }

Answer by Starx

I don’t like you are already opening the file for writing without finding out whether a match occurs or not

$username = "thegreatone";
$lines = file("yourfile.txt");
foreach($line as $no => $line) {
    if(strstr($line,$username)) {
       //Now start the hand
       $fp = fopen('whitelist.txt', 'a+');
       fwrite($fp, 'rn'.$username);
       fclose($fp);

       //Since the search was true... no need to continue the loop
       break;    
    } 
}
Read more

PHP mail() error 500

Question by Chevi

As part of the registration process on a website, I have added mail confirmation. But for some reason, the mail function throws an Internal server error in there.

The strange thing is that if I create a test script, with the exact same email (all the same parameters) it works fine, and sends the email.

The mail is sent from a function in a Class, in case that helps. I didn’t post the code because it isn’t really relevant, even if I try mail('email@email.com','subject','email'); it fails with the 500 error!

The server error logs don’t show anything at all, anyone knows what may cause such a problem?

Technology:

The server is running php through mod_fastcgi, although this problem also happens if I switch to mod_suphp.

Updates:

UPDATE:
I’ll try to explain this better, the mail function works perfectly if called from another file, with the same parameters. The problem here is something that combined with the mail function causes an error 500. The rest of the file where it’s called is fine too, if I comment the mail function everything works. The way it gets called is an AJAX request to a file that calls a function where the mail is sent (Just in case this helps)

UPDATE 2:
In response to answers so far, here is more information I did not share previously:
OS: CentOS release 5.8
When I say error 500, I mean that the server returns only an HTTP 500 status code.
The server does not show anything in any error log
The most important thing is that if I create a file called test.php, with only mail('address@domain.com','Subject','Message'), it works just fine. When called from this other file, 500 status code returned.
What I am asking is if anyone knows, probably from experience, what could be causing this.

UPDATE 3:
Someone had the same problem yesterday: PHP's mail() function causes a 500 Internal Server Error only after a certain point in the code

UPDATE 4:
After some testing, I have discovered that the 500 stats code is only returned when the script is called via AJAX. If I create a file called test.php, and I simply place the mail function and test it, it works. Calling it via AJAX doesn’t, any ideas?

Answer by Chevi

After some more hours of testing I have found the problem!
I was using window.location to redirect the user to a new page after the AJAX call was completed, in it’s callback function.
Apparently if you modify it after an AJAX call to a php script that uses the mail() function, the server returns a 500 status code in the request

Answer by Starx

With the amount of input you have provided, it is very hard to tell, how that error occured.

Error: 500 are Interval Server Errors and can have more than one reasons for occuring.

  • A malformed php cgi script
  • An invalid directive in an .htaccess or other config file
  • Limitation imposed by file system and server software.
    May be you are attachcing a file to be to be sent
  • Missing Line Breaks (rn) in the headers

Try every solution listed from this cPanel Forums

Read more

Better way of splitting and assigning many values in Javascript?

Question by Aaron

I have a for loop that cycles through the number of elements that the user has created. There are a lot of available settings in this plugin, and each element can receive it’s specific settings.

  1. User settings are entered in the following format: speed_x: “1000,500 > 1000,200 > 0,0”
    This controls the speed_x in/out for 3 separate elements. The > divides by object and the commas separate the in/out.

  2. So I can grab specific object speed_x values, I’ve split speed_x into speed_x_set (splitting by >) resulting in:

1 1000,500
2 1000,200
3 0,0`

3 Inside the loop, I grab the value by index (since it’s the object #) and split it by comma (to get speed_x_in and speed_x_out.)

for(var i=0; i<OS.numberofobjects; ++i){
   OS.speed_x_on_set[i]=speed_x_set[i].split(",")[0],
   OS.speed_x_off_set[i]=speed_x_set[i].split(",")[1],
   ...
};

Everything is assigned by object and by setting in/out correctly into the master OS settings object. T*he problem is I have many, many settings which need to be split in this fashion…* for example: delay_x_set, speed_y_set, opacity_set, etc. Their names are all based on the default setting name, with “_set” added as shown above. Hopefully this provides enough information. Thanks!

Answer by Starx

I would say to cache the split result

for(var objindex=0; objindex<OS.numberofobjects; ++objindex){
   var splits = speed_x_set[objindex].split(","); //Cache the split so its does not need to be done twice
   OS.speed_x_on_set[objindex] = splits[0];
   OS.speed_x_off_set[objindex] = splits[1];
   ...
};
Read more

MySQL: How can I get the timestamp of the last insertion to the database

Question by user690182

How can I check when was the last time (timestamp) that I wrote in the database, irrespectively of the database table that I inserted into?

Answer by Michael Durrant

I wasn’t able to use information_schema.tables update_time as the column wasn’t being updated but for create_time this worked. It would work for update_time (if changed) if update_time gets updated which might be true in your setup.

select table_schema,table_name,max_time from information_schema.tables t1 JOIN 
 (select MAX(t2.create_time) AS max_time FROM 
  information_schema.tables t2 where  
  table_schema ='test') as t3  
on t1.create_time = t3.max_time;

Answer by Starx

This is basically what logging is all about.

On the CLI

  1. execute SET GLOBAL log_output = 'TABLE';
  2. execute SET GLOBAL general_log = 'ON';

Now, a table general_log inside mysql database will log all such actions on database.
Use phpMyadmin or similar to view these. You can query from their results very effectively.

Read more

MySQL 1064 syntax error

Question by user1244808

I have this SQL query:

SELECT
  user_id,
  user_name,
  user_level
FROM
  users
WHERE
   user_name = '" . mysql_real_escape_string($_POST['user_name']) . "'
AND
   user_pass = '" . sha1($_POST['user_pass'])

MySQL gives the error:

1064 – You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ‘user_name’]) . "’ AND
user_pass = ‘" . sha1($_POST[‘user_pass’])’ at line 8

Answer by Starx

I am not sure, how are you running the query. But I really hope you are considering the possibility of SQL Injection in your code.

$query = "SELECT
            user_id, user_name, user_level
          FROM users
          WHERE
            user_name = '" . mysql_real_escape_string($_POST['user_name']) . "'
            AND
            user_pass = '" . sha1($_POST['user_pass'])."';";
$result = mysql_query($query);
Read more
...

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