Diferenças entre MySQLi e PDO MySQL

Desde que o PHP 7 foi lançado e o suporte para o PHP 5 foi encerrado, muitas empresas de hospedagem tiraram o PHP 5 de seus servidores, e desenvolvedores PHP foram forçados a migrar seu código para funcionar com PHP 7.

Uma das mudanças do PHP 7 foi a descontinuação da extensão original do MySQL. Os desenvolvedores tiveram que optar por migrar seu código para usar o MySQLi ou e a extensão PDO.

Leia este artigo para saber sobre as diferenças e decidir qual é o melhor para você migrar seu código para trabalhar no PHP 7 ou posterior, bem como aprender sobre alguns pacotes recomendados que usam PDO ou MySQLi para executar propósitos comuns de banco de dados, como backup, segurança, registro de usuário e login, abstração de banco de dados, ORM (Object-Relational Mapping) etc.
Continue reading

Utilizando Lambda e Closures no PHP 5.3

Artigo retirado do site iMaster e reproduzido aqui na sua integra
http://imasters.com.br/linguagens/php/funcoes-anonimas-lambda-e-closure-no-php/?utm_source=iMasters&utm_campaign=80c91f405c-News_semanal_2014_01_201_20_2015&utm_medium=email&utm_term=0_c1528e6ab3-80c91f405c-359962985

Uma função anônima é qualquer função que não possui ou não precise de um nome identificador. Elas podem ser definidas em qualquer lugar e normalmente são atribuídas a uma variável e/ou utilizadas como callback.

Conceitualmente, temos dois tipos de funções anônimas, lambda e closures, que estão disponíveis a partir da versão 5.3 do PHP.

Lambda
Lambda é uma função anônima básica. Muitas linguagens não utilizam esse termo, apenas chamam de função anônima, mas particularmente costumo utilizar, pois a função create_function, que está disponível desde a versão 4 do PHP, cria funções anônimas há um bom tempo, logo costumo chamar este novo estilo de lambda para diferenciar. Confira a sintaxe de uma lambda:

1
$var = function ( parameters ) {
2
statement
3
};
Lambdas são mais rápidas que funções criadas utilizando a função create_function.

Closure
Closures são funções anônimas um pouco mais complexas que as lambdas, pois permitem interações com variáveis externas, ou seja, variáveis que foram definidas no mesmo escopo em que o closure foi definido, para isso utilizamos a palavra-chave use, informando as variáveis externas que iremos interagir entre parênteses.

1
$var = function ( parameters ) use ( variables ) {
2
statement
3
};
É importante finalizar a declaração de uma lambda ou closure com ponto e vírgula após as chaves.

Método mágico __invoke()
O PHP oferece um conjunto de métodos mágicos que podem ser utilizados quando necessário em uma classe e são executados quando um determinado comportamento é solicitado.

O método mágico __invoke() foi adicionado na versão 5.3 do PHP, sendo este executado quando tentamos chamar um objeto como uma função (bem parecido com uma função variável), que foi apresentada no artigo Variáveis e Constantes no PHP.

1

Trabalhando com lambda e closure
Agora que conhecemos um pouco sobre funções anônimas, vamos praticar:

1

Começamos o script acima simulando um array de configurações, em seguida criamos uma lambda, para calcular a soma entre dois parâmetros, atribuindo a variável $lambda.

Após testar a lambda, definimos um closure que recebe uma mensagem e interage com o array de configurações($config) para padronizar como esta mensagem deve ser exibida. Com isso, não precisamos passar as configurações como parâmetro toda vez que a função/closure for utilizada, em seguida testamos o closure.

Por último criamos uma função que recebe dois parâmetros. O primeiro é uma mensagem, já o segundo é um callback, ou seja, uma função que deve ser chamada antes de retornar o resultado; sendo assim, ao executar a função firstWord passamos a mensagem como primeiro parâmetro e como segundo parâmetro enviamos a variável $closure, que antes de retornar o resultado é executada.

