...

Hi! I’m Starx

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

php file upload permission?

Question by user1200640

I am using the following script to upload pictures to my website. It is working perfectly on my local machine. but when I am running on my FTP account with godady it showing me the permission error. I already gave it the 777 permission from my client FTP, but it is still showing me this.

<?php
include ("login.php");
if ($_POST['submit']){


    $name = $_FILES['upload']['name'];
    $temp = $_FILES['upload']['tmp_name'];
    $type = $_FILES['upload']['type'];
    $size = $_FILES['upload']['size'];

    if (($type == "image/jpg") || ($type == "image/png") || ($type == "image/gif") || ($type == "image/jpeg")){
        if  ($size <= 1000000){

                move_uploaded_file($temp,$name);
                echo "<img src='$name'>";
            } else {
                    print"your image file is too big";
                }

        }else {
                print "this file type is not allowed!";
            }


    }else{
            header ("Location: login.php");
        }


?> 

and

<form action="upload.php" method="post" enctype="multipart/form-data">
File: <input type="file" name="upload">
<input type="submit" name="submit" value="Upload!">
</form>

the problem:

Warning: move_uploaded_file(1 (12).jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in D:Hosting8923686htmluploadedimagesupload.php on line 13

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'D:TempphpphpF893.tmp' to '1 (12).jpg' in D:Hosting8923686htmluploadedimagesupload.php on line 13

How do I fix this problem ?

Answer by Starx

Your webserver does not have access to your local drives.

D:Hosting8923686htmluploadedimages is invalid

Use relative path which points to your folder, not the direct path

Something like

move_uploaded_file($temp, "uploadedimages/$name");
Read more

MailTo using Browser Options in new window IE 8

Question by abcdefghi

Below is the HTML

<a id="LnkEmail" onclick="doMailto('d@s.com');" href="javascript:void(0);">
<span id="LblEmail">ABC</span></a>

Javascript

<script type="text/javascript">
    function doMailto(EmailAddress) {
        document.location.href = window.open('mailto:' + EmailAddress, 'new window');
    }

</script>

In FireFox, it opens the image on clicking the span like below.

enter image description here
Query – In IE 8 – Nothing happens on clicking it. Any Idea ?

Answer by Starx

The mailing list is an utility features provided by Firebox only. You may or may not not find one software’s feature on another similar one. If you don’t, you should settle for a work around.

Try to remember that in firefox once the user selects a default mail client, you will not get the popup anymore. So there is no use of attempting to create a solution, that is not going to be permanent.

To trim down your requirement, you are trying to select the mail client of the user. But a website cannot changed the system settings of the user, its simply not allowed. Why? Because it opens many vulnerabilities to the user, if this was somehow allowed.

Read more

Reverse whole date in php

Question by NaeemX2

OK,

i was using following code to reverse a date to use in php yesterday.

<?php
$d=date("F j Y");
$d=explode(" ", $d);
$month=$d[0];
$day=$d[1];
$year=$d[2];
<?php for ($i=10; $i>0; $i--)
{
      $date=$month."-".$day--."-".$year;
      echo $date;
?>

this was working for me till yesterday 31 March Night. but in the morning on april 1 its started printing

April-1-2012

April-0-2012

April–1-2012 April–2-2012

and so on.

this was the bad logic i used to reverse a date. i realized it soon.
i want this like following.

April-1-2012

March-31-2012

March-30-2012

March-29-2012

and so on

so how this could be possible ?

Thanks in advance.


Well, this also a logic that work perfect for me i made after post of question. but i am really thankful for all answers. that also making me many things clear.

<?php
$d=date("F j Y");
 for ($i=0; $i>-10; $i--)
 {
$date="<br>".date('F-j-Y', strtotime("+$i days"));
echo $date;
}
?>

Answer by Starx

This is probably the quickest way to do it

for($i=1; $i <= 10; $i++) {
    echo date("F j Y", time()-($i*24*60*60)); //Instead of 24*60*60 write 86400 to increase slight performance
}

Demo

Read more

limit PHP script to one domain per license

Question by Mac Os

I’m encoding my script with Ioncube and want to ensure that it works only on the licensed domain. How is this commonly done?

I was thinking something like:

function domain(){

}

if($this_domain <> domain()){
   exit('no');
}

or

$allowed_hosts = array('foo.example.com', 'bar.example.com');
if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) {
    header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
    exit;
}

But I’m not sure if that’s correct. Would strpos be better?

Answer by Starx

This is a wasted attempt. As any determined developer can hack your code and remove the blocking algorithm.

However, as per the algorithm goes, this is fine

$allowed_hosts = array('foo.example.com', 'bar.example.com');
if (!in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) {
    header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
    exit;
}
Read more

Which should I use? (performance)

Question by Yim

I want to know a simple thing:

when setting up a style that is inherited by all its children, is it recommended to be most specific?

Structure: html > body > parent_content > wrapper > p

I want to apply a style to p but respecting these:

  • I don’t care having parent_content or wrapper having the style
  • I do care changing the html or body style (or all p)

So what should I use?

#parent_content{
    color:#555;
}

