@jkon, regarding Databases queries I think that I am using the recommended way, here is an example:

try {
    $query          = 'INSERT INTO
                        requests (
                            `request_id`, `email`, `ip`
                        )
                        VALUES (
                            :request_id, :email, :ip
                        );';
    $stmt           = $dbconnection->prepare($query);
    $stmt->bindParam(':request_id', $request_id, PDO::PARAM_INT);
    $stmt->bindParam(':email', $email, PDO::PARAM_STR);
    $stmt->bindParam(':ip', $ip, PDO::PARAM_STR);
    $stmt->execute();
} catch(PDOException $exception) {
    $_SESSION['ERROR_CODE'] = $exception->getCode();
    $_SESSION['ERROR_MSG']  = $exception->getMessage();
}

Sorry regarding my terminology, maybe it is misleading.

Till now in most of the cases I am dealing with this parameters types:

  1. Integers(Numbers, IDs), that I secure them with
    $id = (int)$_POST['parameter'];

  2. Strings(Article Titles, Names), after some tests this functions fits my needs, but I am not sure if it is really secure!
    $title = strip_html_tags($_POST['parameter']);
    https://csiphp.com/blog/2016/05/02/stop-writing-your-own-strip-tags/

  3. Strings(Comments, Article contents, Profile description).
    In this scenarion I don't know how to secure this kind of information.
    To let the users adding securely some links, ul, li etc(pretty much the tags that allow daniweb editor).
    I have read some cases that the attacker can add malicious codes even on the image like:
    <img SRC=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>

Could you share a function/class that is mainly used on this cases?

Thank you!

Hello,

With just this information I can't say exactly where may be your issue.
Can I ask you if dropzone JS has be called on your page?

Hello,

After searching over the internet how to secure a web application(forms) in PHP,
in most of the cases were just suggestions not a short and real example.

In some cases is suggested to use strip_tags( trim( $_POST['PARAMETER'] ) );
but when you have some special inputs like comments field
htmlentities ( trim ( $_POST[ ‘comment’ ] ) , ENT_NOQUOTES ); is suggest.

Maybe there is a useful example (custom made function) to achieve standard safe methods without introducing complicated libraries like HTMLPurifier into the application.

Thank you for your time!

Hello,

What about the security of this method, is it considered SAFE?!
If not how it can be secured.

Thank you!

Also you should consider to start using mysqli*

I managed to change the code as suggest, for the moment it seems to be working.
All the uploaded images are storen in a hidden input divided by a ,

Here is a simple version of the code to help everyone else in the future

<form id="appointment-form" class="box-body no-padding">
    <input name="firstname" type="text" />
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 no-padding">
        <div class="form-group">
            <form id="uploadInput" method="post" action="upload.php" class="dropzone">
                <div class="fallback">
                    <input name="file" type="file" />
                </div>
            </form>
            <input name="attached_files" value="" type="hidden" />
        </div>
    </div>
  <button type="button" class="btn btn-default btn-flat">
     <i class="fa fa-plus"></i> Add
  </button>
</form>
<script type="text/javascript">
        jQuery(".dropzone").dropzone({
            success : function(file, response) {
                //console.log(file);
                //console.log(response);
                if (response['target_file'] != '') {
                    var currentValue = jQuery("#appointment-form input[name='attached_files'").val();
                    if (currentValue == '') {
                        jQuery("#appointment-form input[name='attached_files'").val(response['target_file']);
                    } else {
                        jQuery("#appointment-form input[name='attached_files'").val(currentValue + ", " + response['target_file']);
                    }
                }
            }
        });
    </script>

upload.php

<?php
    header('Content-type: application/json');
    $ds          = DIRECTORY_SEPARATOR;  //1
    $storeFolder = 'files/tmp';   //2
    if (!empty($_FILES)) {
        $tempFile       = $_FILES['file']['tmp_name'];      
        $targetPath     = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
        $path_parts     = pathinfo($_FILES["file"]["name"]);
        $extension      = $path_parts["extension"];
        $targetFile     = $targetPath . time() . '.' . $extension;
        move_uploaded_file($tempFile, $targetFile); //6
        echo json_encode(['target_file' => $targetFile]);
    }
?>

