vendredi 8 mai 2015

Need to fix PHP mailer error

I am implementing mail functionality by using PHP mailer. The code is not working on online but its working on local machine. On local machine code sends the mail successfully but on online website it is showing following error:

          SMTP -> ERROR: Failed to connect to server: ()
          SMTP Error: Could not connect to SMTP host. 

Code is:

        <?php
          include "classes/class.phpmailer.php"; // include the class name
            $mail1 = new PHPMailer(); // create a new object
            $mail1->IsSMTP(); // enable SMTP
            $mail1->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
            $mail1->SMTPAuth = true; // authentication enabled
            $mail1->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
            $mail1->Host = "smtp.gmail.com";
            $mail1->Port = 465; // or 587
            $mail1->IsHTML(true);
            $mail1->Username = "yourmail@gmail.com";
            $mail1->Password="password";        
            $mail1->SetFrom("yourmail@gmail.com");
            $mail1->Subject = "Working";
            $mail1->Body ="Hi, you got email";
            $mail1->AddAddress("yourmail2@gmail.com"); 
            $mail1->Send(); 
?>

browser shows only part of result list (php, mysql) [on hold]

I got a weired one today, not really a programming issue though.

I created this tool for company internal use and it's still growing. One part of it is a list of items who's stock is below some threshold. This list is also capable of showing all items without regard of the threshold, so can have say up to 2000 or so entries. All of those come out of a mysql DB and I'm handling things in php. The mentioned 2000 entries get formatted somewhat by Javascript (showing / hiding stuff etc.) in the browser - nothing really fancy.

It does work nicely... However, I just came across one computer that shows just under 10% of the requested list. I tried on three other computers in the office and all is good there. Just the one machine doesn't show it all. On one occasion I saw that it stopped displaying in the middle of an object, so just half of it was there. I cleaned everything like cookies and cache and everything the browser might save - no success. We're talking about one of those hybrid laptops with detachable screen / touchscreen.. It's a nicely quick and powerful machine, running photoshop and equally demanding apps...

Has anyone any idea???

UPDATE: since it seems my question is "unclear what you're asking", I will try to provide more technical data:

The page as described works fine on all in all 7 different machines running WIN7 and WIN8.1 in Chrome and Firefox (all up to date). Even IE11 has no problems :P

Javascript console throws no errors, php error log is clean

All cookies and cache have been emptied

As far as I can see the only difference is the hardware itself, though we're probably talking about the machine best equipped in our office.

I really don't know what else to specify.. I'd be glad to answer any questions that I couldn't think of so far..

Join entity properties in form

Is it possible to join two properties in an entity collection form field ?

So that the select input displays soemthing like this:

property1 - Property 2

So far, my builder field looks like this

->add('arrival', 'entity', array(
'class' => 'AOFVHFlyBundle:Airport',
'property' => 'name',
'query_builder' => function($repository) {
                                return $repository->createQueryBuilder('u')
                                    ->orderBy('u.name', 'ASC');
                            },
))

But obviously, it only returns the name property. My Airport Entity has a "name" property and a "Code" property, I would like to display something like [Airpot Name] - [Airport Code]

Is it possible?

How to get separate sums of last seven days from SQL with 0 value included

In my CRM system I have table with leads. I would like to make a chart to see how many leads were added in last 7 days. For that purpose I need to have separete sums for every day from last week.

My table called tab_leads comes with lead_id (integer) and lead_create_date (time stamp, format: 0000-00-00 00:00:00)

So I need something like:

  • Day 1 - 10
  • Day 2 - 0
  • Day 3 - 5
  • Day 4 - 0
  • Day 5 - 9
  • Day 6 - 15
  • Day 7 (today) - 0

At the moment I am usign this query:

SELECT
    DATE(lead_create_date) AS `Date`,
    COUNT(*) AS `Leads`
FROM
    tab_leads
WHERE
    lead_create_date >=  CURRENT_DATE - INTERVAL 6 DAY
GROUP BY
    DATE(lead_create_date)

But the problem is, that if in any of those days we do not hava any data (ex. weekend) I am getting less than 7 sums. Ex:

  • Day 1 - 10
  • Day 2 - 5
  • Day 3 - 9
  • Day 4 - 15

For drawing a chart I need to have always seven sums, even with 0 value. How to do that in MySQL or MySQL + PHP?

..UPDATE: I am just trying to create SQL Fiddle withous success. Sample data:

CREATE TABLE tab_leads (
  `lead_id` int,
  `lead_create_date` timestamp
) ENGINE=InnoDB 

INSERT INTO tab_leads
  (`lead_id`, `lead_create_date`) 
VALUES
(0, '2015-05-02 05:30:40'),
(1, '2015-05-02 00:00:00'),
(2, '2015-05-03 00:00:00'),
(3, '2015-05-03 00:00:00'),
(4, '2015-05-05 00:00:00'),
(5, '2015-05-06 00:00:00'),
(6, '2015-05-07 00:00:00'),
(7, '2015-05-08 00:00:00'),
(8, '2015-05-08 00:00:00')
;

including a file is failing in php

I ma having this code

<?php include ("commentsdisplay.php?postid=".$activity[$i]['PostId']."&category=".$activity[$i]['Category']) ; ?>

but php is generating a fatal error. Is this syntax wrong?

 Warning: include(commentsdisplay.php?postid=17&amp;category=article): 
 failed to open stream: No error in C:\wamp\www\Spiralblog\home.php on line  
 79
 Call Stack
 #  Time    Memory  Function    Location
 1  0.0015  253760  {main}( )   ..\home.php:0

Setting access rule in Yii for action with the same name from different controller?

I searched over the internet and I found nothing. I centralized all of the access rule from all controller in the main Controller.php from components. This is my code:

public function accessRules() {

        $controllers = array(' '); $actions = array('index');
        if (Yii::app()->user->getState("isAdmin") == true){ 
            array_push($controllers, 'controllerName','ModuleName/ControllerName');
            array_push($actions, 'create');
        }
        if (Yii::app()->user->getState('isNormalUser') == true){
            array_push($controllers, 'controllerName2');
        }
        if (Yii::app()->user->getState("isAdmin") == false && Yii::app()->user->getState("isNormalUser") == false){
            return array(
                array('deny', // deny all users
                    'users' => array('*'),
                ),
            );
        }else{ 
            $controllers = array_unique($controllers); //remove duplicates
            $actions = array_unique($actions);//remove duplicates
            return array(
                array('allow',
                    'controllers'=> $controllers,
                    'actions'    => $actions,
                ),
                array('deny', // deny all users
                    'users' => array('*'),
                ),
            );
        }
    }

My problem is: In my module if I have a controller(C1) with a function named f1 and another controller (C2) with the same function name f1 and i want to give access only to C1 with f1? How can I do that? I observed that i can make the difference between modules with the same controller name giving the format

ModuleName/ModuleController Is it smth similar to actions ? Thx

Using name attribute for Propel joins

I lately started to use Propel (PHP ORM) and I love it but I have one quite annoying issue I can't resolve even with a lot of trying. I use reverse engineering to create my schema.xml, which works great until it comes to joins. Sadly for all my foreign keys the reverse engineering only adds the name and not the phpName attribute. Whatever I try to use this name attribute for a join I fail. After I added the phpName attribute manually (and then rebuilding the models of course) the join works fine as it should.

Here is the snippet of the foreign key in the schema.xml (without the phpName attribute obviously):

<foreign-key foreignTable="users" name="messages_ibfk_1">
  <reference local="creating_user_id" foreign="id"/>
</foreign-key>

And here is the code for my join (which doesn't work):

$messages = MessagesQuery::create()->joinWith('messages_ibfk_1')->findByRecipientId($id);

I tried all kinds of variations for the joinWith value but none worked. On top of the schema this setting is active: defaultPhpNamingMethod="underscore"

The error propel pulls out is: Unknown relation messages_ibfk_1 on the Messages table.

If I add the phpName attribut with the value Author the join works fine like that:

$messages = MessagesQuery::create()->joinWith('Author')->findByRecipientId($id);

As I have a lot of foreign keys and I want minimum/none manual work the question is: How do I resolve this without adding all the phpName attributes manually. Either I find a way to access the foreign keys with their regular name attribute or there is a way to tell propel to set up the phpName attribute while building the models?

I hope someone has an idea, would be a great help! :)