Referências
http://php.net/manual/pt_BR/functions.anonymous.php
http://stackoverflow.com/questions/150129/what-is-a-lambda
http://stackoverflow.com/questions/220658/what-is-the-difference-between-a-closure-and-a-lambda

Como calcular valores monetários no PHP

Para aqueles que estão iniciando e precisam de uma ajudinha para o desenvolvimento daquela aplicação chata que todo mundo precisa fazer quando estão començando utilize os exemplos abaixo para somar valores monetários no PHP

$valor = "25.00";
$multa = "1.50";
$resultado = $valor + $multa;
echo number_format($resultado,2,",",".");
// resultado: 26,50

Criando aplicativo em PHP para publicar na página do mural do Facebook

Tutorial em inglês

In this tutorial you can learn how to post in Facebook Page wall from a PHP application.

post to FB
For this tutorial i have created a sample page named ‘New Movies’. You can create a page by using ‘Create Page’ option present in your facebook dashboard.

 

post to fb

Also i have created a Facebook App named ‘Newmoviesapp’ by which am going to connect with facebook.

To create a facebook application…

* Go to https://developers.facebook.com/apps
* Login with your facebook credentials
* If you are not verified your mobile number with facebook you will be prompted to verify it.
* Click on “Create New App” and fill out the form.
* Once you created the app, under “Website with Facebook Login” add your project URL (i.e http://yourdomain.com/postfofbpage.php) and save the changes.

 

post to fb
Now download Facebook PHP SDK here: https://github.com/facebook/facebook-php-sdk

Find the ‘src’ folder from the SDK download and keep it in your project folder. Create ‘postfofbpage.php’ file in the place where your ‘src‘ folder exists and place the following code.

Dont forgot to replace ‘APPID_FROM_FACEBOOK‘, ‘APPSECRET_FROM_FACEBOOK‘ and ‘YOUR_PAGE_URL‘ with your Facebook App details.

<?php
include_once 'src/facebook.php';

$appId = 'APPID_FROM_FACEBOOK';
$secret = 'APPSECRET_FROM_FACEBOOK';
$returnurl = 'YOUR_PAGE_URL';
$permissions = 'manage_pages, publish_stream';

$fb = new Facebook(array('appId'=>$appId, 'secret'=>$secret));

$fbuser = $fb->getUser();

if($fbuser){

if(isset($_POST['msg']) and $_POST['msg']!=''){
try{
$message = array(
'message' => $_POST['msg']
);
$posturl = '/'.$_POST['pageid'].'/feed';
$result = $fb->api($posturl,'POST',$message);
if($result){
echo 'Successfully posted to Facebook Wall...';
}
}catch(FacebookApiException $e){
echo $e->getMessage();
}
}

try{
$qry = 'select page_id, name from page where page_id in (select page_id from page_admin where uid ='.$fbuser.')';
$pages = $fb->api(array('method' => 'fql.query','query' => $qry));

if(empty($pages)){
echo 'The user does not have any pages.';
}else{
echo '<form action="" method="post">';
echo 'Select Page: <select name="pageid">';
foreach($pages as $page){
echo '<option value="'.$page['page_id'].'">'.$page['name'].'</option>';
}
echo '</select>';
echo '<br />Message: <textarea name="msg"></textarea>';
echo '<br /><input type="submit" value="Post to wall" />';
echo '</form>';
}

}catch(FacebookApiException $e){
echo $e->getMessage();
}

}else{
$fbloginurl = $fb->getLoginUrl(array('redirect-uri'=>$returnurl, 'scope'=>$permissions));
echo '<a href="'.$fbloginurl.'">Login with Facebook</a>';
}

?>

Now execute postfofbpage.php in browser and check the output. The Page will ask you to give permission for the app to post in your page wall.

post to fb

Once you accept it you will be redirected to your php app where you can see a form by which you can post a status message to your facebook page wall.

post to fb

– See more at: http://www.detailsinn.com/c7f76878ca736e015b7a94bf3036136c1357649641-article-posting-in-facebook-page-wall-from-a-php-application.html#sthash.dv0lKA0Y.dpuf

Link original
http://www.detailsinn.com/c7f76878ca736e015b7a94bf3036136c1357649641-article-posting-in-facebook-page-wall-from-a-php-application.html

Blue Systems Recursive Gallery

O Blue Systems Recursive Gallery, tem como principal objetivo listar todas as imagens encontradas em um diretório classificar e montar uma galeria de imagens. Ele possibilita que seja scaneada imagens em subdiretórios e isto acaba tornando o script ainda mais interessante.

Para carregar as imagens de forma mais natural é gerado um cache do thumbnail. A instalação não requer um banco de dados ele scaneia as imagens on the fly.

Nome do projeto: Blue Systems Recursive Gallery
Requisitos de sistema: Apache 2.x, LibGB, PHP 5.x
Desenvolvido por @Jaccon (JS) – Software Engenier Blue Systems Tecnologia
Em: 20/11/2013

Screenshot
Screen Shot 2015-12-13 at 12.42.01 AM

Download
https://github.com/jaccon/blue_recursive_gallery/tree/master

 

Protegendo imagens com PHP

Post falando a respeito de como proteger imagens utilizando PHP. Artigo em inglês.

Sources to check

In this article, we’re going to tackle a few different tactics to safeguard images. But, let’s first think about what ways people can get images.

  • Direct path – if a user knows the path to an image, they can simply go straight to it, and download the image.
  • Drag and drop – in most browsers today, you can simply drag and drop an image right onto your desktop.
  • Hotlinking – another website can link directly to your image
  • Screenshot – a visitor can simply take a screenshot of your page and crop the image.

How to fix them

So, now that we’ve established where our problems are, how can we fix them?

  • Direct path – we’re going to create a PHP script to “hide” the direct path.
  • Drag and drop – we’re going to implement something that Flickr does… placing a 1×1 transparent GIF on top of the image.
  • Hotlinking – using .htaccess, we can prevent hotlinking from occurring
  • Screenshot – not much you can do here. The best recommendation I have is to add a watermark to your image (not covered in this tutorial)

Blocking Direct Path Access

To block a user from using the direct path route, we will implement a combination of PHP and .htaccess. What we will do is create a PHP file that serves as the “proxy” for the image, and prevents the user from seeing the final path. So…let’s get to it.

image.php

1
2
3
4
5
6
7
8
9
10
11
<br>
$_GET['f'] = "protectedImages/" . $_GET['f'];<br>
$type = getFileType($_GET['f']);<br>
if (acceptableType($type)) {<br>
    header("Content-type: $type");<p></p>
<p> echo file_get_contents($_GET['f']);<br>
    exit;<br>
}<br>
header('HTTP/1.1 403 Forbidden');<br>
exit;<br>
</p>

We first set the image path for the image. We point it into the ‘protectedImage’ directory to prevent someone from browsing around. True, they could simply set ?f=../../ and get out, but that is why we use the getFileType and acceptableType functions.

getFileType()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<br>
function getFileType($file) {<br>
    //Deprecated, but still works if defined...<br>
    if (function_exists("mime_content_type"))<br>
        return mime_content_type($file);<p></p>
<p> //New way to get file type, but not supported by all yet.<br>
    else if (function_exists("finfo_open")) {<br>
        $finfo = finfo_open(FILEINFO_MIME_TYPE);<br>
        $type = finfo_file($finfo, $file);<br>
        finfo_close($finfo);<br>
        return $type;<br>
    }</p>
<p> //Otherwise...just use the file extension<br>
    else {<br>
        $types = array(<br>
            'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',<br>
            'gif' => 'image/gif', 'bmp' => 'image/bmp'<br>
        );<br>
        $ext = substr($file, strrpos($file, '.') + 1);<br>
        if (key_exists($ext, $types)) return $types[$ext];<br>
        return "unknown";<br>
    }<br>
}<br>
</p>

In this simple function, we first try using mime_content_type. This function has been deprecated, but if it’s defined, we’ll try to use it. Otherwise, we’ll try the Fileinfo library that was added into the PHP 5.3.0 and PECL fileinfo 0.1.0. But, if that isn’t available, we’ll just revert to using the good ol’ file extension method. Since I assume you uploaded all of the files yourself, I assume it is safe to use. You may want to alter this if users are allowed to upload their own pictures.

acceptableTypes()

Now that we have our file type, let’s validate it. This will prevent users from trying to get PHP files, or any sort of file they shouldn’t get. Here it is…

1
2
3
4
5
6
7
<br>
function acceptableType($type) {<br>
    $array = array("image/jpeg", "image/jpg", "image/png", "image/png");<br>
    if (in_array($type, $array))<br>
        return true;<br>
    return false;<br>
}<br>

Of course, if you want to use other image types, feel free to add them to the array. But, those are some of the common ones (sorry bmp and gif).

From there, we set our header to tell the browser what we’re returning, and then send the browser the contents of the image we want to send. The exit is important because you don’t want to return a 403, which is the default for a bad request.

Your image script should work just fine now. Try it out, and see how it goes. Don’t forget to change the image directory if you have a folder named something other than “protectedImages”.

Preventing Drag and Drop

To prevent drag and drop of images, we’re going to use a little trick that I noticed Flickr was using. They simply stretch a 1×1 transparent gif over the image, so when a user either tries to drag and drop (or right-click and “Save image as”), the image saved is the gif, not the actual image.

First, download a 1×1 transparent gif here.

Now, in your HTML, all you will need to do is add in the image. So, let’s do that first. Here is a pretty simple html page we’ll work with.

1
2
3
4
5
6
7
8
9
10
11
12
<br>
<html><br>
<head><br>
    <title>Page Title</title><br>
</head><br>
<body><br>
    <div class="image"><br>
        <img src="image.php?f=image.jpg" alt="Image" /><br>
        <div class="cover"><img src="imageCover.gif" alt=""  /></div><br>
    </div><br>
</body><br>
</html><br>

You’ll see that we added an image tag that uses the image.php file we just created. Of course, we will need to add some css to make this all work correctly though. Here’s how to do it:

1
2
3
4
5
6
7
8
9
10
11
12
13
<br>
.image {<br>
    overflow: hidden;<br>
    position: relative;<br>
    float: left;<br>
}<br>
.image .cover, .image .cover img {<br>
    position: absolute;<br>
    top: 0px;<br>
    left: 0px;<br>
    width: 100%;<br>
    height: 100%;<br>
}<br>

So, what’s this do? The wrapping div (.image) is given a position: relative to allow us to absolute position the cover image inside this div. Otherwise, the cover image would be positioned to the browser’s top-left corner (unless another div had position:relative). The float:left and overflow:hidden forces the div to be wrapped only around the content of the div, not the entire width of the browser. This also ensures that the image cover, when given 100% width uses the width of the div, not the window.

So, test it out and see what happens! The cover image appears on top, and if you try to right-click and save, it grabs the transparent image, not the real image. Then, try to drag and drop it onto your desktop. Same thing!

Disabling hotlinking

In this scenario, we are forcing PHP to handle the image handling. So, we can technically deny ALL requests for images within the protectedImages directory. How do we do that? Create a .htaccess file within the protectedImages folder, and paste this code into it.

1
2
3
4
5
6
7
8
<br>
#Prevent directory listing<br>
Options -Indexes<p></p>
<p>#Prevent images from being viewed<br>
<Files *><br>
  deny from all<br>
</Files><br>
</p>

The first line prevents any sort of directory listings. Some servers do this automatically, but others may not. Without this, a user may be able to see a directory listing of all files. The second set of parameters tells the server to deny any and all files. If anyone tries to visit the page, they will get a “Forbidden” message.

Further protection on the image.php file

Although we have the image.php file handling all of the images, it really isn’t protected. Try inserting the URL for the image src directly into your browser. You’ll get an image, and you can download it. Let’s do a little trick to prevent that. What we’ll do is two things: force the image.php to be referred by the site and allow the user to get images only within two seconds of visiting a page.

Forcing the referral

When a browser visits your index.html page, any images that are requested will have a referrer of your page. So, we can use that. We’ll use .htaccess to handle that!

1
2
3
4
5
<br>
RewriteEngine on<br>
RewriteCond %{HTTP_REFERER} ^$<br>
RewriteCond %{SCRIPT_FILENAME} image\.php<br>
RewriteRule (.*) image.php?onlyHappensFromHTACCESS=denied [QSA,L]<br>

This uses the RewriteEngine module in Apache servers. It has two different conditions. It first ensures that the referrer is not empty, and checks that the page being requested is the image.php script. If both of these are true, we’ll redirect the request to go to image.php?onlyHappensFromHTACCESS=denied. What we’ll do is display a different message to the user.

In the image.php file, we need to add a check for this. Around your previous code, wrap a check for $_GET[‘onlyHappensFromHTACCESS’]. Here’s what it looks like:

1
2
3
4
<br>
if (!isset($_GET['onlyHappensFromHTACCESS'])) {<br>
    //Our previous code here<br>
}<br>

Since our page exits every time if we run our own code, the ‘else’ for the above statement can be a plain HTML page. Here’s what I use.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<br>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><br>
<html><br>
<head><br>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" /><br>
  <title>Image Denied</title><br>
  <style type="text/css" media="screen"><br>
    body {<br>
        background-color: #ccc;<br>
        font-family: Helvetica, Arial;<br>
    }<br>
    #wrapper {<br>
        margin: 30px auto;<br>
        background-color: #ffffff;<br>
        -moz-border-radius: 15px;<br>
        -webkit-border-radius: 15px;<br>
        border-radius: 15px;<br>
        width: 800px;<br>
        padding: 20px;<br>
    }<br>
  </style><br>