Thank you cereal :)

cereal commented: you're welcome :) +15

Hello,

In my project I have a form with many inputs and one object is using DropzoneJS to attach files.
Since I store all the inputs when I post the form I need somehow to read the file names of the uploaded files in my server,
currently I can only get the list of the original filename of the files that are uploaded.
For many reasons when a file is uploaded I am giving it a random name with time() function.

A part of my HTML form

<form id="appointment-form" class="box-body no-padding">
    <input name="firstname" type="text" />
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 no-padding">
        <div class="form-group">
            <form id="uploadInput" method="post" action="upload.php" class="dropzone">
                <div class="fallback">
                    <input name="file" type="file" />
                </div>
            </form>
        </div>
    </div>
  <button type="button" class="btn btn-default btn-flat">
     <i class="fa fa-plus"></i> Add
  </button>
</form>

upload.php

<?php
$ds          = DIRECTORY_SEPARATOR;
$storeFolder = 'files/tmp';

if (!empty($_FILES)) {
         $tempFile   = $_FILES['file']['tmp_name'];             
    $targetPath     = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
    $path_parts     = pathinfo($_FILES["file"]["name"]);
    $extension      = $path_parts["extension"];
    $targetFile     = $targetPath . time() . '.' . $extension;
    echo $targetFile;
    move_uploaded_file($tempFile, $targetFile);
}
?>

How can I store the $targetFile in my HTML form so I can read them when I post the main form?!

Someone else helped me to fond a solution.
Here is all the logic.

$source = '
  <img src="1.jpg"/>' . "\n" . '
  <img src="2.jpg" alt="2" />' . "\n" . '
  <img name="omg" src="3" asd="sdfgf" alt="2.jpg">' . "\n" . '
  <img src="4.jpg" alt="4" width="1107" height="1626"/>' . "\n" . '
  <img src="5.jpg" id="zz" alt="5" >' . "\n" . '
  <img src="6.jpg" alt="6" width="1229" height="922" />' . "\n" . '
  <img src="7.jpg" alt="7"/>' . "\n" . '
  <img src="8.jpg" alt="8" width="807" height="1117">
';

$pattern = '~(<img .*?src="([^"]+)" ?.*?(alt="([^"]+)")?.*?>)~';
$replacement = '<a href="$2" data-fancybox="image-popup" data-caption="$4">$1</a>';

$result = preg_replace($pattern, $replacement, $source);

echo 'SOURCE:<br />' . nl2br(htmlspecialchars($source)) . '<br /><br /><br />';
echo 'RESULT:<br />' . nl2br(htmlspecialchars($result));

Thank you @AndrisP
This code works well, but it may needs some improvements.

In some cases the editor of the website puts some other parameters to the image (width, height)
on this cases you code does not work.

Could the above suggestion be improved?!

Hello,

I am trying to manipulate a HTML content stored in a php variable.
The logic is as follows: The variable should be checked if it contains an <img ... /> tag and if a tag is found it should be wraped in an tag and some parametres of the a tag should be read from the img tag.
The code in the end enables the fancybox plugin to all images, this can be done even via JS, but in my case I would like to have the content ready as it would be served to the visitor.

Example:
The initial content.

$content = 'This content has two images
<img src="/images/img1.jpg" alt="Image 1" />
<img src="/images/img2.jpg" alt="Image 2" />';

The final content

$content = 'This content has two images
    <a href="/images/img1.jpg" data-fancybox="image-popup" data-caption="Image 1">
        <img src="/images/img1.jpg" alt="Image 1" />
    </a>
    <a href="/images/img2.jpg" data-fancybox="image-popup" data-caption="Image 2">
         <img src="/images/img2.jpg" alt="Image 2" />
    </a>';

Thank you!

Sorry for my insecurities, but as I am not very good on this topics I got confused.
How can I deal with the query when I have many parameters like gjendja_id, or fname as you called it in your example?
Is the following code the correct way to implement this logic?!

$sql = "SELECT * FROM `names` WHERE %s %s";
if($int > 0)
{
    $condition = "`fname` = :fname";
    $data = [':fname' => 'klaus'];
}
else
{
    $condition = "`fname` IS NOT NULL";
    $data = NULL;
}

