Thursday, September 25, 2014

PHP search word in string

preg_match — Perform a regular expression match.

Syntax :
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.

 <?php

/* The \b in the pattern indicates a word boundary, so only the distinct
* word "web" is matched, and not a word partial like "webbing" or "cobweb" */

if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}

//OUTPUT : A match was found.

if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}

//OUTPUT : A match was not  found.
?>

Special  thanks to buriedunderground .

Thursday, September 18, 2014

jquery ajax file upload php

This is HTML part:

<input id="sortpicture" type="file" name="sortpic" />

<button id="upload">Upload</button>

A PHP script is necessary to put the file uploaded to the server in the uploads directory. The jQuery ajax function directs the form data to the particular file that handles the upload.

$('#upload').on('click', function() {
    var file_data = $('#sortpicture').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file', file_data)
    alert(form_data);                             
    $.ajax({
                url: 'upload.php',
                dataType: 'text',
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,                         
                type: 'post',
                success: function(data){
                    alert(data); 
                }
     });

});

upload.php:

<?php

    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    }


?>

A couple things about the destination directory: 1) make sure you have the correct server path, and 2) make sure it's writeable.