Friday, 18 August 2017

HTML APIs: What They Are And How To Design A Good One

HTML APIs: What They Are And How To Design A Good One


As JavaScript developers, we regularly forget that not everybody has a similar data as USA. It’s referred to as the curse of knowledge: once we’re associate expert on one thing, we have a tendency to cannot keep in mind however confused we have a tendency to felt as newbies. we have a tendency to overestimate what folks can notice simple. Therefore, we predict that requiring a bunch of JavaScript to initialize or piece the libraries we have a tendency to write is OK. Meanwhile, a number of our users struggle to use them, frantically repetition and pasting examples from the documentation, tweaking them indiscriminately till they work.

One in 2 folks that write hypertext mark-up language and CSS isn't comfy with JavaScript. One in two. Let that sink certain  an instant.

As associate example, check out the subsequent code to initialize a jQuery UI autocomplete, taken from its documentation:

<div class="ui-widget">
    <label for="tags">Tags: </label>
    <input id="tags">
</div>

$( function() {
    var availableTags = [
        "ActionScript",
        "AppleScript",
        "Asp",
        "BASIC",
        "C"
    ];
    $( "#tags" ).autocomplete({
        source: availableTags
    });
} );

This is straightforward, even for people that don’t recognize any JavaScript, right? Wrong. A non-programmer would have all forms of queries looking their head once seeing this instance within the documentation. “Where do I place this code?” “What area unit these braces, colons associated brackets?” “Do i want them?” “What do I do if my part doesn't have an ID?” and then on. Even this small snip of code needs individuals to grasp object literals, arrays, variables, strings, a way to get a relation to a DOM part, events, once the DOM is prepared and far a lot of. Things that appear trivial to programmers may be associate uphill battle to HTML authors with no JavaScript information.

Now take into account the equivalent declarative code from HTML5:

<div class="ui-widget">
    <label for="tags">Tags: </label>
    <input id="tags" list="languages">
    <datalist id="languages">
        <option>ActionScript</option>
        <option>AppleScript</option>
        <option>Asp</option>
        <option>BASIC</option>
        <option>C</option>
    </datalist>
</div>

Not solely is that this abundant clearer to anyone World Health Organization will write hypertext mark-up language, it's even easier for programmers. we have a tendency to see that everything is about in one place, no have to be compelled to care concerning once to initialize, a way to get a respect to the component and the way to line stuff thereon. No have to be compelled to grasp that perform to decision to initialize or that arguments it accepts. And for a lot of advanced use cases, there's additionally a JavaScript API in situ that enables all of those attributes and components to be created dynamically. It follows one among the foremost basic API style principles: It makes straightforward} easy and therefore the advanced doable.

This brings U.S.A. to a crucial lesson concerning hypertext mark-up language APIs: they might profit not solely individuals with restricted JavaScript ability. For common tasks, even we, programmers, square measure usually wanting to sacrifice the flexibleness of programming for the convenience of declarative markup. However, we have a tendency to somehow forget this once writing a library of our own.

So, what's Associate in Nursing hypertext mark-up language API? in line with Wikipedia, Associate in Nursing API (or application programming interface) is “is a group of software definitions, protocols, and tools for building application computer code.” In Associate in Nursing hypertext mark-up language API, the definitions and protocols square measure within the hypertext mark-up language itself, and therefore the tools look in hypertext mark-up language for the configuration. hypertext mark-up language Apis typically accommodates bound category and attribute patterns that may be used on existing hypertext mark-up language. With net elements, even custom component names square measure game, and with the Shadow DOM, those will even have a whole internal structure that's hidden from the remainder of the page’s JavaScript or CSS. however this is often not a piece of writing concerning net elements; net Components provide a lot of power and choices to hypertext mark-up language API styleers; however the principles of excellent (HTML) API design square measure an equivalent.

HTML Apis improve collaboration between designers and developers, carry some work from the shoulders of the latter, and change designers to make abundant higher-fidelity mockups. as well as Associate in Nursing hypertext mark-up language API in your library doesn't simply build the community a lot of inclusive , it additionally ultimately comes back to profit you, the engineer.

Not each library desires Associate in Nursing hypertext mark-up language API. hypertext mark-up language Apis square measure largely helpful in libraries that change UI components like galleries, drag-and-drop, accordions, tabs, carousels, etc. As a rule of thumb, if a non-programmer cannot perceive what your library will, then your library doesn’t would like Associate in Nursing hypertext mark-up language API. as an example, libraries that modify or facilitate to prepare code don't would like Associate in Nursing hypertext mark-up language API. What quite hypertext mark-up language API would Associate in Nursing MVC framework or a DOM helper library even have?

So far, we've mentioned what Associate in Nursing hypertext mark-up language API is, why it's helpful and once it's required. the remainder of this text is concerning a way to style an honest one.

Init Selector


With a JavaScript API, formatting is strictly controlled by the library’s user: as a result of they need to manually decision a operate or produce Associate in Nursing object, they management exactly once it runs and on what. With Associate in Nursing hypertext markup language API, we've got to create that alternative for them, and make certain to not get within the method of the facility users World Health Organization can still use JavaScript and need full management.

The common thanks to resolve the stress between these 2 use cases is to solely auto-initialize components that match a given selector, sometimes a particular category. Awesomplete follows this approach, solely finding out input components with class="awesomplete".

In some cases, creating auto-initialization straightforward is additional vital than creating opt-in specific. this can be common once your library must run on plenty of components, and once avoiding having to manually add a category to each single one is additional vital than creating opt-in specific. for instance, Prism mechanically highlights any &lt;code&gt; part that contains a language-xxx category (which is what the HTML5 specification recommends for specifying the language of a code snippet) or that's within a component that will. this can be as a result of it may be enclosed during a web log with plenty of code snippets, and having to travel back and add a category to each single one in every of them would be an enormous problem.

In cases wherever the init selector is employed terribly munificently, a decent follow is permit|to permit} customization of it or allow opting-out of auto-initialization altogether. for instance, elastic autosizes each &lt;input&gt;, &lt;select&gt; and &lt;textarea&gt; by default, however permits customization of its init selector to one thing additional specific via a data-stretchy-filter attribute. Prism supports a data-manual attribute on its &lt;script&gt; part to utterly disable automatic formatting. a decent follow is to permit this feature to be set via either hypertext markup language or JavaScript, to accommodate each kinds of library users.


Minimize Init Markup


So, for each component the init selector matches, your library wants a wrapper around it, 3 buttons within it and 2 adjacent divs? No downside, however generate them yourself. this type of grunt work is healthier suited to machines, not humans. don't expect that everybody exploitation your library is additionally exploitation some variety of templating system: many of us area unit still hand-crafting markup and realize build systems too sophisticated. build their lives easier.

This additionally minimizes error conditions: What if a user includes the category that you simply expect for initialisation however not all of the markup you need? once there's no further markup to feature, no such errors area unit potential.