Laravel 5 Routing Issue

I am new to laravel. My problem is that If i try to access a route Like this : http://localhost/shivani/public/sitehome , It works perfectly fine.

but If I try to access it like this : localhost/shivani/public/sitehome/

It redirects to http://localhost/sitehome and says "Object not found".

Please help.

cakephp assocations issue in 2x

I have two tables

  • messages

  • users

users has roles Doctor and user.

messages has doc_id & user_id.

How do I make an association, so that it returns me both data doc_id & user_id from users.

Find array with a specific data string and return another data string it has

I have this JSON(Cant change it) every array in bbData contains["Username","ID","Age"]

{"bbData":[
 ["Peter","/id/5423","42.4"],
 ["Bob","/id/5355","32.1"],
 ["Dolan","/id/5113","22.6"]
]]}

I know an id for a user, let's say "/id/5423". How can i then make PHP find the array with that id and return the age data which lays in the same array?

jquery post call not working with slash at end of the url

example url:
Target is not to show .php extension, but content stop working when page/url is open with a slash at the end.
http://ift.tt/1F9Oyt6 - form is working with this url
http://ift.tt/1EnOLSI - form is not working with this url

Folder & files:
|
| /js/custom.js
| /manager/create.php
| /manager/creategetpostdata.php
| /manager/.htaccess

Content on custom.js

$(window).load(function() {
    // get post code data
    $('.contentfinder').on('keyup', function(e){
        var xyz = $(this).closest('.contentRow');
        //alert( "success" );
        $.post("../manager/creategetpostdata.php", xyz.find('.contentfinder').serialize(),  function(response) {
            //alert( "success" );
            xyz.children('.showPostData').html(response);
            xyz.children('.showPostData').show();
        });

    });

});

input form on create.php file:

                    <div class="contentRow">
                        <input type="text" name="inputdata" class="form-control contentfinder" placeholder="" />
                        <div class="showPostData"></div>
                    </div>

content on creategetpostdata.php

<?php echo 'hello, what the hell wrong with you. just show content now!'; ?>

content on .htaccess file

Options +FollowSymLinks -MultiViews
RewriteEngine On

RewriteCond %{THE_REQUEST} \s/+(.+?)\.php\?([^=]+)=([^\s&]+) [NC]
RewriteRule ^ /%1/%2/%3? [R=302,L,NE]

RewriteCond %{THE_REQUEST} \s/+(.+?)\.php\s [NC]
RewriteRule ^ /%1 [R=302,L,NE]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

any help? thanks in advance.

.htaccess: rewrite rules not working as I'd like

Sorry in advance for non technical terms; but keep in mind I really tried a lot to find a solution before posting here.

Under webroot folder i've 2 websites; these are the entry points:

/frontend/web/index.php
/backend/web/index.php

My goal is

  • Access /frontend/web/index.php opening http://domain.tld
  • Access /backend/web/index.php opening http://ift.tt/1uW9qfP

This is my webroot/.htaccess

  RewriteCond %{REQUEST_URI} !^something
  RewriteRule ^(.*)$ frontend/web/$1 [L] 
  RewriteRule ^(.*)/something$ backend/web/$1 [L] 

In this way, domain.tld/ is opening /frontend/web (GOOD), but also domain.tld/something is pointing to frontend/web/index.php instead of backend/web/index.php

How can i add Dynamic Json data into a Mysql Database.

How can i add JSON Data into a Database? i have a script there is generating automatic updated JSON Data. i read in a book that i should use a methode called

JSON_decode 

I Think i should have to do something like, put The value into The tables for each value. Then try to use The methode JSON_decode and then make a loop foreach. but i am not sure about this. what is the best way, and can you tell me what to do in my case or maby show a example?

Here is the data located:

http://ift.tt/1H3Ee3g

The current script:

<?php
require_once ('simple_html_dom.php');

$html = @file_get_html('http://csgolounge.com/');
$output = array();

if(!$html) exit(json_encode(array("error" => "Unable to connect to CSGOLounge")));

// Source: http://ift.tt/1cv6y4s
function strip_tags_content($text, $tags = '', $invert = FALSE) {
preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags);
$tags = array_unique($tags[1]);

if(is_array($tags) AND count($tags) > 0) {
    if($invert == FALSE)
        return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text);
    else
        return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text);
} elseif($invert == FALSE) {
    return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
}

return $text;
}

foreach($html->find('.matchmain') as $match) {
$when = $match->find('.whenm')[0];
$status = trim($when->find('span')[0]->plaintext) == "LIVE" ? true : false;
$event = $match->find('.eventm')[0]->plaintext;
$time = trim(strip_tags_content($when->innertext));
$id = substr($match->find('a')[0]->href, 8);
    $additional = substr(trim($when->find('span')[$status ? 1 : 0]->plaintext), 4);
$result;

$output[$id]["live"] = $status;
$output[$id]["time"] = $time;
$output[$id]["event"] = $event;

foreach($match->find('.teamtext') as $key => $team) {
    $output[$id]["teams"][$key] = array(
        "name" => $team->find('b')[0]->plaintext,
        "percent" => $team->find('i')[0]->plaintext
    );

    if(@$team->parent()->find('img')[0])
        $result = array("status" => "won", "team" => $key);
    }

if($additional)
    $result = $additional;

if(isset($result))
    $output[$id]["result"] = $result;
}

echo json_encode($output);

store order data (to be exact ID) in different rows in mysql

I want to follow the suggestions of this posts, but I have a problem of understanding: How to store complex product/order data in MySQL?

My php code looks like this:

if(isset ($_POST['submit'])) {
$payment = $_POST['payment'];
$shipping = $_POST['shipping'];
$order_person = $_POST['order_person'];
$total = $_POST['total'];
$status = $_POST['status'];
$q = "INSERT INTO orders(payment,shipping, order_person, total, status) VALUE(:payment, :shipping, :order_person, :total, :status)";
$query = $con->prepare($q);
$results = $query->execute(array(
":payment" => $payment,
":total" => $total,
":shipping" => $shipping,
":status" => $status,
":order_person" => $order_person
));
}

In my mysql database I have a row named "orders" where I have the fields:

  • orderID
  • date
  • order_person
  • shipping
  • payment
  • total
  • status

The order ID is generated with AUTO_INCREMENT. I created a second row named "order_details". Here I want to store my product details.

My problem is: I do not understand how exactly do I store the order ID into my row "orders" and also into "order details". I would be grateful about a detailed explanation. I am so confused. Thank you very much!

Read external file match specific string in first column and return respective string of second column in php

I have two text files, csvurl.txt and tickerMaster.txt
tickerMaster.txt
H0001

Remarks: No ""H0002"" in tickerMaster.txt

csvurl.txt
H0001, URL1
H0002, URL2

I would like to read the entries in tickerMaster.txt one by one, say H0001, H0002...
and createURL by matching the data in csvurl.txt. So I am using following code...

<?php
  function createURL($ticker){
    $file = 'csvurl.txt';
    header('Content-Type: text/plain');
    $contents = file_get_contents($file);
    $sep = ',';
    $pattern = preg_quote($searchfor, '/');
    $searchfor = $ticker;
    $pattern = "/^($searchfor\w+)$sep.*$/m";
    if (preg_match_all($pattern, $contents, $matches)){
    echo implode($matches[0])."\n";
    }
    else{
        echo "No matches found";
    }
}

function main(){
$mainTickerFile = fopen("tickerMaster.txt", "r");
while(!feof($mainTickerFile)){
    $companyTicker = fgets($mainTickerFile);
    $companyTicker = trim($companyTicker);
    $fileURL = createURL($companyTicker);
    }
}
main()
?>