</head><p></p>
<p><div id="wrapper"><br>
  <h3>Access Denied!</h3><br>
  <p>You have tried to access an image, but due to security reasons, you cannot view the image.</p></p>
<p>  <p>If you wish to use the image you requested, please contact me.</p><br>
</div><br>
</html><br>
</p>

Session timer

We’ll also add in a two-second “timer” to ensure the user visited one of our pages first.

In each page you are going to use (index.php in our case), add a simple session variable we can check. Here’s an example:

1
2
3
<br>
session_start();<br>
$_SESSION['lastcheck'] = time();<br>

Then, in our image.php, we need to check this variable, and see if it’s within our allotted time frame. Here’s what I have:

1
2
3
4
5
6
7
8
<br>
function goodTiming() {<br>
    $n = time();<br>
    session_start();<br>
    if ($n - $_SESSION['lastcheck'] > 2 )<br>
        return false;<br>
    return true;<br>
}<br>

Of course, if you’re using a session earlier, you don’t need to start it in this function. Now, the final step is to add it into the image.php checks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<br>
if (!isset($_GET['onlyHappensFromHTACCESS'])) {<br>
   $_GET['f'] = "pictures/" . $_GET['f'];<br>
    $type = getFileType($_GET['f']);<br>
    if (acceptableType($type)) {<br>
        if (goodTiming()) {<br>
            header("Content-type: $type");<p></p>
<p>         echo file_get_contents($_GET['f']);<br>
            exit;<br>
        }<br>
    }<br>
    header('HTTP/1.1 403 Forbidden');<br>
    exit;<br>
}<br>
</p>