There is one exception to the present rule: swish degradation and progressive sweetening. for instance, embedding a tweet involves lots of markup, despite the fact that one component with data-* attributes for all the choices would answer. this can be done in order that the tweet is legible even before the JavaScript hundreds or runs. a decent rule of thumb is to raise yourself, will the additional markup provide a profit to the tip user even while not JavaScript? If thus, then requiring it's OK. If not, then generate it together with your library.

There is additionally the classic tension between easy use and customization: Generating all of the markup for the library’s user is less complicated for them, however exploit them to put in writing it offers them additional flexibility. Flexibility is nice after you want it, however annoying after you don’t, and you continue to ought to set everything manually. To balance these 2 wants, you'll generate the markup you would like if it doesn’t exist already. for instance, suppose you wrap all .foo parts with a .foo-container element? 1st, check whether or not the parent — or, better yet, any ascendant, via component.closest(".foo-container") — of your .foo component already has the foo-container category, and if so, use that rather than making a brand new component.

Settings


Typically, settings ought to be provided via data-* attributes on the relevant part. If your library adds plenty of attributes, then you may wish to namespace them to stop collisions with alternative libraries, like data-foo-* (where foo could be a one-to-three letter prefix supported your library’s name). If that’s too long, you'll use foo-*, however bear in mind that this may break hypertext markup language validation and may place a number of the a lot of diligent hypertext markup language authors off your library owing to it. Ideally, you ought to support each, if it won’t bloat your code an excessive amount of. None of the choices here area unit ideal, thus there's associate current discussion within the WHATWG concerning whether or not to decriminalise such prefixes for custom attributes.

Follow the conventions of hypertext markup language the maximum amount as potential. for instance, if you employ associate attribute for a Boolean setting, its presence means that true despite the worth, and its absence means that false. don't expect things like data-foo="true" or data-foo="false" instead. Sure, ARIA will that, however if ARIA jumped off a formation, would you are doing it, too?

When the setting could be a Boolean, you'll additionally use categories. Typically, their linguistics area unit almost like Boolean attributes: The presence of the category means that true, and also the absence means that false. If you wish the alternative, you'll be able to use a no- prefix (for example, no-line-numbers). confine mind that category names area unit used quite data-* attributes, thus there's a larger chance of collision with the user’s existing category names. you'll think about prefixing your categories with a prefix like foo- to stop that. Another danger with category names is that a future supporter may notice that they're not utilized in the CSS and take away them.

When you have a gaggle of connected Boolean settings, victimisation one space-separated attribute may be higher than victimisation several separate attributes or categories. for instance, &lt;div data-permissions="read add edit delete save logout&gt;" is healthier than &lt;div data-read data-add data-edit data-delete data-save data-logout"&gt;, and &lt;div class="read add edit delete save logout"&gt; would doubtless cause plenty of collisions. you'll be able to then target individual ones via the ~= attribute selector. for instance, element.matches("[data-permissions~=read]") checks whether or not part has the scan permission.

If the sort of a setting is associate array or object, then you'll be able to use a data-* attribute that links to a different part. for instance, scrutinize however HTML5 will autocomplete: as a result of autocomplete needs an inventory of suggestions, you employ associate attribute to link to a &lt;datalist&gt; part containing these suggestions via its ID.

This is a degree once following hypertext markup language conventions becomes painful: In hypertext markup language, linking {to associateother|to a different} part in an attribute is often done by referencing its ID (think of &lt;label for="…"&gt;). However, this is often rather limiting: It’s such a lot a lot of convenient to permit selectors or perhaps nesting if it is sensible. What you accompany can for the most part rely on your use case. simply confine mind that, whereas consistency is very important, usability is our goal here.

It’s OK if not each single setting is out there via hypertext markup language. Settings whose values area unit functions will keep in JavaScript and be thought-about “advanced customization.” think about Awesomplete: All numerical, boolean, string and object settings area unit accessible as data-* attributes (list, minChars, maxItems, autoFirst). All perform settings area unit solely accessible in JavaScript (filter, sort, item, replace, data). If somebody is ready to write down a JavaScript perform to assemble your library, then they will use the JavaScript API.

Regular expressions (regex) area unit alittle of a grey area: usually, solely programmers recognize regular expressions (and even programmers have bother with them!); thus, initially look there doesn’t appear to be any purpose in together with settings with regex values in your hypertext markup language API. However, HTML5 did embody such a setting (&lt;input pattern="regex"&gt;), and that i believe it absolutely was quite winning, as a result of non-programmers will research their use case during a regex directory and replica and paste.


Inheritance


If your UI library goes to be used once or doubly on every page, then inheritance won’t matter a lot of. However, if it may well be applied to multiple parts, then configuring constant settings on every one of them via categories or attributes would be painful. bear in mind that not everybody uses a build system, particularly non-developers. In these cases, it would be helpful to outline that settings is inheritable  from relative parts, in order that multiple instances is mass-configured.

Take Prism, a well-liked syntax-highlighting library, used here on Smashing Magazine yet. The highlight language is designed via a category of the shape language-xxx. Yes, this goes against the rules we tend to mentioned within the previous section, however this was a acutely aware call as a result of the HTML5 specification recommends this for specifying the language of a code piece. On a page with multiple code snippets (think of however usually a journal post concerning code uses inline &lt;code&gt; elements!), specifying the cryptography language on every &lt;code&gt; part would become extraordinarily tedious. To mitigate this pain, Prism supports inheritance of those categoryes: If a &lt;code&gt; part doesn't have a language-xxx class of its own, then the one in every of its nearest relative that will is employed. this permits users to line the cryptography language globally (by putt the category on the &lt;body&gt; or &lt;html&gt; elements) or by section, and override it solely on parts or sections with a special language.

Now that CSS variables square measure supported by each browser, they're a decent candidate for such settings: they're inheritable  by default and may be set inline via the design attribute, via CSS or via JavaScript. In your code, you get them via getComputedStyle(element).getPropertyValue("--variablename"). Besides browser support, their main draw back is that developers don't seem to be nonetheless accustomed them, however that's ever-changing. Also, you can't monitor changes to them via MutationObserver, such as you will for parts and attributes.

Global Settings  


Most UI libraries have 2 teams of settings: settings that customise however every instance of the device behaves, and international settings that customise however the library behaves. So far, we've got in the main mentioned the previous, therefore you would possibly be curious what's a decent place for these international settings.

One candidate is that the &lt;script&gt; component that has your library. you'll get this via document.currentScript, and it's excellent browser support. The advantage of this can be that it’s unambiguous what these settings area unit for, therefore their names are often shorter (for example, data-filter, rather than data-stretchy-filter).

However, the &lt;script&gt; component mustn't be the sole place you choose up these settings from, as a result of some users could also be mistreatment your library during a CMS that doesn't permit them to customise &lt;script&gt; parts. you may conjointly search for the setting on the &lt;html&gt; and &lt;body&gt; parts or maybe anyplace, as long as you have got a clearly declared policy concerning that price wins once there area unit duplicates. (The 1st one? The last one? one thing else?)