However, what I got is the whole line on the information in csvurl.txt for example:
No matches found H0001, URL1 H0002, URL2

My desired output is just:
URL1

Actually, I am looking for the function like vlookup in excel, but I cant search any solution for this kind of matching. Thanks.

PHP - return to another page using header

I was trying to update data in database using oop php but after I call function update I should return the user to view all page , so i used header but then whenever i try to view update page, it views view all page. what should i do?

<body>

    <form  method='POST'>
<table>
<tr>
<td>id</td>
<td>
<input type='text' name='id' value='' ></td>
</tr>
<tr>
<td>price</td>
<td>
<input type='text' name='price' value='' ></td>
</tr>
<tr>
<td></td>
<td>
<input type='submit' name='commit' value='Submit'>
</td>
</tr>

</table>
</form> 
</body>
</html>

<?php
require_once ('database.php');
require_once ('admin.php');
$object= new admin();
if (isset($_POST['commit'])) {
$id    = $object->clean($_POST['id']);
$price = $object->clean($_POST['price']);
$object->update_sport($id ,$price);
}
header("C:\wamp\www\omnia\viewsports.php");

How to exclude folder(s) from ZIP file generation using php?

I found a great solution on how to ZIP folders and files on my server, but how do I make the script exclude the folder /archiv and all of its subfolders?

$backup_file = $_SERVER['DOCUMENT_ROOT'].'/archiv/system/system_' . date("Y-m-d-H-i-s") . '.zip';

$zip = new ZipArchive();
$zip->open($backup_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);

$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($_SERVER['DOCUMENT_ROOT']),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    if($file == 'archiv'){
        continue;
    }else{
        // Skip directories (they would be added automatically)
        if (!$file->isDir()){
            $filePath = $file->getRealPath();
            $relativePath = substr($filePath, strlen($rootPath) + 1);
            $zip->addFile($filePath, $relativePath);
        }
    }
}

$zip->close();

Many thanks for any help!

Implement partial bid concept codeigniter [on hold]

I want to implement partial bid concept in reverse auction in php codeigniter. What should be screen and how its work?

Getting values of all checked checkboxes in PHP and put them in an array

I'm creating a CMS in which I have an overview of pages. I want the user to be able to mass delete these pages and so I have created a form in which each page has a checkbox with the pages database ID as value and name:

<input class="mass-delete-check" type="checkbox" name="<?=$page["id"]?>" value="<?=$page["id"]?>" id="<?=$page["id"]?>">

Now when I submit this form I need to get the values of the checkboxes that are actually checked and put them in an array I can go through to delete them. The thing here is that I will have to get checkbox values based on if they are checked and not on their name because I can't know all names.

Does anyone have a solution to this?

Laravel 5 redirect loop error

I trying to make a login and admin script, the problem is that i have a redirect loop i dont know why. I want the login users and can be in the "/" path not "/home". If change return new RedirectResponse(url('/')); to return new RedirectResponse(url('/anotherpage')); works but i want to be "/". I cant find the solution.

Routes:

    Route::get('/', [
        'as' => 'home', 'uses' => 'HomeController@index'
    ]);


    // Tutorials Routes

    Route::get('/tutorials', 'HomeController@tutorials');
    Route::get('/tutorials/{category?}', 'HomeController@tutorialsCategory');
    Route::get('/tutorials/{category?}/{lesson?}', 'HomeController@tutorialsLesson');

    // Courses and Series Routes

    Route::get('/courses-and-series', 'HomeController@coursesandseries');

    // Admin Routes

    Route::group(['middleware' => 'App\Http\Middleware\AdminMiddleware'],                 function()
    {
        Route::get('/admin', function()
        {
            return 'Is admin';
        });
    });

    Route::controllers([
        'auth' => 'Auth\AuthController',
        'password' => 'Auth\PasswordController',
    ]);

Admin middleware:

    public function handle($request, Closure $next)
    {
        if (Auth::user()->type != 'Admin')
        {
            return abort(404);
        }

        return $next($request);
    }

RedirectIfAuthenticated:

    public function handle($request, Closure $next)
    {
        if ($this->auth->check())
        {
            return new RedirectResponse(url('/'));
        }

        return $next($request);
    }

Thanks!

No credit memo button available if the end price if 0

I'm trying to convert a magento instance from a b2c platform to a b2b platform.

I'm having issues with a particular part of magento.

When an order with the final price of 0 is issued, I have no credit memo button available.

The order is issued from the back-end and in the Payment Method Field the massage is

No payment Methods.

This is actually logical because there is no amount of payment to be refunded.

But the thing is that the product, although it does not cost the customer anything to buy, it actually leaves my stock.

The first question is, if this is a normal behavior for magento of is something broken on my end? The end goal is not to refund my customer's money but to get the product in my stock again.

If this in normal for a magento instance, is there any other way to force a payment method when the order is issued so that the credit memo button will be available and later down the refund process, will let me get the product back in stock?

Change data source dynamically - CakePHP

I want to allow a user to pass in database config data in from the front-end and with that data i want to try switch to that datasource.

I am using CakePHP 2.3.

Getting string results to INSERT into database from foreach loop

I am creating a checkout system and I am trying to figure out how I am going to insert the string from the results of my foreach loop that displays which products were chosen, the quantity, and and pertinent data about them.

The way I have the shipping information in place is I validate it and if it passes, I allow it to be inserted once the order is placed. Like this:

if(Input::exists()) {
        $validate = new Validate();
        $validation = $validate->check($_POST, array(
            'fullname' => array(
                'required' => true,
                'min' => 2,
                'max' => 50
            )

if($validation->passed()) {
            if(isset($_POST['create'])){ 
                $fullname = trim( $_POST['customer_name'] );

<div class="field">
                                        <label class="paddingleft" for="fullname">Full Name</label>
                                    <div class="center"><input type="text"  class="biginputbarinline" name="fullname" value="<?php echo escape(Input::get('firstname')); ?>" required></div>
                                    </div>

I am wanting to INSERT all of the data on my page at once and not do seperate INSERT submissions. I have the shipping info, payment info and Order confirmation all on the same page. I will not be storing the payment info in my database. So that is irrelevant to this question. The Order confirmation is where the order will be displayed and I want that info to send in to my database with my shipping info.

The part I am really confused with is how to INSERT the actual string this foreach loop displays. This is how I have the Order confirmation section as of now..

<div class="checkoutconfirmationcontainer">
                                            <?php foreach($_SESSION['shopping_cart'] as $id => $product) {
                                                    $product_id = $product['product_id'];
                                        ?>
                                        <span class="tealmedium"><?php echo $product['quantity'] . " - "  . $products[$product_id]['name'] . $message; ?></span><br><br><br>


                                            <div class="floatleft"><div class="smallerimgcontainer">
                                                    <?php
                                                        $result = mysqli_query($con,"SELECT * FROM products");
                                                        if($row = mysqli_fetch_array($result)) {
                                                            $products[$row['product_id']] = $row;

                                                        if($row['image'] == ""){
                                                                echo "<img class='sizedimg' src='/productpics/coming_soon.png' alt='Coming Soon'>";
                                                        } else {
                                                                echo "<img class='sizedimg' src='/productpics/".$row['img']."' alt='Product Picture'>";
                                                        }
                                                        echo "<br><br><br><br>";
                                                        }
                                                    ?>
                                            </div></div>
                                            <div class="checkoutitemsummary">
                                                <?php echo "<a href='./viewProduct.php?view_product=$id'>" . $product['name'];?><?php echo $products[$product_id]['name']; ?> </a>
                                                    <p><span class="redprice"><?php echo '$' . $products[$product_id]['price'] . "<br />"; }?></span></p>
                                            </div>

How could I get the foreach loop produced string to be inserted into my database?

Some misunderstanding with pagination

I trying to make pagination from one post to next post in the single blog post. But seems I don't understand it very well. The problem is that when I open article with ID-1 and I click on next button I get blank/empty page.

This is the post page which get the ID of the chosen post in blog.php. This is what I have so far. Any suggestions?

<?php
     // include database connection
     require_once 'database.inc.php';
     $pdo = Database::connect();
       if(isset($_GET['post_id']) && is_numeric($_GET['post_id'])){
                $post_id = $_GET['post_id'];
     // page is the current page, if there's nothing set, default is page 1
     $page = isset($_GET['page']) ? $_GET['page'] : 1;

     // set records or rows of data per page
     $recordsPerPage = 1;

     // calculate for the query LIMIT clause
     $fromRecordNum = ($recordsPerPage * $page) - $recordsPerPage;

     // select all data
     $query = "SELECT * FROM posts WHERE post_id = $post_id LIMIT {$fromRecordNum}, {$recordsPerPage}";

     $stmt = $pdo->prepare( $query );
     $stmt->execute();

     //this is how to get number of rows returned
     $num = $stmt->rowCount();

     //check if more than 0 record found
     if($num>0){                           
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){               

                     echo ' 
                           // post body ';     
                }
    }                                                 

         // *************** <PAGING_SECTION> ***************

             // ***** for 'first' and 'previous' pages
             if($page>1){       
                 // ********** show the previous page
                 $prev_page = $page - 1;
                 echo "
                <a href='" . $_SERVER['PHP_SELF'] . "?page={$prev_page}'>
                    <div class='prev-btn control-nav text-left'>
                        <h5>Previous Post</h5>
                    </div>
                </a>";     
             }
             // find out total pages
             $query = "SELECT COUNT(*) as total_rows FROM posts";
             $stmt = $pdo->prepare( $query );
             $stmt->execute();

             $row = $stmt->fetch(PDO::FETCH_ASSOC);
             $total_rows = $row['total_rows'];

             $total_pages = ceil($total_rows / $recordsPerPage);

             if($page<$total_pages){
                 // ********** show the next page
                 $next_page = $page + 1;
                 echo "<a href='" . $_SERVER['PHP_SELF'] . "?page={$next_page}'>
                    <div class='next-btn control-nav text-right'>
                        <h5>Next Post</h5>
                    </div>
                </a>";
             }
}
?>                       

How to show dirty values when debguging entity

I need use _get so I just did it at User entity just for test:

protected function _getName($name)
{
    return $name . ' - FOOBAR';
}

So in the view I did Debug($user), and heres the result:

'properties' => [
        'id' => (int) 32,
        'name' => 'Daniel Pedro', //<- Clean Value
        'email' => 'daniel@gmail.com',
    ],
    'dirty' => [],
    'original' => [],
    'virtual' => [],
    'errors' => [],

As you can notice the property name is with the original value Daniel Pedro, so I thought I did something wrong at _getName but when I look at the input at form the value was Daniel Pedro - FOOBAR.

My question is, how can I show the mutated values at Debug?

Inserting into a database via Android

I have the following problem:

I have set up a database using XAMPP and I've written 4 PHP-Scripts to insert and show the content of it. That works fine by now. The database has two columns body and address both of type text and it is there to write some sms data in it.

Now I want to insert from my Android app. To achieve this, I have written those few lines of code inside my app:

        //the sms to send
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("body","testbody"));
        nameValuePairs.add(new BasicNameValuePair("address", "testaddress"));

        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://ift.tt/1IodHzf");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
        }

Now the problem is - if the code above has no fault - how can I pass those BasicNameValuePairs into my PHP variables? My PHP script for this looks like the following:

<?php

//This is my problem: How can I write the values from inside my android application in to those variables here? :(
//This does not work
$body = $_REQUEST['body'];
$address = $_REQUEST['address'];

//Connecting to database
require_once('mysqli_connect.php');

//Defining the query for inserting
$query = "INSERT INTO sms (body, address) VALUES (?,?)";

//Preparing the statement to be executed
$stmt = mysqli_prepare($dbc, $query);

//Binding the parameters to the statement
mysqli_stmt_bind_param($stmt, "ss", $body, $address);

//Executing the statement
mysqli_stmt_execute($stmt);

?>

I can run the app on the emulator, but nothing happens, so I get no new entry in my database. Can someone explain to me, how I get this right in PHP? Or is there a fault in the android code?

rikojir

Symfony security.yml Unrecognized options "check_path, login_path, provider" under "security.firewalls.secured_area.ldapsecure"

I'm getting this error when trying to configure a custom authentication provider using Symfony 2.6.

Unrecognized options "check_path, login_path, provider" under "security.firewalls.secured_area.ldapsecure"

Here's my security.yml

security:
  encoders:
    Symfony\Component\Security\Core\User\User: plaintext
  role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
  providers:
    ldap_provider:
      id: ldap.security.user.provider
  firewalls:
    login_firewall:
      pattern: ^/app/login$
      anonymous: ~
    secured_area:
      pattern: ^/
      ldapsecure:
        check_path: app_security_login_check
        login_path: app_security_login_path
        provider: ldap_provider
    dev:
      pattern:  ^/(_(profiler|wdt)|css|images|js)/
      security: false
  access_control:
    - { path: ^/app/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/, roles: ROLE_USER }

The ldapsecure "factory" class exists and if I change the getKey() method to return someone else, it breaks differently, so the ldapsecure is being recognized. But I can't see why it's not accepting check_path, login_path or provider. If I change ldapsecure to form_login, I don't get the error, it's just not using my authentication provider.

So I feel like I'm missing something, but don't know where to look at this point.

Laravel 5: After login the user is was redirected to /home. How to change that?

I have created my own root page (/) as well as my register page (/cadastrar). My next step was to allow the user to login and update their information. For that I just used laravel's login page (/auth/login). It works fine and when I login I get redirected to /home. At this point my problem arises: I can not go to any other page (/) (/cadastrar). I always get redirected back to /home.

I did not change any configuration regarding login or redirections so what could be wrong and how to fix it?

EDIT: At my (/) I have a Sign in link. When I click, I go to (/auth/login). I put my email and password, press login and it redirects me to (/home) saying that I'm logged in. Now I want to go to (/) or any other page, but it always redirect me to (/home). Thats my problem. My plan was to let the users update their information only if they are logged in, but now I can't go anywhere.

how to identify the web server name of remote host

According to this solution link it shows how to get the web server name for a local web server but how to do the same for a remote server by URL ?

i.e. $_SERVER['software'] returns name like Apache/2.2.21 (Win32) PHP/5.3.10

how can I apply this solution for a remote server - example here: http://ift.tt/1hCl4IQ

I want to be able to specify the name of the remote server i.e. $url = 'www.domain.com'; - I want to get the web server name as shown above for host name specified in $url

I am only interested in the web server name

how to redirect external requests?

I want to configure Apache using .htaccess file so that any request from external web page should be redirected to splash.html but internal request should be not redirected for example :

if i'm on www.test.com and I clicked a link that leads to www.mysite.com it should redirect to http://ift.tt/1JTGqOs but if I request www.mysite.com from wwww.mysite/com/products it should take me to http://ift.tt/1dBYZ4T

$_POST spaces spaces are converted to \n in array;

Sending form with ajax and php I turn the $_POST in array, and then append do with it, however, the whitespace are converted to \n, where is my mistake?

Updating the page, the \n disappear, but with not append ...

jQuery

$.ajax({
  type: "POST",
  url: "send.php",
  data: dataString,
  dataType: 'json',
  cache: false,
  success: function(mydata) {
  $(divtoload).append('<span>'"mydata.text"'</span>');
  }

PHP

//  array
$my = array(

 'text'=>$text

);

$myJSON = json_encode($my);

echo($myJSON);

HTML OUTPUT

test\n

php regex extract matches where tag contain a specific word

I have the following string:

<product><name>Tea</name><price>12</price></product>
<product><name>black coffee</name><price>23</price></product>
<product><name>cheap black-coffee</name><price>44</price></product>

I would like to grab all products where "coffee" or "coffee black" occurs.

I tried with the following code:

preg_match_all('/<product>(.*?)(black coffee|black-coffee)(.*?)<\/product>/is', $string, $result);

But that code merges two of the products in the array. As you can tell, I am not at all familiar with regex.

k2 item.php extra fields Display default image if left blank

I am currently buiding a site in joomla and using k2 to manage the content I am creating a template in k2, for item.php. I wish to use an extra field to display a header image on the item.

I have managed to Implement this using the following

Toward top of document

<?php  
$extrafields = array();
foreach($this->item->extra_fields as $item)
{    
$extrafields[$item->id] = $item->value;
}   
?>

Positioned where required

      <?php if($extrafields[2]!=''):?> <!-- if filled in, then call data -->
<?php echo $extrafields[2];?> <!-- actual data call -->
<?php endif; ?>

I have succeeded in that If i fill in the extra field i get my header image exactly where i want it, My problem is if i leave the field blank it is meant to revert to a default image, but insted i get the following error

Notice: Undefined offset: 2 in (URL)\item.php on line 194

I am not sure where I have gone wrong. I'm sure I need an or statement but its Friday and my brain is fried. any help much appreciated!

Iameki

imagewebp (php) creates corrupted webp files

Recently I've been fiddling with the WebP image format. I use php 5.5.12 for this, with the gd library installed (gd 2.1.0 / webp supported). I noticed that for some reason, PHP creates corrupted webp-images. The code I used is the following:

$im= imagecreatefromjpeg("test_img.jpg");
$succes = imagewebp($im, "test_img.webp");
if ($im !== false && $succes == true) {
    echo "Succes.";
}

I fail to grasp why the webp image written to the filesystem by this php script is corrupt. For your convenience, I have attached one of the test images. After processing, its associated webp image is indeed a corrupt image on my system. I'd appreciate your input on this, as I have no idea why this does not work properly.

Initially, I hoped that the problem might be in the stuffing of a wrong byte somewhere in the file, but comparing a proper webp image rendered from this JPEG file to the faulty one, I noticed such stark dissimilarities that I doubt the problem is due to a faulty stuffed byte.

Image: http://ift.tt/1AKvo5M (JPEG)

unable to scrape images and full text , only featured images is scrapped

unable to scrape images and full text , only only title and featured image is inserted.how can i correct this error . save this code as grab.php and run

check it on my server http://ift.tt/1JTGnSMhttp://ift.tt/1AKvnPp

and you can see the results here

http://ift.tt/1JTGoWT

my scrapper uploads the featurued image of each post on my server but if the images that are includedd inside posts doesn't upload them on my site to wp uploads folder

    <head profile="http://gmpg.org/xfn/11">  

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />  
    <meta charset="UTF-8">  

    <?php  
    header('Content-Type: text/html; charset=utf-8');  

    //RUN IT AS grab.php?   c=215&p=1&site=diaforetiko.gr&s=http://ift.tt/1AKvo5E  
    //Where c= Your cat id  
    //Where p= number of posts to grab  
    //Where site= Source site  
    //Where s= Source Sites full category path  


    $source = $_GET['s'];  
    $n = $_GET['p'];  
    $site = $_GET['site'];  
    $mcat = $_GET['c'];  
    $cat = $_GET['c'];  

    require( dirname(__FILE__) . '/../wp-load.php' );  



    //OTHERSIDE SCRAPPER  
    if ($site == "otherside.gr")  
    {  



        $curl = curl_init();  
        curl_setopt($curl, CURLOPT_URL, $source);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl1, CURLOPT_POST, true);
        curl_setopt($curl1, CURLOPT_POSTFIELDS, $post);     
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION,true);
        $result = curl_exec($curl); curl_close($curl); 
        preg_match_all('/<h2 class="title front-view-title">(.*?)<\/h2>/s', $result, $matches, PREG_OFFSET_CAPTURE);
        $arr = array();



       $doc = new DOMDocument();
       //extract the single block post URLs
        for($ik=0;$ik<=$n;$ik++)
        {
            $doc->loadHTML($matches[1][$ik][0]);
            $imageTags = $doc->getElementsByTagName('a');
            foreach($imageTags as $tag) {
            $arr[]=$tag->getAttribute('href');
            }
        }

        //get first 6 post result
        for($i=0;$i<=$n;$i++)
        {
                    $curl1 = curl_init();
                    curl_setopt($curl1, CURLOPT_URL, $arr[$i]);
                    curl_setopt($curl1, CURLOPT_HEADER, 0); 
                    curl_setopt($curl1, CURLOPT_POST, true);
                    curl_setopt($curl1, CURLOPT_POSTFIELDS, $post); 
                    curl_setopt($curl1, CURLOPT_RETURNTRANSFER, 1); 
                    curl_setopt($curl1, CURLOPT_FOLLOWLOCATION,true);
                    $result1 = curl_exec($curl1); curl_close($curl1); 


                    ## get the title
                    preg_match_all('/<h1 class="title single-title">(.*?)<\/h1>/s', $result1, $matches1, PREG_OFFSET_CAPTURE);
                    $my_title =$matches1[1][0][0];




                    require_once('url_to_absolute/simple_html_dom.php');
                    require_once('url_to_absolute/url_to_absolute.php');

                    $arr4 = array();
                    $arr41 = array();
                    $arr44 = array();
                    $html = file_get_html($arr[$i]);

                    ## get the content
                    foreach($html->find('div[class=post-single-content box mark-links]') as $table)
                    {
                     $arr44[]=  $table->innertext ;
                    }


                    ## get the image
                    foreach($html->find('div[class=post-single-content box mark-links] img') as $table1)
                    {
                    $size = getimagesize(url_to_absolute($url, $table1->src));
                    if($size['mime']=="image/jpeg" || $size['mime']=="image/JPEG" || $size['mime']=="image/jpg" || $size['mime']=="image/JPG" || $size['mime']=="image/png" )
                    {
                    $arr4[] = url_to_absolute($url, $table1->src);
                    }
                    }
                    $r_image=$arr4[0];






                    // check if the content was already updated in our database
                    $querystr = "SELECT * FROM $wpdb->posts 
                    LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)  
                    LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)  
                    WHERE ($wpdb->term_taxonomy.term_id = ".$_GET['c']."
                    AND $wpdb->term_taxonomy.taxonomy = 'category'   
                    AND $wpdb->posts.post_status = 'publish'
                    AND $wpdb->posts.post_title like '%".$my_title."%')";
                    $pageposts = $wpdb->get_results($querystr);


                    if(empty($pageposts[0]->ID))
                    {
                        $mcat = $_GET['ca'];
                        //Database insert query
                        $my_post = array(
                        'post_title'    => trim($my_title),
                        'post_status'   => 'publish',
                        'post_author'   => 1,
                        'post_category' => array($_GET['c']),
                        'post_date'  => date('Y-m-d H:i:s'),
                        'post_date_gmt'  => date('Y-m-d H:i:s'),
                        'post_type' => 'post'
                        );
                        $post_id=wp_insert_post( $my_post );

                        //update with new image and the new content
                        $image_url = $r_image;
                        $upload_dir = wp_upload_dir();
                        $image_data = file_get_contents($image_url);
                        $filename = basename($image_url);
                        if(wp_mkdir_p($upload_dir['path']))
                        $file = $upload_dir['path'] . '/' . $filename;
                        else
                        $file = $upload_dir['basedir'] . '/' . $filename;
                        file_put_contents($file, $image_data);

                        $wp_filetype = wp_check_filetype($filename, null );
                        $attachment = array(
                        'post_mime_type' => $wp_filetype['type'],
                        'post_title' => sanitize_file_name($filename),
                        'post_content' => '',
                        'post_status' => 'inherit'
                        );
                        $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
                        require_once(ABSPATH . 'wp-admin/includes/image.php');
                        $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
                        wp_update_attachment_metadata( $attach_id, $attach_data );
                        set_post_thumbnail( $post_id , $attach_id );
                        $Img_Uploaded_Url=get_site_url()."/wp-content/uploads/".$attach_data['file'];

                        // - concatenate both image and content



                        ## I need to wrap the text
                        //$remove_html_first= strip_tags(implode("</p><p>", $arr44));
                        //$mylink = "&nbsp;<a href=http://ift.tt/1JTGoWV".$arr[$i]."> ...συνέχεια ΕΔΩ!</a>";
                        //$then_truncate_the_value=mb_substr($remove_html_first , 0, 300);
                        //$finallink = $then_truncate_the_value.$mylink;
                        //$res_final= "<p><img  src=".$Img_Uploaded_Url."></p>"."<p>".$finallink."</p>";



                        ## I need full text
                        $linkz='<p><a href="http://otherside.gr" target="_blank">Πηγή</a></p>';
                        $res_final= implode("</p><p>", $arr44).$linkz;

                        $d = new DOMDocument();
                        $d->loadHTML('<meta http-equiv="content-type" content="text/html; charset=utf-8">'.$res_final);
                        $s = new DOMXPath($d);

                        foreach($s->query('//div[contains(attribute::class, "sharebar-wrap")]') as $t )
                        $t->parentNode->removeChild($t);

                        foreach($s->query('//*[contains(@class, "sharebar-wrap")]') as $t )
                        $t->parentNode->removeChild($t);            


                        $res_finals = $d->saveHTML();

                        $wpdb->query("UPDATE $wpdb->posts SET post_content = '".str_replace("'", "", $res_finals)."' WHERE ID = '".$post_id."'");


                    }


       }


    echo '<div style="margin-right:10%; margin-top:12%; margin-left:39%; margin-bottom:16%; color:#339933; font-size:16px;"> Successfully scrapped the contents</div>';
    $html->clear(); 
    unset($html);    
    }//END OTHERSIDE







    //TILESTWRA.COM SCRAPPER
    if ($site == "tilestwra.com")
    {

    $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $source);
        curl_setopt($curl, CURLOPT_HEADER, 0); 
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION,true);
        $result = curl_exec($curl); curl_close($curl); 
        preg_match_all('/<h3>(.*?)<\/h3>/s', $result, $matches, PREG_OFFSET_CAPTURE);
        $arr = array();



       $doc = new DOMDocument();
       //extract the single block post URLs
        for($ik=0;$ik<=$n;$ik++)
        {
            $doc->loadHTML($matches[1][$ik][0]);
            $imageTags = $doc->getElementsByTagName('a');
            foreach($imageTags as $tag) {
            $arr[]=$tag->getAttribute('href');
            }
        }

        //get first 6 post result
        for($i=0;$i<=$n;$i++)
        {
                    $curl1 = curl_init();
                    curl_setopt($curl1, CURLOPT_URL, $arr[$i]);
                    curl_setopt($curl1, CURLOPT_HEADER, 0); 
                    curl_setopt($curl1, CURLOPT_RETURNTRANSFER, 1); 
                    curl_setopt($curl1, CURLOPT_FOLLOWLOCATION,true);
                    $result1 = curl_exec($curl1); curl_close($curl1); 


                    ## get the title
                    preg_match_all('/<h1 class="light-title">(.*?)<\/h1>/s', $result1, $matches1, PREG_OFFSET_CAPTURE);
                    $my_title = $matches1[1][0][0];




                    require_once('url_to_absolute/simple_html_dom.php');
                    require_once('url_to_absolute/url_to_absolute.php');

                    $arr4 = array();
                    $arr41 = array();
                    $arr44 = array();
                    $html = file_get_html($arr[$i]);

                    ## get the content
                    foreach($html->find('div[class=item-content]') as $table)
                    {               
                     $arr44[]=  $table->innertext;
                    }


                    ## get the image
                    foreach($html->find('div[class=single-inbox] img') as $table1)
                    {
                    $size = getimagesize(url_to_absolute($url, $table1->src));
                    if($size['mime']=="image/jpeg" || $size['mime']=="image/JPEG" || $size['mime']=="image/jpg" || $size['mime']=="image/JPG" || $size['mime']=="image/png" )
                    {
                    $arr4[] = url_to_absolute($url, $table1->src);
                    }
                    }
                    $r_image=$arr4[0];






                    // check if the content was already updated in our database
                    $querystr = "SELECT * FROM $wpdb->posts 
                    LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)  
                    LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)  
                    WHERE ($wpdb->term_taxonomy.term_id = ".$_GET['c']."
                    AND $wpdb->term_taxonomy.taxonomy = 'category'   
                    AND $wpdb->posts.post_status = 'publish'
                    AND $wpdb->posts.post_title like '%".trim($my_title)."%')";
                    $pageposts = $wpdb->get_results($querystr);


                    if(empty($pageposts[0]->ID))
                    {

                        //Database insert query
                        $my_post = array(
                        'post_title'    => trim($my_title),
                        'post_status'   => 'publish',
                        'post_author'   => 1,
                        'post_category' => array($_GET['c']),
                        'post_date'  => date('Y-m-d H:i:s'),
                        'post_date_gmt'  => date('Y-m-d H:i:s'),
                        'post_type' => 'post'
                        );
                        $post_id=wp_insert_post( $my_post );

                        //update with new image and the new content
                        $image_url = $r_image;
                        $upload_dir = wp_upload_dir();
                        $image_data = file_get_contents($image_url);
                        $filename = basename($image_url);
                        if(wp_mkdir_p($upload_dir['path']))
                        $file = $upload_dir['path'] . '/' . $filename;
                        else
                        $file = $upload_dir['basedir'] . '/' . $filename;
                        file_put_contents($file, $image_data);

                        $wp_filetype = wp_check_filetype($filename, null );
                        $attachment = array(
                        'post_mime_type' => $wp_filetype['type'],
                        'post_title' => sanitize_file_name($filename),
                        'post_content' => '',
                        'post_status' => 'inherit'
                        );
                        $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
                        require_once(ABSPATH . 'wp-admin/includes/image.php');
                        $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
                        wp_update_attachment_metadata( $attach_id, $attach_data );
                        set_post_thumbnail( $post_id , $attach_id );
                        $Img_Uploaded_Url=get_site_url()."/wp-content/uploads/".$attach_data['file'];

                        // - concatenate both image and content


                        ## I need full text AND REMOVE SCRIPTS AND DIVS
                        $linkz='<p><a href="http://www.tilestwra.gr" target="_blank">Πηγή</a></p>';
                        $arr44c = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', "", $arr44); 
                        $arr44d = preg_replace('#<div id="facebook-comments">(.*?)</div>#', ' ', $arr44c);
                        $arr44e = preg_replace('#<div class="mobileno adbox(.*?)</div>#', ' ', $arr44d);
                        $arr44b = preg_replace('#<div class="mobileno adbsox(.*?)</div>#', ' ', $arr44e);
                        $res_final= '<div style="font-size:16px; color:#000;">' . implode("</p><p>", $arr44b).$linkz . '</div>';


                        $d = new DOMDocument();
                        $d->loadHTML('<meta http-equiv="content-type" content="text/html; charset=utf-8">'.$res_final);
                        $s = new DOMXPath($d);

                        //REMOVE DIVS
                        foreach($s->query('//div[contains(attribute::class, "fbwithcount")]') as $t )
                        $t->parentNode->removeChild($t);


                        foreach($s->query('//*[contains(@class, "fbwithcount")]') as $t )
                        $t->parentNode->removeChild($t);

                        $res_finals = $d->saveHTML();


    $wpdb->query("UPDATE $wpdb->posts SET post_content = '".str_replace("'", "", $res_finals)."' WHERE ID = '".$post_id."'");

    }

    }


    echo '<div style="margin-right:10%; margin-top:12%; margin-left:39%; margin-bottom:16%; color:#339933; font-size:16px;"> Successfully scrapped the contents</div>';
    $html->clear(); 
    unset($html);
    }//END TILESTWRA.COM






    //DIAFORETIKO SCRAPPER
    if ($site == "diaforetiko.gr")
    {

    $website_url='www.diaforetiko.gr';


        $curl = curl_init($website_url);

        curl_setopt($curl, CURLOPT_URL, $source);
        curl_setopt($curl, CURLOPT_HEADER, 0); 
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION,true);
        $result = curl_exec($curl); curl_close($curl); 
        preg_match_all('/<h2>(.*?)<\/h2>/s', $result, $matches, PREG_OFFSET_CAPTURE);
        $arr = array();



       $doc = new DOMDocument();
       //extract the single block post URLs
        for($ik=0;$ik<=$n;$ik++)
        {
            $doc->loadHTML($matches[1][$ik][0]);
            $imageTags = $doc->getElementsByTagName('a');
            foreach($imageTags as $tag) {
            $arr[]=$tag->getAttribute('href');


            }
        }

        //get first 6 post result
        for($i=0;$i<=$n;$i++)
        {
                    $curl1 = curl_init();
                    curl_setopt($curl1, CURLOPT_URL, $arr[$i]);
                    curl_setopt($curl1, CURLOPT_HEADER, 0); 
                    curl_setopt($curl1, CURLOPT_RETURNTRANSFER, 1); 
                    curl_setopt($curl1, CURLOPT_FOLLOWLOCATION,true);
                    $result1 = curl_exec($curl1); curl_close($curl1); 


                    ## get the title
                    preg_match_all('/<h1>(.*?)<\/h1>/s', $result1, $matches1, PREG_OFFSET_CAPTURE);
                    $my_title =$matches1[1][0][0];




                    require_once('url_to_absolute/simple_html_dom.php');
                    require_once('url_to_absolute/url_to_absolute.php');

                    $arr4 = array();
                    $arr41 = array();
                    $arr44 = array();
                    $html = file_get_html($arr[$i]);

                    ## get the content
                    foreach($html->find('div[class=post-content]') as $table)
                    {
                     $arr44[]=  $table->innertext ;
                    }


                    ## get the image
                    foreach($html->find('div[class=post-content] img') as $table1)
                    {
                    $size = getimagesize(url_to_absolute($url, $table1->src));
                    if($size['mime']=="image/jpeg" || $size['mime']=="image/JPEG" || $size['mime']=="image/jpg" || $size['mime']=="image/JPG" || $size['mime']=="image/png" )
                    {
                    $arr4[] = url_to_absolute($url, $table1->src);
                    }
                    }
                    $r_image=$arr4[0];






                    // check if the content was already updated in our database
                    $querystr = "SELECT * FROM $wpdb->posts 
                    LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)  
                    LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)  
                    WHERE ($wpdb->term_taxonomy.term_id = ".$_GET['c']."
                    AND $wpdb->term_taxonomy.taxonomy = 'category'   
                    AND $wpdb->posts.post_status = 'publish'
                    AND $wpdb->posts.post_title like '%".trim($my_title)."%')";
                    $pageposts = $wpdb->get_results($querystr);


                    if(empty($pageposts[0]->ID))
                    {
                        $mcat = $_GET['ca'];
                        //Database insert query
                        $my_post = array(
                        'post_title'    => trim($my_title),
                        'post_status'   => 'publish',
                        'post_author'   => 1,
                        'post_category' => array($_GET['c']),
                        'post_date'  => date('Y-m-d H:i:s'),
                        'post_date_gmt'  => date('Y-m-d H:i:s'),
                        'post_type' => 'post'
                        );
                        $post_id=wp_insert_post( $my_post );

                        //update with new image and the new content
                        $image_url = $r_image;
                        $upload_dir = wp_upload_dir();
                        $image_data = file_get_contents($image_url);
                        $filename = basename($image_url);
                        if(wp_mkdir_p($upload_dir['path']))
                        $file = $upload_dir['path'] . '/' . $filename;
                        else
                        $file = $upload_dir['basedir'] . '/' . $filename;
                        file_put_contents($file, $image_data);

                        $wp_filetype = wp_check_filetype($filename, null );
                        $attachment = array(
                        'post_mime_type' => $wp_filetype['type'],
                        'post_title' => sanitize_file_name($filename),
                        'post_content' => '',
                        'post_status' => 'inherit'
                        );
                        $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
                        require_once(ABSPATH . 'wp-admin/includes/image.php');
                        $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
                        wp_update_attachment_metadata( $attach_id, $attach_data );
                        set_post_thumbnail( $post_id , $attach_id );
                        $Img_Uploaded_Url=get_site_url()."/wp-content/uploads/".$attach_data['file'];

                        // - concatenate both image and content



                        ## I need to wrap the text
                        //$remove_html_first= strip_tags(implode("</p><p>", $arr44));
                        //$mylink = "&nbsp;<a href=http://ift.tt/1JTGoWV".$arr[$i]."> ...συνέχεια ΕΔΩ!</a>";
                        //$then_truncate_the_value=mb_substr($remove_html_first , 0, 300);
                        //$finallink = $then_truncate_the_value.$mylink;
                        //$res_final= "<p><img  src=".$Img_Uploaded_Url."></p>"."<p>".$finallink."</p>";



                        ## I need full text
                        $linkz='Μην ξεχάσετε να κάνετε κοινοποίηση';
                        $arr44d = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', "", $arr44);
                        $arr44e = preg_replace('#<div id="minions">(.*?)</div>#', ' ', $arr44d);
                        $arr44f = preg_replace('#<div align="left">(.*?)</div>#', ' ', $arr44e);
                        $arr44g = preg_replace('#<h3>(.*?)</h3>#', ' ', $arr44f);
                        $arr44c = preg_replace('#<div class="fb-comments fb_iframe_widget">(.*?)</div>#', ' ', $arr44g);

                        $res_final= implode("</p><p>", $arr44c).$linkz;

                        $d = new DOMDocument();
                        //libxml_use_internal_errors(true);
                        $d->loadHTML('<meta http-equiv="Content-Type" content="text/html"; charset="utf-8">'.$res_finals);

                        $s = new DOMXPath($d);

                        foreach($s->query('//div[contains(attribute::class, "sharebar-wrap")]') as $t )
                        $t->parentNode->removeChild($t);

                        foreach($s->query('//*[contains(@class, "sharebar-wrap")]') as $t )
                        $t->parentNode->removeChild($t);            

                        foreach($s->query('//div[contains(attribute::class, "fb-comments fb_iframe_widget")]') as $t )
                        $t->parentNode->removeChild($t);

                        foreach($s->query('//*[contains(@class, "fb-comments fb_iframe_widget")]') as $t )
                        $t->parentNode->removeChild($t);

                        $res_finals = $d->saveHTML();

                        $wpdb->query("UPDATE $wpdb->posts SET post_content = '".str_replace("'", "", $res_finals)."' WHERE ID = '".$post_id."'");


                    }


       }


    echo '<div style="margin-right:10%; margin-top:12%; margin-left:39%; margin-bottom:16%; color:#339933; font-size:16px;"> Successfully scrapped the contents</div>';
    $html->clear(); 
    unset($html);    
    }//END DIAFORETIKO




    ?>