if($int2 > 0)
{
    $condition2 = "`fname2` = :fname2";
    $data2 = [':fname2' => 'klaus2'];
}
else
{
    $condition2 = "`fname2` IS NOT NULL";
    $data2 = NULL;
}

$stmt = $db->prepare(sprintf($sql, $condition, $condition2));
$stmt->execute($data, $data2);

What about PDO::PARAM_INT, PDO::PARAM_STR etc, is a big deal to not specify them, at first sight it might cause slower performance.

Thank you for the fast reply.
This was the way I wanted to avoid :(
I have many other parameters like $gjendja_id, so the only solution is to have many if else conditions for the($stmt = $dbconnection->prepare())?!
I think there must be a way to deal with this kind of query.

Hello,

Recently I am starting to code my scripts in PDO method to manage the information in a mysql database.
In this case I am having an issue how to use the best practice conditions when dealing with a POST int value.

With the posted values I am making a select query, a short version of it is as follows

if( isset($_POST['gjendja_id']) ){
    $gjendja_id     = intval($_POST['gjendja_id']);
    if( $gjendja_id > 0 ){
        $gjendja_id = $_POST['gjendja_id'];
    }else{
        $gjendja_id = 'IS NOT NULL';
    }
}else{
    $gjendja_id     = 'IS NOT NULL';
}

The query that would be executed

try {
    $counter    = 1;
    $response   = '';
    $stmt       = $dbconnection->prepare('SELECT a.dokumenti, a.datafillimit, a.datambarimit, b.programi, c.lloji_diplomes, d.ial, e.akreditimi FROM programet_akreditimet AS a INNER JOIN programet AS b ON a.programi_id = b.id INNER JOIN programet_llojet_diplomave AS c ON b.lloji_diplomes_id = c.id INNER JOIN institucionet AS d ON b.ial_id = d.id INNER JOIN akreditimet_llojet AS e ON a.lloji_akreditimit_id = e.id WHERE a.datambarimit >= CURDATE() AND b.gjendja_id =:gjendja_id AND d.gjendja_id = 1 AND a.trashed = 0 ORDER BY d.ial ASC;');
    $stmt->bindParam(':gjendja_id', $gjendja_id, PDO::PARAM_INT);
    $stmt->execute();
    $result     = $stmt->fetchAll();
    foreach($result as $row){
        $response   .='';
        $counter++;
    }
    $response       = array('error_code' => '0', 'response' => $response);
}catch(PDOException $exception){
    $response       = array('error_code' => '1', 'response' => 'Gabim gjatë kërkimit në databazë.');
    //$exception->getMessage();
}

In this case I would have two scenarios
1- When the value of gjendja_id > 0 the condition would be b.gjendja_id =:gjendja_id(1, 2, 3, 4, ....)
2- When the value of gjendja_id < 1 the condition would be b.gjendja_id =:gjendja_id(IS NOT ...

Dani thank you for your reply.
I understand the theory how it works, but I wanted a detailed example.

There are a lot of information in google and a lot of methods to improve the performace
of you code and I am getting very confused. Even now to told me something new memcached + redis :O

If you can plz post here a full example how can this be done!
Thank you.

Hello,
Recently I am dealing with bad performance in an php application that I have build,
googling this issue I found out that using services like memcached you can archive a huge performance improvements.

The weird thing comes when I try to find a very good and detailed example I failed to find something.
Could someone helps me giving a good url or example using php + mysql + memcached?!

Thank you!

Thank you Mangel,
I solved my problem with a tricky procedure.
Before adding the excel content I use phpexel load,
to load a template created in MS Office that has the header image as I wanted,
after inserting the rows inside the loaded template I save it where I wanted to :)

How your are uploading files in your server?!
Are your using a root account, if so check the files permissions.

As you are using Joomla I suggest you to use Profiles to upload files to your site.
http://www.mooj.org/en/extensions/components/profiles-joomla-web-file-manager.html

Hello,
Recently I am using phpexcel and afer many tries I wasn't able to find out how to
make a document with a image in its header.
Here is a simplified code that I am using. Can someone helps me with this issue?!

<?php
require_once 'PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objDrawing = new PHPExcel_Worksheet_HeaderFooterDrawing();
$objDrawing->setPath('header.jpg');
$objPHPExcel->getActiveSheet()->getHeaderFooter()->addImage($objDrawing, PHPExcel_Worksheet_HeaderFooter::IMAGE_HEADER_RIGHT);
$objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddHeader("&C&G");
$objPHPExcel->setActiveSheetIndex(0)->setCellValueExplicit('A1',  'CODICE PRATICA');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter      = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save('test.xlsx');
?>

Thank you guys for your support!
As my level of knowledge is not very good, it will take me some time to understand and test this examples.

I have seen the hierarchical method is better then the structure that I am using, but I can't understand how it works. How lft and rgt are calculated when you enter a new record on the table.

Yes diafol,
Maybe my explanation was not very clear in the begining.
My issue is with the new id's of the folders that are copy/pasted(select/inserted),
as you may be clear now its somehow complicated.

Days before I have seen an example to doing this the recursive function, but I am not finding that anymore...

Also I want to thank you anyway, because in most of my issues you have saved me :)