Documentation


So, you’ve taken care to style a pleasant declarative API for your library. Well done! but, if all of your documentation is written as if the user understands JavaScript, few are able to use it. I bear in mind seeing a cool library for toggling the show of parts supported the computer address, via hypertext markup language attributes on the weather to be toggled. However, its nice hypertext markup language API couldn't be utilized by the individuals it targeted as a result of the whole documentation was tormented by JavaScript references. The terribly initial example started with, “This is resembling location.href.match(/foo/).” What likelihood will a non-programmer got to perceive this?

Also, bear in mind that a lot of of those individuals don't speak any programing language, not simply JavaScript. don't refer models, views, controllers or alternative software system engineering ideas in text that you just expect them to browse and perceive. All you may bring home the bacon is confusing them and turning them away.

Of course, you must document the JavaScript components of your API furthermore. you may do this in associate “Advanced usage” section. However, if you begin your documentation with references to JavaScript objects and functions or software system engineering ideas, then you’re primarily telling non-programmers that this library isn't for them, thereby excluding an oversized portion of your potential users. Sadly, most documentation for libraries with hypertext markup language arthropod genus suffers from these problems, as a result of hypertext markup language arthropod genus area unit usually seen as a cutoff for programmers, not as the way for non-programmers to use these libraries. Hopefully, this may modification within the future.

What About Web Components?


In the close to future, the net elements quartet of specifications can revolutionize hypertext mark-up language Apis. The &lt;template&gt; part can change authors to supply scripts with partial inert markup. Custom components can change way more elegant init markup that resembles native hypertext mark-up language. hypertext mark-up language imports can change authors to incorporate only 1 file, rather than 3 vogue sheets, 5 scripts and 10 templates (if Mozilla gets its act along and stops thinking that ES6 modules area unit a competitive  technology). The Shadow DOM can change your library to own advanced DOM structures that area unit properly encapsulated which don't interfere with the user’s own markup.

However, <template> aside, browser support for the other three is currently limited.. So, they need giant polyfills, that makes them less engaging for library use. However, it’s one thing to stay on your radiolocation for the close to future.

MarkApp: A List Of Libraries With HTML APIs


If you’ve followed the recommendation during this article, then congratulations on creating the net a more robust, a lot of comprehensive area to be inventive in! I try and maintain an inventory of all libraries that have HTML Apis on MarkApp. Send a pull request and add yours, too!

Wednesday, 16 August 2017

How to use Use isset() Instead of strlen()

How to use Use isset() Instead of strlen()


This is truly a neat trick, though the previous article utterly fails to clarify it. Here is that the missing example:

<?php

if (isset($username[5])) {
    // The username is at least six characters long.
}

?>

When you treat strings as arrays, every character within the string is a component within the array. By determinant whether or not a selected component exists, you'll confirm whether or not the string is a minimum of that several characters long. (Note that the primary character is component zero, therefore $username[5] is that the sixth character in $username.)

The reason this is often slightly quicker than strlen() is difficult. the easy clarification is that strlen() may be a operate, and isset() may be a language construct. usually speaking, business a operate is dearer than employing a language construct.

Tuesday, 15 August 2017

How to use the Suppression Operator Correctly

How to use the Suppression Operator Correctly

Always try to avoid using the error suppression operator. In the previous article, the author states:

The @ operator is rather slow and can be costly if you need to write code with performance in mind.

Error suppression is slow. this is often as a result of PHP dynamically changes error_reporting to zero before corporal punishment the suppressed statement, then like a shot changes it back. this is often costly.

Worse, exploitation the error suppression operator makes it tough to trace down the basis reason for a haul.

The previous article uses the subsequent example to support the apply of assignment a variable by reference once it's unknown if $albus is set:

<?php

$albert =& $albus;

?>

Although this works — for now — relying on strange, unsupported behavior while not a really smart understanding of why it works may be a great way to introduce bugs. as a result of $albert is appointed to $albus by reference, future modifications to $albus will modify $albert.

A much higher resolution is to use isset(), with braces:

<?php

if (!isset($albus)) {
    $albert = NULL;
}

?>

Assigning $albert to NULL is that the same as assignment it to a nonexistent reference, however being specific greatly improves the clarity of the code and avoids the denotative  relationship between the 2 variables.

If you inherit code that uses the error suppression operator too, we’ve got a bonus tip for you. there's a replacement PECL extension known as Scream that disables error suppression.

Friday, 11 August 2017

How to use Shortcut of else

How to use Shortcut of else

This tip accidentally stumbles upon a helpful apply, that is to continually initialize variables before you utilize them. take into account a conditional statement that determines whether or not a user is Associate in Nursing administrator supported the username:

<?php

if (auth($username) == 'admin') {
    $admin = TRUE;
} else {
    $admin = FALSE;
}

?>

This appears safe enough, as a result of it’s straightforward to grasp at a look. Imagine a rather additional elaborate example that sets variables for name and email moreover, for convenience:

<?php