#parent_content p{
    color:#555;
}

#wrapper{
    color:#555;
}

#wrapper p{
    color:#555;
}

/*...etc...*/

Also, some links to tutorials about this would be great

Answer by Starx

In the matter of specificity, give an id to the p and use

#paragraphid {}

But the answer depends what actually are your need. I will break down your code

#parent_content{
    color:#555;
}

Will apply the color the text inside and may be inside its children also

#parent_content p{
    color:#555;
}

Will apply the color to all the p inside #parent_content and its children

#wrapper{
    color:#555;
}

Will apply the color to all the text inside it, and of its children

Read more

How can I generate a number that never be the same again(repeated) PHP

Question by yeah its me

Possible Duplicate:
Algorithm for generating a random number

is posible to generate a random number that is never repeated??

Is there a solution in php? or codeIgniter?

for example if i need to generate a random never repeated id for every user, how can i be sure that no user will have the same id?

Answer by Starx

Clearly speaking, there is always a chance for a number since every form is generated from same algorithm generally.

The safest way would be to check you database to ensure that, if an id is already taken like:

$id = "1"; //Your id to check
$query = "SELECT * FROM table where id=?";
$result = mysql_query($query);
if(mysql_num_rows($result)) { 
  //the id is present
}

It will be better if you use mysqli instead

$id = "1"; //Your id to check
$query = "SELECT * FROM table where id=?";
$stmt = mysqli_prepare($link, $query);
mysqli_stmt_bind_param($stmt, "i", $id);
mysql_stmt_execute($stmt);
if(mysql_stmt_num_rows($stmt))
  //the id is present
}  
mysqli_stmt_close($stmt);
Read more
March 31, 2012

I want to INSERT VALUES but I don't want user to navigate to this page

Question by user1304328

I want to INSERT VALUES after user has clicked OK on the confirmation box. Now the confirmation box works well. The only problem I can see is that when the user clicks ‘OK’ I want the INSERT VALUES to happen on a seperate page (insertQuestion.php) but I do not want the form to be navigated to that page. I want the form to navigate the way it is doing which is either submit to its own page or submit to create_session.php depending on the situation ($action).

So how can I INSERT VALUES into the database without navigating the user to that page (insertquestion.php) after the user has clicked ‘OK’ in the confirmation box?

below is the javascript code where the confirmation box appears and if confirmation is ‘OK’, it submits the form:

 function showConfirm(){

             var confirmMsg=confirm("Do you want to Proceed" + "n" );

             if (confirmMsg==true)
             {
             submitform();   
         }
    }

 function submitform()
            {

        var QandAO = document.getElementById("QandA");

          QandAO.submit();

            }

Answer by Starx

Post the form using an ajax request.

A simple example using jQuery

$("#yourbutton").click(function() {
   var fieldvalue = $("#inputname").val(); //grab the form value
   $.post("yourpage.php", //send it to yourpage.php
       {
          field1: fieldvalue
       }, function(data) {
         //do something on success
       }
   );
});
Read more

Remove duplicate commas and extra commas at start/end with RegExp in Javascript, and remove duplicate numbers?

Question by Mohammad

Assume we have a string like the following :

