...

Hi! I’m Starx

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

Copy file from remote server or URL

Question by Kris

I have the following code:

    $file = 'http://3.bp.blogspot.com/-AGI4aY2SFaE/Tg8yoG3ijTI/AAAAAAAAA5k/nJB-mDhc8Ds/s400/rizal001.jpg';
    $newfile = '/img/submitted/yoyo.jpg';

    if ( copy($file, $newfile) ) {
        echo "Copy success!";
    }else{
        echo "Copy failed.";
    }

and it always output “Copy failed”

copy(/img/submitted/yoyo.jpg) [function.copy]: failed to open stream: No such file or directory

my directory is set to 777.

any ideas? thanks!

Answer by Mark Biek

While copy() will accept a URL as the source argument, it may be having issues a url for the destination.

Have you tried specifying the full filesystem path to the output file? I’m assuming you’re not trying to put the new file onto a remote server.

For example:

$file = 'http://3.bp.blogspot.com/-AGI4aY2SFaE/Tg8yoG3ijTI/AAAAAAAAA5k/nJB-mDhc8Ds/s400/rizal001.jpg';
$newfile = $_SERVER['DOCUMENT_ROOT'] . '/img/submitted/yoyo.jpg';

if ( copy($file, $newfile) ) {
    echo "Copy success!";
}else{
    echo "Copy failed.";
}

The above worked nicely for me.

Answer by Starx

You cannot copy a file from a server without having access to it.

You can ftp_get() to open up a FTP connection and copy file.

$local_file = 'localname.zip'; // the nam
$server_file = 'servername.zip';
$conn = ftp_connect($ftp_server);

$login_result = ftp_login($conn, $ftp_user_name, $ftp_user_pass);

if (ftp_get($conn, $local_file, $server_file, FTP_BINARY)) {
    echo "Successfully copied";
}
ftp_close($conn);

If you want to download a file from URL

$fullPath = "filepath.pdf";

if ($fd = fopen ($fullPath, "r")) {
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
    header("Content-type: application/octet-stream");
    header("Content-Disposition: filename="".$path_parts["basename"].""");
    header("Content-length: $fsize");
    header("Cache-control: private"); //use this to open files directly
    while(!feof($fd)) {
        $buffer = fread($fd, 2048);
        echo $buffer;
    }
}
fclose ($fd);
Read more

Why is this PHP comparison failing?

Question by Paul

I’m trying to compare a defined code against a set of blocked country codes. In the following example the country code is getting caught in my if block:

$country_code = 'US';

if ($country_code == ("NG" || "RO" || "VN" || "GH" || "SN" || "TN" || "IN" || "ID" || "KE" || "CN" || "CI" || "ZA" || "DZ" || "RU")) {
    print "COUNTRY CODE: $country_code<br>";
}

I see this for my results”

COUNTRY CODE: US

I wouldn’t expect ‘US’ to get caught…what am I missing?

Answer by Brad

What you are doing is OR-ing strings together. Since non-empty strings converted to boolean values are true, this evaluates to the following:

$country_code == true

Since $country_code is also a non-empty string, that also evaluates to true:

true == true

Thus, you get TRUE.

To solve your problem, you need to do what Pekka suggests:

if (in_array($country_code, array('NG', 'RO', etc.)))

See also:

Answer by Starx

This would be a lot simpler if done this way.

$codes = array("NG", "RO", "VN");

$search = array_search("NG");
if($search) {
    echo $codes[$search];
}
Read more

PHP advice: To be or not to be Variable Variables

Question by matt

is it useful to implement variable variables in PHP?

(Try not to leave this post just with a yes/no answer. The importance here, and for what I’m asking, is about the fundamentals of your opinion.)

Thanks!

Answer by Starx

Depends entire upon the requirement of the application.

I will give you a scenario

$array = array(1,2,3,4,5,6,7,8); //This array holds the number of time you have been on the mission
$month1 = "January"; //this holds when it happened
$month2 = "March";

//Now, the colonel  might want to know when the mission happened    
foreach($array as $value) {
    $v = "month".$value;
    echo $$v;
}
Read more

Javascript – Cannot call method 'split' of null

Question by Lelly

I have a javascript error that occurs on my site, Im pretty sure I know why, but I dont know how to fix it!

here’s the error:

Uncaught TypeError: Cannot call method 'split' of null

Here’s my JS code:

$(function(e) {
    if (document.cookie.indexOf("login") >= 0) {
        $("a#loggedInUser").html( $.cookie("login").split("|")[0] );
    }
});

I’m just trying to display the username stored in the “login” cookie. Now, im pretty sure the error is because the value returned sometimes isn’t a string, then it doesn’t have the split method, so it causes this error.

How can I fix that? Any ideas?

Thanks!

Answer by Jamund Ferguson

Well you can do something like this to set a default if the value is null.

var login = $.cookie("login") || "";
$("a#loggedInUser").html(login);

Also, if you do that you might not need the document.cookie.indexOf thing.

Answer by Starx

Check the length of the cookie. This way you validate two things at once.

if (document.cookie.indexOf("login") >= 0 && $.cookie("login").length) {
    $("a#loggedInUser").html( $.cookie("login").split("|")[0] );
}
Read more

Problems with my javascript, I dont want to validate <select> tags that are disabled

Question by ps__

This javascript will find all my selects and validate them but I want to add that it doesnt validate my disabled selects. How can I code that in my javascript?

$("#next-step").click(function () {

                var $step = $(".wizard-step:visible"); // get current step

                var validator = $("form").validate(); // obtain validator
                var anyError = false;
                $step.find("select").each(function () {
                    if (!validator.element(this)) { // validate every input element inside this step
                        anyError = true;
                    }


                });

                if (anyError)
                    return false; // exit if any error found

Thanks in advance!

Answer by ehynds

if (!this.disabled && !validator.element(this)) {
    anyError = true;
}​

or (slower)

$step.find("select:enabled").each(function() {
    if (!validator.element(this)) {
        anyError = true;
    }
});​

Answer by Starx

The easiest way, i know of is to give the select tags, a class like skipvalidation and then

$("form").validate(
   ignore: ".skipvalidation"
);

You can find all the disabled elements and add the class as

$("input:disabled").addClass("skipValidation");
$("form").validate(
   ignore: ".skipvalidation"
);
Read more

Search array key from form post and get sub array

Question by Vince Lowe

I have an array which is storing server addresses like so

$servers = array(
  'UK'=>array(
    'voi' =>  '54.53.23.32',
    'gps' =>  '55.65.34.34',
    'sos' =>  '54.54.34.23'
  ),
  'USA'=>array(
    'voi' =>  '12.23.45.67',
    'gps' =>  '65.443.23.45',
    'sos' =>  '12.23.456.4'
  )
);

I have a form which is listing the server locations

<select name="server" id="server">
<?php foreach($servers as $key => $arr){
echo "<option>" .$key. "</option>"; }
?>
</select>

Once the form is submitted i need to set a session variable with the correct countrys IP’s

$_SESSION['voi']=$submitted_countrys_voi_ip;
$_SESSION['gps']=$submitted_countrys_gps_ip;

etc..

How can i choose the correct key based on the form post and get the values from the sub array into a session variable?

Answer by Starx

First of all, you select does not have a value. So fixed that first

<select name="server" id="server">

    <?php foreach($servers as $key => $arr){
    echo "<option value='$key'>" .$key. "</option>"; }
    ?>

</select>

Then, after the form is submitted. Assuming that form is submitted using POST method

$server = ..; //Being your array of ips
$sub_server = $_POST['server']; //get the submitted server
$_SESSION['voi'] = $server[$sub_server]['voi'];
$_SESSION['gps'] = $server[$sub_server]['gps'];
// and so on

Improvement

In case you have lots of IP’s for a nation, then you might want to create an array of the types first.

$server = ..; 
$types = array('voi','gps', 'sos'); //TYPES in a single array
$sub_server = $_POST['server']; 
foreach($types as $type) {
    $_SESSION[$type] = $server[$sub_server][$type];
}

This is automatically assign every types at once.

Read more

Stop user from progressing in a multi-step jQuery form if datepicker value is blank

Question by methuselah

How would I validate the “date picker” field on step 3 of my multi-step jQuery form. Right now the field just checks if $(‘#datepicker’).val() is empty by sending an alert but still lets the user carry on until the next stage. How do you prevent the user from carrying on if the field is blank?

It can be found here: http://jsfiddle.net/xSkgH/28/

Thanks in advance!

Answer by Starx

Pretty simple, just return false;

if (!$('#datepicker').val()){
     //alert('no date!');   
     return false;                
}

Fixed fiddle

Updated Demo with inline Message

if (!$('#datepicker').val()){
    $("#errorMessage").html('no date!');   
    return false;                
}
Read more

window.open() does nothing in jquery mobile?

Question by PathOfNeo

i can’t use target=_blank because my actions are build dynamically, example: when user clicks on the link, i catch it with .click(function(event), than ajax api is called and then in the callback i have the url where to go.

Now the problem:

window.location = mylink; // WORKS – OK!
window.open(mylink); // DOES NOT WORK – NOT OK!

why?

I need to open a new window because mylink is a link to a pdf file, and when using window.location the pdf file is correctly viewed, but,..without any back navigation controls of the browser. It’s a mobile webapp, and i use jquery mobile.

Too bad on the internet many others have the pdf viewer problem but no one has solved it, so i figured out to open a new window and pass the pdf link there. This way my parent window would stay untouched. Otherwise, you have to kill the current session and open safari again..

Answer by Starx

If you want to open a dialog/popup in jQuery Mobile you have to use an attribute data-rel="dialog" and the href attribute must point to a URL you want to load

<a href="yourpage.html" data-role="button" data-rel="dialog">Open dialog</a>
Read more

smooth auto scroll by using javascript

Question by hiteshtr

hi i am trying to implement a code on my web page to auto scroll after loading the page, i used javascript function to perform auto scrolling and called my function onload event of body of my page but the page is not scrolling smoothly so tell me any way to auto scroll my page smoothly my javascript function is as follows:

function pageScroll() {
        window.scrollBy(0,50); // horizontal and vertical scroll increments
        scrolldelay = setTimeout('pageScroll()',100); // scrolls every 100 milliseconds
}

Answer by mikeymeows

It’s not smooth because you’ve got the scroll incrementing by 50 every 100 milliseconds.

change this and the amount you are scrolling by to a smaller number to have the function run with the illusion of being much more ‘smooth’.

turn down the speed amount to make this faster or slower.

function pageScroll() {
    window.scrollBy(0,1);
    scrolldelay = setTimeout('pageScroll()',10);
}

will appear to be much smoother, try it 😉

Answer by Starx

Smoothly running animations depends on the clients machine. No matter how fairly you code, you will never be satisfied the way your animation runs on a 128 MB Ram system.

Here is how you can scroll using jQuery:

$(document).scrollTop("50");

You might also want to try out AutoScroll Plugin.

Read more

jQuery can't use $.ajax on Dynamically loaded content

Question by Abhishek Biswal

I was working on a Login Form ( AJAX ) enabled. When a use clicks on link, that Login box, as a floating modal appears. The Content of that Login box is loaded from another page using jQuery’s $().load function. On click of the link the Login Box loads. But, when I implemented AJAX submitting on that form:

$(document).ready(function(){
    $("form#loginbox").submit(function(e){ e.preventDefault(); /*AJAX function here*/ });
});

But the form is submitted normally, without following what is given in the function, that is ( Prevent the Default – Submitting and use AJAX ). so does that mean the Loaded content is not considered inside DOM or the script cannot read it? I load the content only once:

$(document).ready(function(){
    if($("#loadedform").html() == "")
    { $(this).load('/load/login.html'); }
    $(".login-modal').slideDown('slow');
});

The structure:

<div class="login-modal"><div id="loadedform"></div></div>

the content to be loaded:

<form id="loginbox" method="post" action="xyz.html">
<!-- INPUT Boxes and Submit Button -->
</form>

Answer by Richard Dalton

Change

$("form#loginbox").submit(function(e){ 
    e.preventDefault(); 
    /*AJAX function here*/ 
});

to

$('#loadedform').on("submit", "form#loginbox", function(e){ 
    e.preventDefault(); 
    /*AJAX function here*/ 
});

or if you’re using a version before 1.7:

$('#loadedform').delegate("#loginbox", "submit", function(e){ 
    e.preventDefault(); 
    /*AJAX function here*/ 
});

This is because the event is registered when the page is loaded, so when your form is loaded it does not have the event attached. This change will register the event at a higher level in the dom so any new content will also work.

It also looks like you should change the code that loads the form to:

if($("#loadedform").html() == "") { 
    $("#loadedform").load('/load/login.html'); 
}
$(".login-modal').slideDown('slow');

Otherwise you won’t be loading it into the right place.

Answer by Starx

You have to delegate over the dynamic elements using .on() method

$(document).on("submit","#loginbox", function() {
 e.preventDefault(); 
 /*AJAX function here*/
});
Read more
...

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