if (auth($username) == 'admin') {
    $name = 'Administrator';
    $email = 'admin@example.org';
    $admin = TRUE;
} else {
    /* Get the name and email from the database. */
    $query = $db->prepare('SELECT name, email
                           FROM   users
                           WHERE  username = :username');
    $query->execute(array('username' => $clean['username']));
    $result = $query->fetch(PDO::FETCH_ASSOC);
    $name = $result['name'];
    $email = $result['email']; 
    $admin = FALSE;
}


?>

Because $admin remains continually expressly set to either TRUE or FALSE, all is well, however if a developer later adds associate elseif, there’s a chance to forget:

<?php

if (auth($username) == 'admin') {
    $name = 'Administrator';
    $email = 'admin@example.org';
    $admin = TRUE;
} elseif (auth($username) == 'mod') {
    $name = 'Moderator';
    $email = 'mod@example.org';
    $moderator = TRUE;
} else {
    /* Get the name and email. */
    $query = $db->prepare('SELECT name, email
                           FROM   users
                           WHERE  username = :username');
    $query->execute(array('username' => $clean['username']));
    $result = $query->fetch(PDO::FETCH_ASSOC);
    $name = $result['name'];
    $email = $result['email']; 
    $admin = FALSE;
    $moderator = FALSE;
}

?>

If a user provides a username that triggers the elseif condition, $admin is not initialized. This can lead to unwanted behavior, or worse, a security vulnerability. Additionally, a similar situation now exists for $moderator, which is not initialized in the first condition.


By first initializing $admin and $moderator, it’s easy to avoid this scenario altogether:

<?php

$admin = FALSE;
$moderator = FALSE;

if (auth($username) == 'admin') {
    $name = 'Administrator';
    $email = 'admin@example.org';
    $admin = TRUE;
} elseif (auth($username) == 'mod') {
    $name = 'Moderator';
    $email = 'mod@example.org';
    $moderator = TRUE;
} else {
    /* Get the name and email. */
    $query = $db->prepare('SELECT name, email
                           FROM   users
                           WHERE  username = :username');
    $query->execute(array('username' => $clean['username']));
    $result = $query->fetch(PDO::FETCH_ASSOC);
    $name = $result['name'];
    $email = $result['email'];
}

?>

Regardless of what the remainder of the code will, it’s currently clear that $admin is fake unless it's expressly set to one thing else, and also the same is true for $moderator. This conjointly hints at another smart security apply, that is to fail safely. The worst that may happen as a results of not modifying $admin or $moderator in associate degreey of the conditions is that somebody United Nations agency is an administrator or moderator isn't treated mutually.

If you wish to route one thing, associate degreed you’re feeling to a small degree thwarted that our example includes an else, we've a bonus tip which may interest you. We’re not sure it will be thought-about a route, however we have a tendency to hope it’s useful notwithstanding.

Consider a operate that determines whether or not a user is allowed to look at a selected page:

<?php
 
function authorized($username, $page) {
    if (!isBlacklisted($username)) {
        if (isAdmin($username)) {
            return TRUE;
        } elseif (isAllowed($username, $page)) {
            return TRUE;
        } else {
            return FALSE;
        }
    } else {
        return FALSE;
    }
}
 
?>

This example is really pretty easy, as a result of there area unit solely 3 rules to consider: directors area unit forever allowed access; people who area unit blacklisted area unit ne'er allowed access; and isAllowed() determines whether or not anyone else has access. (A special case exists once associate administrator is blacklisted, however that's associate unlikely chance, therefore we’re ignoring it here.) we have a tendency to use functions for the foundations to stay the code easy and to specialise in the logical structure.

There area unit varied ways in which this instance will be improved. If you wish to scale back the amount of lines, a compound conditional will help:

<?php
 
function authorized($username, $page) {
    if (!isBlacklisted($username)) {
        if (isAdmin($username) || isAllowed($username, $page)) {
            return TRUE;
        } else {
            return FALSE;
        }
    } else {
        return FALSE;
    }
}
 
?>

In fact, you can reduce the entire function to a single compound conditional:

<?php
 
function authorized($username, $page) {
    if (!isBlacklisted($username) && (isAdmin($username) || isAllowed($username, $page)) {
        return TRUE;
    } else {
        return FALSE;
    }
}
 
?>

Finally, this can be reduced to a single return:

<?php
 
function authorized($username, $page) {
    return (!isBlacklisted($username) && (isAdmin($username) || isAllowed($username, $page));
}
 
?>

If your goal is to reduce the number of lines, you’re done. However, note that we’re using isBlacklisted(), isAdmin(), and isAllowed() as placeholders. Depending on what’s involved in making these determinations, reducing everything to a compound conditional may not be as attractive.

This brings us to our tip. A return immediately exits the function, so if you return as soon as possible, you can express these rules very simply:

<?php
 
function authorized($username, $page) {
 
    if (isBlacklisted($username)) {
        return FALSE;
    }
 
    if (isAdmin($username)) {
        return TRUE;
    }
 
    return isAllowed($username, $page);
}
 
?>

This uses a lot of lines of code, however it’s terribly straightforward and unimposing (we’re proudest of our code once it’s the smallest amount impressive). a lot of significantly, this approach reduces the quantity of context you want to continue with. for instance, as presently as you’ve determined whether or not the user is blacklisted, you'll be able to safely ignore it. this can be significantly useful once your logic is a lot of difficult.

Thursday, 10 August 2017

Know the Difference Between Comparison Operators

Know the Difference Between Comparison Operators

This is a decent tip, however it's missing a sensible example that demonstrates once a non-strict comparison will cause issues.

If you employ strpos() to see whether or not a substring exists at intervals a string (it returns FALSE if the substring isn't found), the results may be misleading:

<?php

$authors = 'Chris & Sean';

if (strpos($authors, 'Chris')) {
    echo 'Chris is an author.';
} else {
    echo 'Chris is not an author.';
}

?>

Because the substring Chris happens at the terribly starting of Chris &amp; Sean, strpos() properly returns zero, indicating the primary position within the string. as a result of the conditional statement treats this as a Boolean, it evaluates to FALSE, and also the condition fails. In alternative words, it's like Chris isn't associate degree author, but he is!


This can be corrected with a strict comparison:


<?php

if (strpos($authors, 'Chris') !== FALSE) {
    echo 'Chris is an author.';
} else {
    echo 'Chris is not an author.';
}


?>


Tuesday, 8 August 2017

How to Use an SQL Injection

How to Use an SQL Injection

This tip is just a link to a useful resource with no discussion on how to use it. Studying several permutations of a specific attack can be useful, but your time is spent better learning to protect against it. In addition, there is much more in Web application security than in SQL injection. XSS (Cross-Site Scripting) and CSRF (Cross-Site Request Forgeries), for example, are at least as common and at least as dangerous.We can provide a much needed context, but because we do not want to focus too much on an attack, we will first take a step back. Every developer should be familiar with good security practices, and applications should be designed with these practices in mind. A fundamental rule is to never trust the data you get from somewhere else. Another rule is to escape data before sending it to another location. Combined, these rules can be simplified to form a basic safety principle: filter inlet, exhaust outlet (FIEO).The root cause of SQL injection is a failure to exit the output. More specifically, it is when the distinction between the format of an SQL query and the data used by the SQL query is not carefully maintained. This is common in PHP applications that construct queries as follows:


<?php

$query = "SELECT *
          FROM   users
          WHERE  name = '{$_GET['name']}'";
         
?>


In this case, the value of $_GET[‘name’] is provided by another source, the user, but it is neither filtered nor escaped.

Escaping preserves data in a new context. The emphasis on escaping output is a reminder that data used outside of your Web app needs to be escaped, else it might be misinterpreted. By contrast, filtering ensures that data is valid before it’s used. The emphasis on filtering input is a reminder that data originating outside of your Web app needs to be filtered, because it cannot be trusted.

Assuming we’re using MySQL, the SQL injection vulnerability can be mitigated by escaping the name with mysql_real_escape_string(). If the name is also filtered, there is an additional layer of security. (Implementing multiple layers of security is called “defense in depth” and is a very good security practice.) The following example demonstrates filtering input and escaping output, with naming conventions used for code clarity:

<?php

// Initialize arrays for filtered and escaped data, respectively.
$clean = array();
$sql = array();

// Filter the name. (For simplicity, we require alphabetic names.)
if (ctype_alpha($_GET['name'])) {
    $clean['name'] = $_GET['name'];
} else {
    // The name is invalid. Do something here.
}

// Escape the name.
$sql['name'] = mysql_real_escape_string($clean['name']);

// Construct the query.
$query = "SELECT *
          FROM   users
          WHERE  name = '{$sql['name']}'";

?>

Although the use of naming conventions can help you keep up with what has and hasn’t been filtered, as well as what has and hasn’t been escaped, a much better approach is to use prepared statements. Luckily, with PDO, PHP developers have a universal API for data access that supports prepared statements, even if the underlying database does not.

Remember, SQL injection vulnerabilities exist when the distinction between the format of an SQL query and the data used by the SQL query is not carefully maintained. With prepared statements, you can push this responsibility to the database by providing the query format and data in distinct steps:

<?php

// Provide the query format.
$query = $db->prepare('SELECT *
                       FROM   users
                       WHERE  name = :name');

// Provide the query data and execute the query.
$query->execute(array('name' => $clean['name']));

?>

The PDO manual page provides more information and examples. Prepared statements offer the strongest protection against SQL injection.

Wednesday, 2 August 2017

How to Remove Date Number (Year & Month Figure) From Blogger Post URL

A large portion of the bloggers couldn't care less the date data on the blogspot post URL since they regard blog as a web journal. They expound on things or actualities which are substantial just at the season of composing. For instance political online journals, news sites and so on are legitimate just at a particular purpose of time and the time figure on the distributed URL bodes well. In any case, on the off chance that you are an expert blogger who composes certainties or instructional exercises which are legitimate for constantly, date figures on the post joins have neither rhyme nor reason. In the event that you are utilizing WordPress, you can pick the custom URL structure to maintain a strategic distance from Year/Month from connect yet in Blogspot you don't have such opportunity. Despite the fact that blogger does not give an approach to expel the date from the blog entry URL, you can pick a roundabout technique to stay away from them from your prevalent articles without influencing the present movement and backlink esteem. In this technique you should to make another page (not post) where there is no digit on the URL and glue the substance of your old mainstream post. At that point utilizing custom divert highlight of blogspot, you can divert the old post URL to the new URL which does not have date figure. In the event that you are searching for a straight strategy to dispose of digits from blogger distributed connections, as of now it doesn't have such a component.

The most effective method to Get Rid of Date from Blogspost Post Links 


To dispose of date figure from Old Popular blogger post URL, take after the means beneath.

  • Login to Blogger Account.
  • Click Dashboard 
  • Tap on Pages and make another page by Selecting clear page
How to Remove Date Number (Year & Month Figure) From Blogger Post URL


  • Duplicate the whole substance on the old prominent page (post which you would prefer not to demonstrate the information figure on URL) including all the meta labels and glue them on the recently made blogger page and distribute it. You should ensure the whole post content including labels (title, meta labels and so on) are replicated to the new page. 
  • Play out a custom divert from the old article URL to the recently made page. To do this take after the directions gave in the connection beneath. 



By following the means portrayed above we can effectively conceal the date figure(The Year and Month ) from the blogspot post joins. Similarly on the off chance that you need to show blogger posts backward request take after the means said in the connection underneath. 

Presently you can expel the date data from your mainstream blog entries. To make your blog more one of a kind you should include a redid Favicon for your blog. To do this tap on the connection underneath.

Monday, 31 July 2017

How To Embed YouTube Videos In WordPress

How To Embed YouTube Videos In WordPress

Do you realize that the quantity of individuals who devour video content has expanded fundamentally in the previous 2 years? This is to a great extent because of expanded cell phone utilization and enhanced web speeds.

In any case, despite the fact that it's simpler than any time in recent memory to install recordings from destinations like YouTube and Vimeo, numerous novice bloggers don't know about how to do it.
In this instructional exercise, I will demonstrate to you generally accepted methods to insert YouTube recordings in your WordPress articles.

Yet, before we get into that, we should comprehend why you ought to implant recordings into your blog entries.


Blog entries with recordings will: 


  • Give perusers a superior comprehension of the point.
  • Enable perusers to invest more energy in your site. 
  • Make your articles more media rich (and more streamlined for SEO). 

What's more, if it's your own YouTube video, you will: 


  • Get more perspectives, offers, and endorsers. 
  • Win more cash with AdSense for YouTube. 


There are numerous more points of interest, however thinking about these is a decent place to begin.

At whatever point I work with another creator or am counseling an organization on WordPress, a standout among the most well-known inquiries that I get asked is:

All things considered, in the event that you have never implanted a video into a blog entry earlier (don't get mistook for "installed" as it just means including a video from YouTube), this convenient guide will enable you to take in a couple of WordPress video traps.

Step by step instructions to Embed A YouTube Video in WordPress 


Including a YouTube video in a WordPress blog entry is simple.

You don't have to download the video and transfer it to WordPress in light of the fact that WordPress underpins auto-installing for YouTube and other well known video facilitating and social locales (Ted, Facebook, Vimeo, WordPress.tv, Instagram, and numerous others).

What auto-insert implies is that you should simply glue the URL of the video in plain content organization and WordPress will naturally put the video into the post.


Give me a chance to demonstrate to you best practices: 


  • Go to the YouTube video that you wish to install. 
  • Tap on Share and duplicate the URL.

How To Embed YouTube Videos In WordPress

Presently glue the URL into your WordPress post editorial manager (it ought not be hyperlinked). WordPress will naturally render the video and install it into the post. 

The YouTube video will now show up in your article. 


Including YouTube Video Using An Embed Code: 


When you need to include a YouTube video into your blog entry, the above technique is quickest. 

Notwithstanding, now and again you might need to add video to different parts of your blog, similar to the gadget territory where auto-implanting is impossible. 

Here you can utilize the (non-auto) install highlight of YouTube to get the insert code. 

  • Go to the YouTube video
  • Tap on Share
  • Tap on Embed
Here you can control the measure of the video player, you can debilitate indicating related recordings, and you can do a couple of different things like evacuating the YouTube control catch.

How To Embed YouTube Videos In WordPress


When you have arranged the settings, essentially glue the install code in the gadget segment you need to include. 

What's more, that is it! 

Implant YouTube Videos On WordPress 


Including video is helpful for enhancing your articles. Utilizing the auto-implant technique for WordPress to indicate YouTube video in an article is the quickest and least demanding strategy for doing this. 

You can take in somewhat more about inserting in WordPress by perusing this official help page. 

So simply ahead and implant a YouTube video in your next WordPress article!

Monday, 24 July 2017

10 HTML Tips and tricks for Beginners

Here are 10 HTML tips for beginners. In case you're quite recently beginning with building your Web pages, these methods ought to be exceptionally valuable to you!

1. Always close your HTML tags


When you type an opening HTML tag (e.g. <b>, <p>), always place the corresponding closing tag at the end. For example:

    <b>My favourite animals are horses and elephants.</b>
    <p>My favourite animals are horses and elephants.</p>
    <h2>My favourite animals are horses and elephants.</h2>

This will ensure that your HTML pages work suitably on all projects, and will keep any unusual issues occurring in your pages! This is particularly imperative with labels, for example, <div>, <span>, <table>, <tr> and <td>.

Some tags don't have a corresponding closing tag - just use these tags on their own. Examples include:

    The <br> tag, for creating line breaks
    The <img> tag, for inserting images


2. Style HTML using style sheets wherever possible


Templates will make your HTML coding life so considerably less demanding. No more <font> labels all over the place! You likewise oversee the way your pages look, and you can change their appearance just by altering one template record.

On the off chance that you haven't worked with templates yet, fly over to our CSS instructional exercises to go ahead!

3. Use an HTML validator

It's an incredible thought to run your Web pages through a HTML validator before you distribute them on your Web website. These projects will get potential issues, for example, missing shutting labels on tables, and utilizing labels that won't work appropriately on all programs. Bear in mind - in light of the fact that your page looks extraordinary in the program you're seeing it with doesn't mean it will take a shot at different programs!

HTML validators are additionally a decent approach to find out about the right approach to utilize HTML labels - you can gain from your missteps!

Some great free validators on the Web incorporate the W3C Markup Validation Service and the WDG HTML Validator. Numerous cutting edge web composing bundles have worked in HTML checkers as well.

4. Use HTML comments wisely


To make your HTML code clearer for you (and for others), you can add remarks to your code. These are scraps of code that are disregarded by Web programs, so they're valuable for including short notes and updates inside the code:


<!-- Navigation area: Highlight a menu item with the "hi" class -->

<div id="nav">
  <ul>
    <li><a href="/">Home</a></li>
    <li class="hi"><a href="/about/">About</a></li>
  </ul>
</div>

Learn how to write and use comments in our HTML Comments tutorial.

5. Embedding images in HTML


Directing accurately toward pictures utilizing the <img> tag is a typical hindrance for novices. Frequently your Web page will look extraordinary on your desktop PC, however when you transfer the page to your website, every one of the pictures are broken!

The issue isn't helped by some website page editors, which inaccurately put "document://" picture URLs as opposed to utilizing relative URLs!

Take after these basic standards to ensure your HTML pictures show up effectively without fail.

An) If conceivable, utilize relative URLs

Relative URLs are normally the best to utilize in light of the fact that they will work wherever the page and pictures are found, given they're generally in a similar place in respect to each other. For instance, if the picture is in an indistinguishable envelope from the Web page, utilize:


<img src="myphoto.jpg">

If the image is in an images folder at the same level as the Web page, use:


<img src="images/myphoto.jpg">

If the image is in an images folder at a level above the Web page, use:


<img src="../images/myphoto.jpg">

B) Alternatively, use URLs relative to the document root

On the off chance that you have every one of your pictures in a pictures organizer in the best level of your webpage (the report root or web root), you can reference pictures this way:


<img src="/images/myphoto.jpg">

This has the favorable position that you can move your Web page anyplace inside your webpage, and the pictures will at present show, if you keep the pictures in this worldwide pictures organizer.

The hindrance of this approach is that it will just work when your Web pages are being shown by means of a Web server (utilizing http://), not when seen specifically from your hard drive (utilizing record://).

C) Do not utilize total URLs!

In the event that at all conceivable, abstain from utilizing supreme URLs inside your site. A flat out URL is a URL that starts with http://or document://. Specifically, if the Web page on your hard drive contains a picture URL like this:


<img src="file:///C:|/mywebsite/images/myphoto.jpg">

it won't work when you transfer it to your Web server, as the img tag is straightforwardly referencing the document on your hard drive! Change the connection to a relative connection, for example,


<img src="myphoto.jpg">

or maybe:


<img src="../images/myphoto.jpg">

as described in Rule A above.

You can find more information on images in Web pages by reading our HTML Images tutorial!

6. Use widths and heights with HTML images


It's a good idea to specify the width and height of an image when using an <img> tag. For example:


<img src="myphoto.jpg" width="234" height="123">

The benefit of doing this is the Web program can design the page all the more rapidly as it is stacked, as it most likely is aware how to lay out the pictures before they've been downloaded. This implies your guests can begin surfing your page without waiting for every one of the pictures to show!

Most illustrations bundles (Photoshop, Paint Shop Pro, and so forth) enable you to see the width and tallness of a picture (in pixels) with the goal that you can opening the qualities into the <img> tag. You can likewise right-tap on the picture and select Properties (in Internet Explorer) or view the picture in a window all alone and read the width and stature in the title bar (in most different programs).

7. Non-breaking spaces in HTML


Here and there you need to keep certain words together with the goal that they're not part more than two lines. The best approach to do this is with a non-breaking space. In HTML the markup for a non-breaking space resembles this:


&nbsp;

For example, the following words will wrap if they fall at the end of a line:


<p>The quick brown fox</p>

while this example, which uses a non-breaking space, will keep the words "brown" and "fox" together even if they fall at the end of a line:


<p>The quick brown&nbsp;fox</p>

8. Use tables for tabular data, CSS for layout


Tables have by and large been used to lay out substance on the page; however this was never their normal use. They're really proposed to be used for demonstrating unbelievable data, (for instance, data from a spreadsheet, for example).

With the arranging limits of CSS, you can manufacture HTML pages that essentially contain the page substance, and use an alternate format to lay the substance out. Regardless of the way that it has a more outrageous desire to learn and adjust than tables-based outlines, CSS arranging is well worth learning as your resulting goals will be speedier stacking, less requesting to keep up and more accessible.

CSS situating can likewise do a considerable measure of cool traps that are hard with tables, and you can likewise change the whole look of your site just by changing your template (an awesome case of this is CSS Zen Garden).

In case you're new to CSS, look at our CSS articles.

9. Creating empty table cells


Sometimes you'll want to create table cells (<td>s) with nothing in them; for example, when a particular row doesn't have any data for one of its columns. Usually, the best way to create an empty table cell is with a non-breaking space, as follows:


<td>&nbsp;</td>

Don't just use <td></td> as this will cause your tables to appear rather strange on some browsers!

Find out more about tables in our HTML Tables tutorial.

10. The spacer GIF trick

For genuinely correct control over page organize, and if you haven't yet got the hang of CSS arranging, you can't beat the old spacer GIF trap. This incorporates using a 1 pixel x 1 pixel clear GIF, which will be imperceptible in your Web pages, and using the width and height credits to control the correct padding between page segments, for instance, pictures, substance and table cells. For example, the code:


<img src="one.gif" width="20" height="20" border="0">
<img src="space.gif" width="10" height="1" border="0">
<img src="two.gif" width="20" height="20" border="0">

will create a 10-pixel horizontal gap between the two images, one.gif and two.gif.

You can use spacer GIFs in table cells to "pad out" the table cell and make sure it doesn't shrink below a certain width or height. In this code example:


<td><img src="space.gif" width="1" height="20" border="0"></td>

the table cell will always be at least 20 pixels high.

It's easy to make a spacer GIF in your graphics package - create a new 1 pixel x 1 pixel image then save it as a GIF with a transparent background.

Obviously, nowadays you should be utilizing CSS situating to lay out your substance. :)

Ideally you've delighted in these HTML tips and discovered them valuable. Good fortunes with your site!

Thursday, 16 March 2017

CakePHP Interview Questions and Answers for fresher + experienced

Here we’ll discuss about some basic and advanced cakephp interview questions and answers which are most ask-able questions during interview session, These CakePHP questions and answers will help you to crack CakePHP technical interview round.

Question: What is Cakephp?

CakePHP is a free, open-source, MVC (Model, View, Controller) rapid development framework for PHP. It’s a framework which help you to make development fast and secure. CakePHP goal is to enable developers to work in a structured and rapid manner–without loss of flexibility.


Question: What is MVC in CakePHP?

Model view controller (MVC) is an architectural pattern used in software engineering.
Model: Handle database related functionality, manipulating database related query like add, edit , delete.
View: Design parts written here (HTML+PHP)
Controller: Business Logic goes here

Question: What Is The Name Of Cakephp Database Configuration File Name And Its Location?

FileName: database.php.default
Location: /app/config/database.php.default

Question: What is First cakphpe file loaded in application?

bootstrap.php


Question: What is the folder structure of CakePHP?

cakephp/
app/
Config/
Console/
Controller/
Lib/
  Locale/
  Model/
  Plugin/
  Test/
  tmp/
  Vendor/
  View/
  webroot/
    .htaccess
  index.php

 lib/
 plugins/
 vendors/
 .htaccess/
 index.php/
 README.md/

Question:What Is The Use Of Security.Salt And Security.CipherSeed In Cakephp?

The Security.salt is used for generating hashes.
The Security.cipherseed is used for encrypt/decrypt strings.

Question: What is default function for a controller?

function index() is default function in controller.


Question:Which function is executed before every action in the controller?

function beforeFilter()

Question: What Is Scaffolding In Cakephp?

Scaffolding is a technical way that allows a developer to define and create a basic application that can create, retrieve, update and delete objects.

Question: List some of the features in CakePHP?

* MVC architecture
* In-Built validations
* Caching
* Scaffolding
* CSRF protection via Security Component.
* Access Control Lists and Authentication and creating role management system.

Question: How to add Scaffolding in your application?

By adding $scaffold variable in the controller see following example.

<?php
class PostsController extends AppController {
    var $scaffold;
}
?>

Question: How To Include Components In Controller?


echo $this->here;

Question: How To Get Controller Name In CakePHP Views?

$this->request->params['controller']


Question: How To Get Controller Action Name In CakePHP Views?

$this->request->params['action']

Question: Which Methods Are Used To bind And Destroy Model Associations?

bindModel() : used to bind Model Associations
unbindModel() : used to destroy Model Associations

Question: What Is The Default Extension Of view files In Cakephp?

.ctp

Question: What is a Helper in CakePHP?

Helpers in CakePHP are associated with Presentation layers of application.Helpers mainly contain presentational logic which is available to share between many views, elements, or layouts

Question:What is a Behavior in CakePHP?

Behaviors in CakePHP are associated with Models.Behaviors are used to change the way models behaves and enforcing model to act as something else.

Question: What is the difference between Component, Helper, Behavior?

Component is a Controller extension, Helpers are View extensions, Behavior is a Model Extension.

Question: How to set variables for views?

$this->set('name','Cake PHP');

Question: How to set layout for controller

By adding $layout variable in the controller see following example.

<?php
class PostsController extends AppController {
    public $layout = 'layoutname';
}
?>

Setting layout for particular action,

layout = ‘layoutname’;
}
}
?>

Question: How to write, read and delete the Session in cakephp?

$this->Session->write(‘User.name’, ‘Rohit Kumar’);
$black = $this->Session->read(‘User.name’);
$this->Session->delete(‘User’);

Wednesday, 8 March 2017

How to import excel file into mysql using php

With the help of php we can easily import our excel or csv file data in our Mysql database.
So i am going to show you some methods doing this easily

How to import excel file into mysql using php

To import excel data into php-mysql records first create a table with required fields. Make database connection. Open excel file and read columns one by one and store in variables.


Method-1: Import excel data using php script

$handle = fopen("BooksList.csv", "r");
while (($data = fgetcsv($handle)) !== FALSE) {
$num = count($data);
$row;
echo "INSERT into importing(text,number)values('$data[0]','$data[1]')";
echo "<br>";
}


Method-2:

$handle = fopen("BooksList.csv", "r");
$fields=array('category','datatype','date','value');
$table='test';
$sql_query = "INSERT INTO $table(". implode(',',$fields) .") VALUES(";
while (($data = fgetcsv($handle)) !== FALSE) {
    foreach($data as $key=>$value) {
            $data[$key] = "'" . addslashes($value) . "'";
        }
           $rows[] = implode(",",$data);
  }
$sql_query .= implode("),(", $rows);
$sql_query .= ")";
echo $sql_query;


Method:3 Using third party library like php-excel-reader

Download form http://code.google.com/p/php-excel-reader/downloads/list

require_once 'Excel/reader.php'; 
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('CP1251');
$data->read('BooksList.xls');
for ($x = 2; $x<=count($data->sheets[0]["cells"]); $x++) {
    $name = $data->sheets[0]["cells"][$x][1];
    $extension = $data->sheets[0]["cells"][$x][2];
    $email = $data->sheets[0]["cells"][$x][3];
    $sql = "INSERT INTO mytable (name,extension,email) VALUES ('$name',$extension,'$email')";
    echo $sql."\n";
    echo "<br>";
 }

Hope this will help you to import your excel file into mysql db.
Thanks :)

Tuesday, 7 March 2017

How to upload file in cakephp without refersh page

Change image without refresh page in php and jquery, Upload file without refresh page in cakephp and jquery


Here we are going discuss about how to upload image or file without refresh page in cakephp and jquery.

Create controller in cakephp

ProfilesController.php

class ProfilesController extends AppController {
var $name = 'Profiles';
public $uses = array('Profile');
function changeprofilephoto() {
$profile_id = “14”; //
$path = "../../app/webroot/profilepic/";//set path
$valid_formats = array(".jpg", ".png", ".gif", ".bmp", ".jpeg");//
if($this->data)
{
$this->Profile->set( $this->data );
$name = $this->data["Profile"]['profile_pic']['name'];
$size = $this->data["Profile"]['profile_pic']['size'];
if(strlen($name))
{
$fileExt = substr(strrchr($name, '.'), 0);
if(in_array($fileExt,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = strtotime(date('Y-m-d H:i:s')).$fileExt;
$tmp = $this->data["Profile"]['profile_pic']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$this->Profile->set($this->data);
$this->Profile->id=$profile_id;
$this->Profile->saveField('uploadfoldername',$actual_image_name);
echo "<img src='/profilepic/".$actual_image_name."' class='preview'>";
$this->Session->write('suc','1');
$this->redirect($_SERVER['HTTP_REFERER']);
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
} else
echo "Please select image..!";
exit;
}
}
}


Create view file

Views/Profiles/changeprofilephoto.ctp

 <?php
echo $this->Html->script('jquery.min.js');
echo $this->Html->script('jquery.form.js');
?>

<script type="text/javascript" >
$(document).ready(function() {
$('#profile_pic').live('change', function(){
$("#preview").html('');
$("#preview").html('<img src="../img/loader.gif" alt="Uploading...."/>');//download loding image
$("#Profile").ajaxForm({
target: '#preview'
}).submit();
});
});
</script>
<style>
.preview
{
width:200px;
border:solid 1px #dedede;
padding:10px;
}
#preview
{
color:#cc0000;
font-size:12px
}
</style>
<div class="layout-popup f-left">
<?php
echo $this->Form->create('Profile',array('id'=>'Profile', 'controller'=>'Profiles','action'=>'changeprofilephoto', 'type'=>'file'));
?>


<!-- start id-form -->
<table class="frm-tbl" id="id-form" >
<tr>
<td colspan="2" class="align-t-r" >
<div class="f-left popup-title">Change profile image</div>
</td>
</tr>
<tr>
<td>Upload your image</td>
<td align="left" >
<!-- <input type="file" name="[Profile][photoimg]" id="profile_pic" /> -->
<?php echo $form->file('profile_pic', array('id'=>'profile_pic', "label" => false, "div"=>false, 'class'=>'styled-input-big'))?>
</td>
</tr>
<tr>
<td colspan="2">
<div id='preview'>
</div>
</td>
</tr>
</table>
<?php
echo $this->Form->end();
?>
</div>

Thanks cheers :)

Monday, 6 March 2017

How to create dynamic XML sitemap and submit to google web master for indexing


In this tutorial I’ll tell you very important method to generate dynamic xml sitemap for your website and how can we indexed all our dynamic url in google search.

Every body wants to create website now days and generate some traffic fast. So this is the trick for smart geeks, The below script is tested by me and worked great for me.

Let me tell you my experience, I had aprox 2 lakh dynamic urls which i created from my database rocords and i want to index all urls in google search, So i have created a php script which pull records from database and create a dynamic url for each records.

Suppose we have a books table with their name and auther.

ID NAME                 AUTHOR
1 Book Name-1 Book Author-1
2 Book Name-2 Book Author-2
3 Book Name-3 Book Author-3

My task is to index all my books url with their author name in google search, so that if anybody is looking for same books then he can find me in google search. Google automatically crawl urls but if you want fast result then give it try.

Create file sitemap.php and paste below script after that upload your sitemap.php file in your project root directory, Your sitemap url will be http://www.example.com/sitemap.php

You can make changes in below script according to your need this is just for demonstration purpose.

sitemap.php

<?php
  header('Content-type: application/xml');
  $baseurl = "http://example.com/books/";
  $hostname = "localhost";
$username = "username";
$password = "password";
$dbname = "booksdb";
$con = mysqli_connect($hostname, $username, $password, $dbname);

 function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

  $output = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
  $output .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
  echo $output;
?>
  <?php $query = "SELECT name, author, id FROM books WHERE  status=1 LIMIT 0, 50000";
    $result = mysqli_query($con, $query);
    $res = array();

    while($resultSet = mysqli_fetch_assoc($result)) { 

 if(!empty($resultSet['name'])) { ?>

<url>
  <loc><?php echo $baseurl.clean(trim($resultSet['name'])).'/'. clean(trim($resultSet['author'])).'/'.$resultSet['id']; ?></loc>
</url>
<?php }  } ?>
</urlset>

Now time to submit your xml sitemap to google web master.

Login into your google web master account and submit your site map.


How to create dynamic XML sitemap and submit to google web master for indexing


If you don’t know how to submit sitemap in google web master please follow this tutorial.




Sunday, 5 March 2017

How to make visible newly hosted websites in google search

How to make visible newly hosted websites in google search

Today we are going to discuss about a very important issue we face while we purchase and host our newly website and facing the issue with google search that why my website is not showing in google search.

SO here i am going to discuss about my experience what i do with my website to index in google search and got visibility in next 24-48 hours.


My steps to index my wordpress blog in google search super fast.

Note: Before doing below steps your website should be live.

Step-1: Create google webmaster account.

https://www.google.co.in/webmasters/

Steps-2: Create XML sitemap for your website and if you have normal html website there is lot’s of online XML sitemap generater tools are available on web like https://www.xml-sitemaps.com/

If your website in wordpress you can install some available plugins for generating XML sitemap for your website.

I used “Yoast” one of the best plugin for doing SEO of wordpress website. And generate XML Sitemap.

Step-3: Place your website XML sitemap on your web root directory using ftp if you used online XML sitemap generater tools.

Your sitemap map url look like www.yourWebsiteName.com/sitemap.xml
In case of wordpress YOAST it does this task automatically.

Step-4: Login into your google web master account and add your website by click on “ADD A PROPERTY” button and popup will open here add your website link and click on continue button.

Step-5: Now click on your added website you can add multiple website here. you’ll see the dashboard. Now click on crawl-> sitemaps in left panel and here you’ll see ADD/TEST SITEMAP button on top right corner.

Step-6: create robots.txt file and place this file in your website root directory via ftp.

What is robots.txt

robots.txt tells search engines which pages have to index and which are not.
You can read more about robots.txt from here http://www.robotstxt.org/

My robots.txt is

User-agent: *
Disallow: /wp-admin/

Where Disallow means i don’t want to crawl my admin panel in google search.

After creating robots.txt file place this file in your website root directory and check it
www.yourWebsiteName.com/robots.txt
Or use google web master robots.txt tester tool.

Now wait at least 24-48 hours your website will become start indexing in google search, You can check by this syntax in google search box

site:yourWebsiteName.com


Hope this tutorial will help you to index your website fast in google search.


Thursday, 2 March 2017

How to Quickly Extract Domain Name & it’s components from URL in PHP


In this quick tutorial, I am going to show you How to Quickly Extract Domain Name & it’s components from URL in PHP, In some cases of development you need to extract host name and it’s parameter individually, For parsing domain name you can simply use php parse_url function to extract domain name, It’ll not only return domain but also Parse the whole URL and return its components in associative array format.

See example below

$url =  'http://html-css-designing-tips.blogspot.com/page/?id=1&name=php';
var_dump(parse_url($url));

OutPut:

array(4) { ["scheme"]=> string(4) "http" ["host"]=> string(15) "html-css-designing-tips.blogspot.com" ["path"]=> string(13) "/page/" ["query"]=> string(15) "id=1&name=php" }

Extract Domain Name

$url =  'http://html-css-designing-tips.blogspot.com/page/?id=1&name=php';
$result = parse_url($url);
echo $result['host']; // output: html-css-designing-tips.blogspot.com


HTML APIs: What They Are And How To Design A Good One

As JavaScript developers, we regularly forget that not everybody has a similar data as USA. It’s referred to as the curse of knowledge:...