Now that we’ve done all of this, our images are pretty much safe. Of course, there are still ways to get it, but there is no 100% way to safeguard your images. If you’ve got it on the internet, it can be retrieved. But, this will at least deter the simple attempts.

Full code source

image.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<br>
<?php<br>
if (!isset($_GET['onlyHappensFromHTACCESS'])) {<br>
   $_GET['f'] = "protectedImages/" . $_GET['f'];<br>
    $type = getFileType($_GET['f']);<br>
    if (acceptableType($type)) {<br>
        if (goodTiming()) {<br>
            header("Content-type: $type");<p></p>
<p>         echo file_get_contents($_GET['f']);<br>
            exit;<br>
        }<br>
    }<br>
    header('HTTP/1.1 403 Forbidden');<br>
    exit;<br>
}</p>
<p>function getFileType($file) {<br>
  if (function_exists("mime_content_type"))<br>
    return mime_content_type($file);<br>
  else if (function_exists("finfo_open")) {<br>
    $finfo = finfo_open(FILEINFO_MIME_TYPE);<br>
    $type = finfo_file($finfo, $file);<br>
    finfo_close($finfo);<br>
    return $type;<br>
  }<br>
  else {<br>
    $types = array(<br>
      'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',<br>
      'gif' => 'image/gif', 'bmp' => 'image/bmp'<br>
    );<br>
    $ext = substr($file, strrpos($file, '.') + 1);<br>
    if (key_exists($ext, $types)) return $types[$ext];<br>
    return "unknown";<br>
  }<br>
}</p>
<p>function acceptableType($type) {<br>
    $array = array("image/jpeg", "image/jpg", "image/png", "image/png");<br>
    if (in_array($type, $array))<br>
        return true;<br>
    return false;<br>
}</p>
<p>function goodTiming() {<br>
    $n = time();<br>
    session_start();<br>
    if ($n - $_SESSION['lastcheck'] > 2 )<br>
        return false;<br>
    return true;<br>
}</p>
<p>?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><br>
<html><br>
<head><br>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" /><br>
  <title>Image Denied</title><br>
  <style type="text/css" media="screen"><br>
    body {<br>
        background-color: #ccc;<br>
        font-family: Helvetica, Arial;<br>
    }<br>
    #wrapper {<br>
        margin: 30px auto;<br>
        background-color: #ffffff;<br>
        -moz-border-radius: 15px;<br>
        -webkit-border-radius: 15px;<br>
        border-radius: 15px;<br>
        width: 800px;<br>
        padding: 20px;<br>
    }<br>
  </style><br>
