jeudi 8 septembre 2016

PHP read file not working

I have a problem with my orders. If a person press F5 too fast, an order can be sent multiple times. I want to write the order_id into a file, and check if it's allready in there. If so, dont send the order again.

I get the order_id, than i want to check if it's in the orders.txt. If it's in, redirect to "mysite". If not there, write it to orders.txt. The other part is that after its written in orders.txt send the order_id-XXXX.xml to a url.

The thing is: only the else part works. If i press F5 multiple times, it writes multiple times to the orders.txt, and not checking if it's allready there. ANd also sends the order multiple times.

But if i remove the inner if (file_exists($filename))else{} part, it works just fine.

Heres my code :

$order_id=  $order->get_order_number();
$filename = $_SERVER['DOCUMENT_ROOT']."/xml/order_id-".$order_id.".xml";
$_cassa_point_url='some_url';

$orders_txt = $_SERVER['DOCUMENT_ROOT']."/xml/orders.txt";

$contents = file_get_contents($orders_txt);
$pattern = preg_quote($order_id, '/');
$pattern = "/^(".$pattern.")/m";

    if( strpos(file_get_contents($orders_txt),$order_id) !== false) {
         header( "refresh:0;url=mysite );
    }else{
            $myfile = file_put_contents($orders_txt, $order_id."\r\n" , FILE_APPEND | LOCK_EX);
                if (file_exists($filename)) {

                $url = $_cassa_point_url . $order_id;
                file_get_contents($url);
                header( "refresh:0;url=mysite);
                return true;

                }
                else {

                    $url = $_cassa_point_url . $order_id;
                    file_get_contents($url);
                    header( "refresh:0;url=mysite );
                    return true;


                }
    }

Aucun commentaire:

Enregistrer un commentaire