Update theme and plugins programmaticaly

I would like to extend my wordpress plugin so that it can update themes and plugins.

Getting a list of all plugins or themes is no problem for me, but I have no idea how to update the themes and plugins with PHP code.

Maybe there is a smart way to do this? I dont want to create a separate table with all plugins/themes and check the versions manually.

Thanks in advance, Thomas.

Form robot to submit multiple javascript form

I have multiple form named from "form1" to "form5" within a same root url, for example 222.111.111.100/Form/. In the first page, which means

http://ift.tt/1JTGoWK

The form in the response http request would be writtin in a general style as following:

<form name="form1" action="B.do?a=first" method="post"  > 
<input name="sure" type="checkbox" id="sure" value="" /> 
<input name="submit" type="submit" value="NextStep" /> 
</form>

I need to fill the form automatically one by one as the previous form will have impact on the next one. And to be clear, after this form1, the url will trace to:

http://ift.tt/1AKvnPi

The problem is when I using cUrl to get the content, then javascript dealing with the input checkbox or submit/nextstep button, the document.forms[0].submit() for each form does not working. Even if i passed to the second page, it seems that the Global Variable have not been passed to the next page.

Sorry for poor organisation of question, I will be available for more details.

How to redirect a user with specific "ROLE" to a specific page after login in Wordpress