The folder_id tells the id of the parent folder, if it is 0 is a root folder
On this post I am posting just the columns that for me are essential for the procedure
An example of the rows
people_folders
1, 0, Main Folder
2, 0, Main Folder II
3, 1, Subfolder I --This folder is under Main Folder
4, 3, Subfolder III --This folder is under Subfolder I

people_documents
1, 3, File I
2, 3, File II
3, 4, File III

For example if I copy Main Folder with ID = 1 to Main Folder II the information on the database would be this

people_folders
1, 0, Main Folder
2, 0, Main Folder II
3, 1, Subfolder I --This folder is under Main Folder
4, 3, Subfolder III --This folder is under Subfolder I

5, 2, Main Folder
6, 5, Subfolder I
7, 6, Subfolder III

people_documents
1, 3, File I
2, 3, File II
3, 4, File III

4, 6, File I
5, 6, File II
6, 7, File III

Hello to everyone,
Currenty I have a php project that uploads files to the server and save some extra information into the database.
My problem is that I want to make a feature that copies a folder structure with files included to a database.

I am trying to copy the folder structure, but the issue is that I cant follow the relationships with the new ids.

The main structure of the table is like this

CREATE TABLE `people_folders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `folder_id` int(11) NOT NULL COMMENT 'Here is stored the root folder id',
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

CREATE TABLE `people_documents` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `folder_id` int(11) NOT NULL COMMENT 'Here is stored the id of the folder that the file is stored',
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

To be more clear, I am trying to do something that Joomla! do copy menus
https://docs.joomla.org/images/8/81/Help30-colheader-batch-process-articles.png

I have write something on this attach, hope it will help you.
This problem had happen to me every time that I use ftp transfers as filezilla, wincsp.
This softwares usually changes the encode of the files.

My suggestion is to use Notepad++.
Another issue might be you hosting fault, on mine this works very well.
On the screenshoots that I have attached inside the archive, please see carefully what encodes I have used.

Good job diafol, you are the best as always!

If you post the original file would be much helfull for everyone to give you an advice!
Maybe is somehow related with php configuration issues...

Hello to everyone,
Currently I am building a web application in php.
The users have option to upload/download files into the server folders, but the issue is that they
should also edit at least some types of documents(Word & Excel) that are uploaded online via the browser.

I have seen the Google offers Google Docs and also Microsoft has its own online document editor,
but they use their storange to save files.

I want some kind of php script that gives you the ability to edit this documents and after that
saves them to my own host.

Could someone suggest me how to do this?!

Hello,
Currently I am using my computer as a webserver, as I own an IP I have made the config to access it from outside.
So now I can access my php sripts via http://MY_PUBLIC_IP:PORT/site.php
The weird thing is that I cant get the visitors IP
This script is working very good on sites with no ip on the url. Could someone help me with this issue?!

function getUserIP(){
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];
    if(filter_var($client, FILTER_VALIDATE_IP)){
            $ip = $client;
        }elseif(filter_var($forward, FILTER_VALIDATE_IP)){
            $ip = $forward;
        }else{
            $ip = $remote;
    }
    return $ip;
}

Wow that works now!
Thank you a lot and have a nice day :)