edwinhermann 57 Junior Poster

Neither of these are the correct approach. strtotime turns the date into an integer. You then subtract one integer from the other which gives you a difference. You are then trying to turn that difference into a date (which will result in a date close to the epoch depending in the size of the difference).

You should be using DateTime::diff - see http://php.net/manual/en/datetime.diff.php There are worked examples there.

diafol commented: good +15
edwinhermann 57 Junior Poster

Then why not simplify like this:

function getdata()	{
return file_get_contents("titel.txt");
}
$content = getdata();
$newvalue = "Fred";
$new_text = str_replace("<name>",$newvalue,$content);
echo $new_text;

Or even better do away with the function, so like this:

$content = file_get_contents("titel.txt");
$newvalue = "Fred";
$new_text = str_replace("<name>",$newvalue,$content);
echo $new_text;
diafol commented: welcome back +14
edwinhermann 57 Junior Poster

This is a new question and you should really have started a new thread. But never mind, we're here now :)

Here's some code:

<?php
$text = "It happened when <name> turned his computer on.";
$newvalue = "Fred";
$new_text = str_replace("<name>",$newvalue,$text);
echo $new_text; // It happened when Fred turned his computer on.
?>
edwinhermann 57 Junior Poster
echo substr($search,0,4); //this would print out "Hello"

Not quite. That would print out "Hell" (4 characters)

decade commented: thank you +1
edwinhermann 57 Junior Poster

This page does the calculation. It uses DateInterval so requires PHP 5.3.0 or later.

<?php

$age = $_GET["age"];
$year = $_GET["year"];
$month = $_GET["month"];
$day = $_GET["day"];

if (!$_GET["age"]) {
  }
elseif (!checkdate($month,$day,$year)) {
  echo "Invalid Date";
  }
else {
  $one_year = new DateInterval("P1Y");
  $one_day = new DateInterval("P1D");
  $age_years = new DateInterval("P".$age."Y");
  $min_date = new DateTime(sprintf("%04d",$year)."-".sprintf("%02d",$month)."-".sprintf("%02d",$day),new DateTimeZone("Pacific/Auckland"));
  $min_date -> sub($age_years);
  $min_date -> sub($one_year);
  if ( ($min_date -> format("j") == $day) && ($min_date -> format("n") == $month) ) {
    $min_date -> add($one_day);
    }
  $max_date = new DateTime($year."-".$month."-".$day,new DateTimeZone("Pacific/Auckland"));
  $max_date -> sub($age_years);
  if ( ($max_date -> format("j") != $day) || ($max_date -> format("n") != $month) ) {
    $max_date -> sub($one_day);
    }
  echo '<p>If the person was <b>'.$age.'</b> on <b>'.sprintf("%04d",$year).'-'.sprintf("%02d",$month).'-'.sprintf("%02d",$day).'</b>, they must have been born between <b>'.$min_date->format("Y-m-d").'</b> and <b>'.$max_date->format("Y-m-d").'</b>.</p>';
  }