I have created a new user role named student_role i want to redirect the user with this role to form page(which i created from wp front end) when he logins. I tried peter login redirect plugin but failed.. Need help for this.

Debug whole Project in Phpstorm?

I searched on net and stackoverflow as well.

But I was unable to find satisfactory answer : How should I debug Whole project (Not a single file) in phpStorm?

I mean like Visual studio or like we debug on Netbeans , Intellij for Java project.

I need to know how to debug an application say like magento.

Because I cant use debugging point for Controller

C:\xampp\htdocs\coinandbuillion\app\code\core\Mage\Checkout\controllers\CartController.php

As it opens that file on controller, and its not properly debugged , gives lots of errors when that file is directly executed,also gives some fatal errors in phpstorm as Controller got executed directly.

Does anyone have idea how to debug project so, it will go from index.php or initalization point of application till the end automatically just like Visual Studio.

How can i create user profile link for my website user?

I have a social networking website named www.dablip.com. I want to create unique user name and unique url for my users. please help. I will be gratefull to you.

Yii2 executing a sql server stored procedure from button

I have a sql server stored procedure sp_annualupdate that I want to call and run from a button using Yii2. Any advise on coding controller and view much appreciated.

How to supress socket_connect(): unable to connect

I am trying to suppress the warning below with the @ operator, but the error still keep getting thrown in my codeigniter log.