,34,23,4,5,634,23,12,5,4,3,1234,23,54,,,,,,,123,43,2,3,4,5,3424,,,,,,,,123,,,1234,,,,,,,45,,,56

How can we convert it to the following string with RegExp in Javascript ?

34,23,4,5,634,12,3,1234,54,123,43,2,3424,45,56

Actually, I wanna remove repeated items and first and last , char

Answer by ninjagecko

[edited] To turn these into a set of unique numbers, as you are actually asking for, do this:

function scrapeNumbers(string) {
    var seen = {};
    var results = [];
    string.match(/d+/g).forEach(function(x) {
        if (seen[x]===undefined)
            results.push(parseInt(x));
        seen[x] = true;
    });
    return results;
}

Demo:

> scrapeNumbers(',1,22,333,22,,333,4,,,')
[1, 22, 333, 4]

If you had an Array.prototype.unique() primitive, you could write it like so in one line:

yourString.match(/d+/g).map(parseBase10).unique()

Unfortunately you need to be a bit verbose and define your own parseBase10 = function(n){return parseInt(n)} due to this ridiculous hard-to-track-down bug: javascript – Array.map and parseInt

Answer by Starx

No need for regex. Few tricks

text = ',34,23,4,5,634,23,12,5,4,3,1234,23,54,,,,,,,123,43,2,3,4,5,3424,,,,,,,,123,,,1234,,,,,,,45,,,56';
text = text.replace(/,+/g, ','); //replace two commas with one comma
text = text.replace(/^s+|s+$/g,''); //remove the spaces
textarray = text.split(","); // change them into array
textarray = textarray.filter(function(e){ return e.length});
console.log(textarray);                                       


// Now use a function to make the array unique
Array.prototype.unique = function(){
   var u = {}, a = [];
   for(var i = 0, l = this.length; i < l; ++i){
      if(this[i] in u)
         continue;
      a.push(this[i]);
      u[this[i]] = 1;
   }
   return a;
}

textarray = textarray.unique();
text = textarray.join(','); //combine them back to what you want
console.log(text);

Demo

If you are familier with jQuery

text = text.replace(/,+/g, ',');
text = $.trim(text);
text = $.unique(text.split(",")).filter(function(e){ return e.length}).join(",");
console.log(text);

Demo

Read more

User specific stylesheet?

Question by user1305075

I have a website where a user chooses a template of their choice for their web page.

Once they’ve selected the template, I want them to be able to change some of the styles such as the font colour etc?

Is there a way I could do this?

I thought of perhaps storing the user specified stuff in a field in a database and then retrieve it and display as internal CSS?

Answer by Monojit

You may use a user.css (initially empty) for each user and then add data provided by user with !important override.

Answer by Starx

Yes

It is possible. But you will have to rely on Javascript to add the stylesheet, url selected.

Assuming you would be using a link to change the theme, using jQuery, you would do

$('#red').click(function (){
   $('#linktagid').attr('href','user_red.css');
});
Read more

How to calculate driven distance using latitude & longitude in php?

Question by hazem

Given something like this:

//$unit="K";
//$unit="m";

$driven_distance ($lat1, $lng1, $lat2, $lng2, $unit);

How I can I get the time between these two points?

Answer by Starx

A pick out function [Source]

function getDistance($latitude1, $longitude1,
$latitude2, $longitude2, $unit = 'Mi')
{
   $theta = $longitude1 - $longitude2;
   $distance = (sin(deg2rad($latitude1)) *
   sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) *
   cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
   $distance = acos($distance);
   $distance = rad2deg($distance);
   $distance = $distance * 60 * 1.1515;
   switch($unit)
   {
      case 'm': break;
      case 'K' : $distance = $distance *1.609344;
   }
   return (round($distance,2));
}

This functions rounds the result to two decimal places.

Now use exatly the way you are using

$driven_distance = getDistance($lat1,$lng1,$lat2,$lng2,$unit);

Update:

If you want to find out the driven distance the best bet is to use google’s geocode api.

$json = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$long&sensor=true_or_false
');
$details = json_decode($json, TRUE);
var_dump($details);
Read more
...

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