$months = array(1=>'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
echo '<hr>';
echo '<form action="'.$_SERVER["PHP_SELF"].'" method="get">';
echo '<p>Age: <input type="text" name="age" maxlength="3" style="width: 30px;"></p>';
echo '<p>Year: <input type="text" name="year" maxlength="4" style="width: 40px;"> Month: <select name="month"><option selected value="0"></option>';
for ($i=1;$i<=12;$i++) {
  echo '<option value="'.$i.'">'.$months[$i].'</option>';
  }
echo '</select> Day: <select name="day"><option selected value="0"></option>';
for ($i=1;$i<=31;$i++) {
  echo '<option value="'.$i.'">'.sprintf("%02d",$i).'</option>';
  }
echo '</select></p>';
echo '<p><input type="submit" value="Calculate"></p>';
echo '</form>';

?>

And if you don't have PHP 5.3.0, you can achieve the same thing with this code:

<?php

$age = $_GET["age"];
$year = $_GET["year"];
$month = $_GET["month"];
$day = $_GET["day"];

if (!$_GET["age"]) {
  }
elseif (!checkdate($month,$day,$year)) {
  echo "Invalid Date";
  }
else {
  $min_date_year = $year - $age - 1;
  $min_date = (checkdate($month,$day,$min_date_year)) ? mktime(0,0,0,$month,$day,$min_date_year)+86400 : mktime(0,0,0,3,1,$min_date_year);
  $max_date_year = $year - $age;
  $max_date = …
edwinhermann 57 Junior Poster

It's easier to troubleshoot if you arrange your code neatly, like this:

<?php
if (empty($mobile)) {
  echo '<script language="javascript">alert("Enter Phone Number")</script>;';
  }
elseif (!(empty($mobile))) {
  if ((is_numeric($mobile))) {
    if ((strlen($mobile)!=10))
      echo '<script language="javascript">alert("phone number should be of 10 digit")</script>;';
    }
  else {
    echo '<script language="javascript">alert("Please Enter valid phone number")</script>;';
    }
  }
elseif (!($_FILES["uploadedfile"]["type"]=="image/pjpeg" ||  $_FILES["uploadedfile"]["type"]=="image/jpeg" ||  $_FILES["uploadedfile"]["type"]=="image/jpg" ||  $_FILES["uploadedfile"]["type"]=="image/png")) { 
  echo "i am in upload";		    
  echo "<script language=\"javascript\">alert(\"Your uploaded file must be of JPG or GIF. Other file types are not allowed!!\")</script>;";  
  echo "<script type='text/javascript'>";
  echo "</script>";
  }
else {
  mysql_connect('localhost','root','');
  mysql_select_db('project');
  mysql_query("SET NAMES utf8");
  //$result=mysql_query("Select * from tbl_hindi");
  echo("INSERT INTO `project`.`tbl_hindi` (`pre`, `name`, `father`, `state`, `city`, `gender`, `mobile`, `dob`, `namdan_date`, `file` ,`relation`)VALUES ('$pre','$name','$father','$state','$city','$gender','$mobile','$dob','$namdan_date','$file','$relation')");
  }
?>

That makes it easier to work out what is going wrong. If you examine your logic closely you'll see that it will never get to the Upload section (or the mysql section). Why? Because you code is effectively saying (in pseudo-code):

if (is empty) {
  // do stuff
  }
elseif (is not empty) {
  // do other stuff
  }
elseif (some other condition) {
  // do upload stuff
  }
else {
  // do mysql stuff
  }

The variable is either empty or not empty, so that's why it never gets to upload stuff. It's like saying "If it's raining then put on your raincoat, if it's not raining then put your raincoat away, otherwise go shopping". You never get to go shopping because you only end up follow the first two branches because it's …

edwinhermann 57 Junior Poster

One way is to have a transparent DIV that takes up the whole screen with a high z-index value, but still lower than the sign-in DIV. On that DIV you'd have something like this:

<div onClick="cancelSignIn()">

And the corresponding Javascript:

function cancelSignIn() {
document.getElementById("signin").name=0;
document.getElementById("twitter").style.display='none';
}

A full-page DIV an be achieved by putting it after the <body> tag and applying the following CSS (assuming the DIV's id is "canceltwitter":

div#canceltwitter {
position: absolute;
margin: 0px;
padding: 0px;
border: 0px;
width: 100%;
height: 100%;
z-index: 50;
display: none;
}

You'd need to also set the z-index of the Twitter div to something greater than 50, and use javascript to set the "display" property of the canceltwitter div to block at the same time as displaying the twitter div. (Also putting the canceltwitter div's display property back to none as part of the cancelSignIn() function).

edwinhermann 57 Junior Poster

Just elaborating on twiss's post:

<script type="text/javascript">
function doSomething(elem) {
alert ('The ID of the element which triggered this is: ' + elem.id;
}
</script>
<div id="blah" onClick="doSomething(this)">Blah blah blah</div>
edwinhermann 57 Junior Poster

How about this for a one-liner:

echo preg_replace_callback('/<a ([^>]+)>([^<]*)<\/a>/m',create_function('$matches','return str_replace(" ","_",$matches[0]);'),$string);

BEFORE:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in ante nec nisl vulputate faucibus at quis <a href="path/to/page" class="pageLink">felis</a>. Aliquam vel dui orci. Integer eget eros sed lorem vestibulum aliquet. Aliquam tortor lorem, semper et rutrum a, hendrerit non tellus. Donec <a href="path/to/page" class="pageLink">sodales nunc</a> sed justo viverra luctus. Proin magna lectus, posuere sed laoreet dapibus, mattis at odio. Fusce sed ultricies augue. Curabitur id eros eu turpis imperdiet vestibulum. Nam <a href="path/to/page" class="pageLink">vitae ante dolor</a>, et placerat elit. Suspendisse nec dictum lectus. Morbi nisi nunc, porta nec tempor non, mollis sed justo. Sed pulvinar commodo consectetur.

AFTER:

<a_href="path/to/page"_class="pageLink">felis</a>. Aliquam vel dui orci. Integer eget eros sed lorem vestibulum aliquet. Aliquam tortor lorem, semper et rutrum a, hendrerit non tellus. Donec <a_href="path/to/page"_class="pageLink">sodales_nunc</a> sed justo viverra luctus. Proin magna lectus, posuere sed laoreet dapibus, mattis at odio. Fusce sed ultricies augue. Curabitur id eros eu turpis imperdiet vestibulum. Nam <a_href="path/to/page"_class="pageLink">vitae_ante_dolor</a>, et placerat elit. Suspendisse nec dictum lectus. Morbi nisi nunc, porta nec tempor non, mollis sed justo. Sed pulvinar commodo consectetur.

colweb commented: Perfect example of a reg expression in action. +3
Venom Rush commented: Brilliant! Thanks for the help ;) +3
edwinhermann 57 Junior Poster

The only way I can think is like this:

$sql = "SELECT * FROM something WHERE id LIKE \"%,".$test.",%\" OR id LIKE \"".$test.",%\" OR id LIKE \"%,".$test."\"";
edwinhermann 57 Junior Poster

Great, so that confirms the array structure of $players.

So in an earlier post I suggested the following:

Change the five SQL lines to this:

mysql_query("DELETE FROM buddies WHERE characterid = ".$players['id']);
mysql_query("DELETE FROM inventoryitems WHERE characterid = ".$players['id']);
mysql_query("DELETE FROM skills WHERE characterid = ".$players['id']);
mysql_query("DELETE FROM keymap WHERE characterid = ".$players['id']);
mysql_query("DELETE FROM characters WHERE characterid = ".$players['id']);

Did this work for you? If not, were error messages generated?

edwinhermann 57 Junior Poster

Hello all,
I have a set of IF ELSE validation code ECHOING onto a php web page through a SWITCH staement. Everything works fine all error messages show up correctly. The problem is, after going through 3 conditons it starts to allow entry into my DB(mysql) all other entries goes straight through and stops validating.

Can someone help please it would be much appreciated, this has never happened to me before. is it common?

Thanks

After each header("Location:") command you need exit, otherwise the script keeps running.

E.g.:

if (empty($_POST[model]))
{                  		
  header("Location: " . $config_basedir . "/newcar.php?error=model"); 		     
  exit;
}
if (empty($_POST[engine]))
{                  		
  header("Location: " . $config_basedir . "/newcar.php?error=engine"); 		     
  exit;
}
if (empty($_POST[colour]))
{                  		
  header("Location: " . $config_basedir . "/newcar.php?error=colour"); 		     
  exit;
}
else {
  header("Location: " . $config_basedir . "/newcar.php?error=date");
  exit;
// etc. ......
edwinhermann 57 Junior Poster

Sounds good - I use a similar system to send me a message when a particular radio station plays the same song twice in one day (first caller gets $1,000). The songs are posted on their web site.

Anyway, back to what you're doing: You could improve the cron side of things. Instead of using cron to call wget, which calls the PHP page (via a Web server), why not modify your PHP file like so:

#!/usr/bin/php
<?php

// your PHP code here

?>

Ensure the file has execute permissions (chmod 700 will work becase that gives you permissions to read, write and execute).

Then just have cron call that file instead of wget. (That file is effectively an executable script).

Note: You may need to change /usr/bin/php to match the path of wherever PHP happens to be installed on your server.

edwinhermann 57 Junior Poster

If it is XML output I would parse it using the xml parsing functions.

However, if it's not entirely XML (or not XML at all), then using preg_match_all should be fine. Here's some sample code to show you:

$b = <<<'ENDOFEXAMPLE'
<translate id="4" token_id="0" variant_id="1">contents............</translate>
blah blah blah
<translate id="9" token_id="8" variant_id="7">other contents...</translate>
ENDOFEXAMPLE;

preg_match_all("/<translate[^>]*\\ id=\\\"([^>]*)\\\"[^>]*\\ token_id=\\\"([^>])*\\\"[^>]*\\ variant_id=\\\"([^>])*\\\"[^>]*>([^<]*)<\\/translate>/imU",$b,$matches);

print_r($matches);

?>

that outputs:

/*
Array
(
    [0] => Array
        (
            [0] => <translate id="4" token_id="0" variant_id="1">contents............</translate>
            [1] => <translate id="9" token_id="8" variant_id="7">other contents...</translate>
        )

    [1] => Array
        (
            [0] => 4
            [1] => 9
        )

    [2] => Array
        (
            [0] => 0
            [1] => 8
        )

    [3] => Array
        (
            [0] => 1
            [1] => 7
        )

    [4] => Array
        (
            [0] => contents............
            [1] => other contents...
        )

)
*/

You can see that the output is an array. Starting at index 1, the contents of that array are:

index = 1: an array of ids
index = 2: an array of token_ids
index = 3: an array of variant_ids
index = 4: the contents of the <translate> tag

The way I've written it, the order of the attributes of the <translate> is fixed. In other words, id="" must come before token_id="" which in turn must come before variant_id="". There can be other attributes inserted in between, but the overall order must be as I've described.

If you don't know that the order will be like that, you'd have to run several preg_match_all …

edwinhermann 57 Junior Poster

A simpler way would be this single-line solution:

print 'There are '.preg_match_all('/[aeiou]/i',$_POST["fname"],$matches).' in the string ('.$_POST["fname"].')';
nav33n commented: Neat! :) +6
edwinhermann 57 Junior Poster

Thanks! This has been informative to say the least and I apologize about the lack of details.

I DO know the names of all the variables, it's the values and the combination that I won't know.

The form is an order processing script, where the user selects one of the known products, selects if it's going to be Net30 or Credit Card, then submits information depending on Net30 or CC chosen as the payment method.

In that case you just build the logic by checking whether certain information has been submitted, e.g.

if (isset($_POST["FirstName"))

or whether it's empty:

if ($_POST["FirstName"] == "")

and other such logic.

Since I know the variables, I usually use:

<?php
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
// rest of post items...

And so on. The problem that I have with this is that I'm declaring all of the variables one-by-one and I feel that it's being far more tedious than it should be. I also feel that calling "$_POST" everytime I need it is excessive, but I may be incorrect on this one.

There are two approaches:

1. You can turn on Register Globals (see http://php.net/manual/en/security.globals.php) but I advise against it because of its security implications, and it's also just not a very clean method. Register Globals allows you to reference $_POST["abc"] as just $abc. You can probably guess the dangers of this. Also worth noting is that Register Globals is deprecated as of version 5.3.0 and removed in PHP 6.0.0, so even …

edwinhermann 57 Junior Poster

Your could should work but I don't see the link between processing the form variables at the beginning and the mailing code.

You might need to provide more information as to what you are wanting to do. The nature of your logic will determine the logic required in your code.

Just to clarify: If you know what the names of the POST variables will be you don't need the foreach loop. But (if I've understood you correctly) your form is dynamic and you don't know what the names of the variables will be, in which case the best thing to do is to use a foreach() loop.

If you DO know all the possible variable names, just that some might not be present, you can do it differently, like this:

$use_name = "";
if (isset($_POST["FirstName"])) {
  $use_name = $_POST["FirstName"];
  if (isset($_POST["LastName"])) {
    $use_name .= " ".$_POST["LastName"];
    }
  }
elseif (isset($_POST["Title"]) || isset($_POST["LastName"])) {
  $use_name = $_POST["Title"]." ".$_POST["LastName"];
  }
else {
  $use_name = "Customer";
  }

and later in your code when you send the email:

$email_message = "Dear ".$use_uame.",\nThank you for signing up to our newsletter....";
// more code to determine the rest of $email_message
if (!mail($email_to,$email_subject,$email_message,$email_headers)) {
  echo "An error occurred!";
  }
else {
  echo "We have sent you a welcome email.";
  }

The two pieces of code determine how to write the greeting line of an email. It will produce:
Dear John Smith (if both names are available)
Dear John (if only the first …

edwinhermann 57 Junior Poster

That would be the best way. You'd do something like this:

foreach($_POST as $name => $value) {
  switch ($name) {
    case "colour":
    // logic here to handle the colour
    break;
    case "size":
    // logic here to handle the type
    break;
    case "type":
    // logic here to handle the type
    break;
  }
}

foreach is the best way of stepping through an array (such as $_POST) to find all the values and keys

edwinhermann 57 Junior Poster

hi, i've got a problem,
hmm...there are three groups (A,B, and C) and their IP address are:
A ==> 10.204.xxx.xxx
B ==> 10.205.xxx.xxx
C ==> 10.206.xxx.xxx

how to read an IP Address, but only for 2 octet, (10.204, 10.205, 10.206)?
I want to put them on index.php, so:
if user IP come from 10.204.xxx.xxx, it will directing to: www.portalA.com,
10.205.xxx.xxx www.portalB.com

The following will work so long as there's no proxy in the way. If there is, you'll need to first check whether $_SERVER["X_FORWARDED_FOR"] exists, and if so, assign $ip that value, otherwise assign S_SERVER["REMOTE_ADDR"].

Not all proxies forward on the original IP address, in which case it will be impossible to tell the real IP address.

However, if you're on a LAN or there's no proxy, the following will work:

<?php

$ip = $_SERVER["SERVER_ADDR"];
$twoOctets = substr($ip,0,strpos($ip,".",strpos($ip,".")+1));
switch ($twoOctets) {
  case "10.204":
  header("Location: http://www.portalA.com");
  exit;
  break;
  case "10.205":
  header("Location: http://www.portalB.com");
  exit;
  break;
  case "10.206":
  header("Location: http://www.portalC.com");
  exit;
  default:
  // put code here to cover no match
}

?>
danang commented: solved my problem +0
edwinhermann 57 Junior Poster

.htaccess can password protect portions of your site. If your private pages are intermingled with public pages in the same directory, you can create a .htaccess file to go in the root of your Web directory, like this:

<Files private_*>
AuthUserFile /path/to/.htpasswd
AuthName "Private"
AuthType Basic
Require valid-user
</Files>

That means that any php files beginning with "private_" (e.g. private_showusers.php, private_editaccount.php) will be password protected. Note that with AuthType set to "Basic" means that your password is sent in the clear, so it's not particularly safe unless you do it over SSL (i.e. as part of https://)

The .htpasswd file takes the format:

username:hash

where "username" is the login name (you can pick one) and "hash" is the standard unix password hash of a password. If you don't know how to use crypt() on Unix, you can use PHP as follows

<?php echo crypt("mypassword","salt"); ?>

Replace "mypassword" with your password (pick one) and replace "salt" with two random characters (e.g. 6v or dR etc).

Alternatively, you can use this online tool to do it: http://www.functions-online.com/crypt.html

The .htpasswd file should live outside of the public Web directories, but be readable by at least the Web server process.

A better way is to have all your private pages in a directory of their own (rather than mixed in with public pages in the same directory), in which case the .htaccess file would go in the root of that private directory and you can …

diafol commented: good advice EH, learned a bit myself +3
Atli commented: Very useful info. +3
edwinhermann 57 Junior Poster

You have an extra tab character after EOSTYLE; (line 29 in your code above)

Delete that line and retype it, taking care not to add any extra characters after the semi-colon.

edwinhermann 57 Junior Poster

If you're wanting to encrypt it so that clients can't "steal" your code, then there are a number of solutions out there - codejoust has suggested one (zend encoder). Zend is apparently very good but very expensive ($600 I think).

There is also:

Ioncube - http://www.ioncube.com/sa_encoder.php ($199)
Source Guardian - http://www.sourceguardian.com/ ($199)
Nusphere - http://www.nusphere.com ($149)
PHPshadow - http://phpshadow.www.co.nz ($90)

edwinhermann 57 Junior Poster

As ardav says, you need urlencode, but you should not use htmlentities. YOu only use htmlentities when you are outputting HTML. The header is not HTML - it's part of the underlying HTTP protocol.

diafol commented: good spot +4
andym67 commented: Thanks +1
edwinhermann 57 Junior Poster

unique, and random are mutually exclusive

They may mean different things, but they're not mutually exclusive.

For them to be mutually exclusive would mean that anything unique cannot be random and anything random cannot be unique.

It is actually possible to generate something that is both random and unique (the latter via a test against a history list).

000000
then

<?php $file = "/cgi-bin/countforms.bcnt";
$form_id = file_get_contents( $file ) + 1;
$fp = fopen($file, "w");
fputs ($fp, "$form_id");
fclose($fp); ?>
<input type='hidden' name='form_id' value='<?php echo $form_id;  ?>'>

Your code doesn't preserve the zero-padding. Changing this line:

fputs ($fp, "$form_id");

to this:

fputs ($fp, sprintf("%06d",$form_id));

would fix that.

almostbob commented: Thanks the obvious, is so hard to see +4