Any idea how to suppress that warning ? I don't want to feed my log with too much of that. Thanks

socket_connect(): unable to connect [10037]: An operation was attempted on a non-blocking socket that already had an operation in progress.
C:\xampp\htdocs\gs\services\system\cms\libraries\tools\tools_sockets.php 64

while (!($connected = @socket_connect($socket, $this->address,   $this->service_port)) && $attempts++ < $this->maxWait) {
    $error = socket_last_error();
    //socket is waiting for the server response
}

CakePHP 1.2 cake i18n extract, generate files based on token/domain

I'm using CakePHP 1.2. I have defined all the strings for which I need localization in gettext function. e.g.

file app/views/posts/add.thtml

<?php echo __("Text1.","feature_one"); ?>
<?php echo __("Text2.","feature_two"); ?>

file app/views/posts/edit.thtml

<?php echo __("Text3.","feature_one"); ?>
<?php echo __("Text4.","feature_two"); ?>

While generating the pot files, I'm using the cake i18n extract command from the cake console folder

cake i18n extract

Using this command I'm able to extract pot files in 2 formats, one in which all the strings are extracted and merged to one single file say 'default.pot', or all the strings are extracted to independent files with file names as the relative file path e.g. "-posts-add.pot" & "-posts-edit.pot".

What I need is to generate pot files based on the tokens/domains defined in the gettext function. i.e. one file each for a token/domain defined containing all the strings in that domain. e.g. "feature_one.pot" & "feature_two.pot".