</head></p>
<p><div id="wrapper"><br>
  <h3>Access Denied!</h3><br>
  <p>You have tried to access an image, but due to security reasons, you cannot view the image.</p></p>
<p>  <p>If you wish to use the image you requested, please contact me.</p><br>
</div><br>
</html><br>
</p>

index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<br>
<?php session_start(); $_SESSION['lastcheck'] = time(); ?><br>
<html><br>
<head><br>
    <title>Page Title</title><br>
    <style type="text/css"><br>
        .image {<br>
            overflow: hidden;<br>
            position: relative;<br>
            float: left;<br>
        }<br>
        .image .cover, .image .cover img {<br>
            position: absolute;<br>
            top: 0px;<br>
            left: 0px;<br>
            width: 100%;<br>
            height: 100%;<br>
        }<br>
    </style><br>
</head><br>
<body><br>
    <div class="image"><br>
        <img src="image.php?f=image.jpg" alt="Image" /><br>
        <div class="cover"><img src="imageCover.gif" alt=""  /></div><br>
    </div><br>
</body><br>
</html><br>

.htaccess in main folder

1
2
3
4
5
<br>
RewriteEngine on<br>
RewriteCond %{HTTP_REFERER} ^$<br>
RewriteCond %{SCRIPT_FILENAME} image\.php<br>
RewriteRule (.*) image.php?onlyHappensFromHTACCESS=denied [QSA,L]<br>

.htaccess in protectedImages folder

1
2
3
4
5
6
7
8
<br>
#Prevent directory listing<br>
Options -Indexes<p></p>
<p>#Prevent images from being viewed<br>
<Files *><br>
  deny from all<br>
</Files><br>
</p>

Feel free to post comments!

Tudo sobre expressões regulares do MySQL ao PHP

Motivo de adoração por uns e terror por outros as expressões regulares são ferramentas que podem auxiliar e descomplicar a vida de muitos developers. Neste material que separmos em inglês você poderá aprender como funciona e aprender mais sobre as famosas REGEX. Continue reading