Laravel 4 how to merge database tables and order them by created_at?

I have 4 database tables that I want to merge together, and than I want to order all the data by created_at field. With my code all data is still grouped per database table, the result should be some sort of timeline of all my tables data. What am I doing wrong? It is only showing 4 items...

public function showIndex()
{

    $users = User::orderBy('created_at', 'desc')->get();
    $projects = Project::with('votes')->orderBy('created_at', 'desc')->get();
    $events = Calendar::orderBy('created_at', 'desc')->get();
    $jobs = Job::orderBy('created_at', 'desc')->get();

    $all = $users->merge($projects)->merge($events)->merge($jobs);

    return View::make('users.index')->with('events', $all);

}

Select data using PDO and a PHP function

When I try to select one nome from my bd it doesn't show anything

That's the function to select a name:

public function searchName(){
    $db = new Conection();
    $query = $db->prepare("SELECT * FROM dog WHERE id = 1");
    $query->execute();
    $result = $query->fetchAll(PDO::FETCH_OBJ);
    foreach($result as $row)
    {
        return $row['name'];//return to getName

    }
}

here is the code from getName:

    require 'Conection.php';
    require 'model/Dog.php';

    $dog = new Dog;
    $res = $dog->searchName(1);

    echo $res;

The class Connection is ok.

Close modal without redirect

I have a modal that is created when I click a button. It's content is php - generated because I need to communicate with the server to do some action. Besides the submit button (which works fine btw) I have another button which should just close the modal without doing any action.

I know I can achieve this by encapsulating the button in <a href="page_to_redirect.php"> </a>

But I don't want to reload the page, so I'm trying to do it using jquery's close() function. However, the result achieved is that the window closes immediately. This is the code of the content:

<body>
    <?php 
        echo '<form action="action.php" method="post">';
        echo '<p >Are you sure you want to do this?</p>';
        echo '<input type="submit" value="YES"></input>';         
        echo '</form>'; 
    ?>

    <input type="button" value="NO" id="reject">

    <script type="text/javascript">
        $(document).ready(function() {          
            $('#reject').onclick($("#delete_dialog").dialog("close"))
        });
    </script>
</body>

delete_dialog is the id of the modal. I removed the data in the modal to simplify the code, but obviously there are data that are submitted when clicking the submit button

Get access token using refresh token

I am currently implementing OAuth2 using thephpleague/oauth2 library. I have already added the refresh token grant and the access token response already contains the refresh token. However, I don't have any idea how to use that refresh token to get a new access token.

I checked the documentation but I don't see anything about it. The oauth2-client library has methods for it but I'm not going to use that.

file_get_contents() skipping text between <> tag

I am trying to read .tsv file using PHP. I am using the simplest method of file_get_contents() but it is skipping any text between "<>" tags. Following is the format of my .tsv file

<id_svyx35_88c_avbfa5>  <Kuldeep_Raval> rdf:type    <wikicat_Delhi_Daredevils_cricketers>

Following is the code I am using

$filename = "access_s.tsv";
$content = file_get_contents($filename);
//Split file into lines
$lines  = explode("\n", $content);
echo $content;

On reading it, the output is just

rdf:type

Please help in what can be the solution to read the line as it is?

Laravel 5 with Foundation 5

I installed foundation via bower under "resources/assets/bower_components".

I don't know what to do with the _settings.scss file and where to put it.

My app.scss file just has:

@import "../bower_components/foundation/scss/foundation";
@import "../bower_components/foundation/scss/normalize";

I can't get the javascript to work. I don't know why. In my gulpfile I've combined all the javascript files into one file app.js.

Here is my gulpfile.

elixir(function(mix) {

var bowerPath = "resources/assets/bower_components/";

mix.sass(
    [
        "app.scss"
    ],
    "public/css",
    {
        includePaths: [
            bowerPath + "foundation/scss"
        ]
    }
)
    .scripts(
    [
        "jquery/dist/jquery.js",
        "fastclick/lib/fastclick.js",
        "jquery.cookie/jquery.cookie.js",
        "jquery-placeholder/jquery.placeholder.js",
        "foundation/js/foundation.js"
    ],
    "public/js/app.js",
    bowerPath
);
});

Here is my current project structure: http://ift.tt/1zIdxRI

Someone please help. I'm stuck and I think I've done something wrong along the way. If someone can walk me through installing Foundation 5 to Laravel 5 from a fresh Laravel project, that would be awesome!

X-cart migration to latest version without loosing database

Our website is currently using X-cart version 4.4. We want to upgragde to version 5.0. The coding standard, file structures, and database tables are completely different. So we have to migrate X-cart 4.4 database into X-cart 5, then make new skins according to X-cart 5 standard and all modules installation as well as customization.

How do we upgrade without loosing the existing database?