Quantcast
Channel: PHP Freaks: PHP Help
Viewing all 13200 articles
Browse latest View live

very short code [ mysql_result to mysqli please help]

$
0
0

started learning php last week, at first didn't know anything about it so used mysql, now yesterday reading some article i saw that i should be using mysqli instead of mysql, so i changed all the code for my registration and login pages every works fine. However can't figure out the mysql_result to mysqli, couldn't find it on google too

the code:
the error im getting:
Warning: mysql_result() expects parameter 1 to be resource, object given in /Applications/XAMPP/xamppfiles/htdocs/index.php on line 12

<?php
require 'conect.php';

$user_ip = $_SERVER['REMOTE_ADDR'];

function update_count()
{ global $dbconnect;

$query = "SELECT count FROM hits_count";
if ($query_run = mysqli_query($dbconnect, $query))
{
$count = mysql_result($query_run, 0, 'count');
echo $count;
}
}
update_count();
?>

 


Unable to locate parse error.

$
0
0

Ok I have a small issue. I know it's because of my lack of php knowledge and it's a small mistake but I can't seem to see it.

 

I am getting this error in Coda 2.0

 

Parse error: parse error, expecting `','' or `';'' in - on line 216
Errors parsing -

 

Which is referring to this line of code. All I did was  add echo and wrap <td> tags around it and it starting throwing the error.

echo "<td>"getGraphic($realIndex1, $aqiLevels, $aqiGraphic, $imagesDir)"</td>";

Here is this complete little script that the line above is extracted from.

<table style="margin: 0px auto;" border="0" width="80%">
     <tbody><tr><?php
  if ($useAQI) {  //  Show Air Quality Index - PLASE YOUR CODE IN PLACE OF THIS SECTION AND START HERE Removing the line above too!
?>
<?php
if ($realValue1 == "") {
  echo "";
} else {
  echo "<td style=\"text-decoration: none; text-align: center;\"><span style=\"font-size:90%; \">Quality<br/>Index<sup>6</sup>:</span><span style=\"font-size: 150%; font-weight:bold;\"><br/>" .$realValue1."</span></td>";
}
if ($realValue1 == "") {
  echo "Data Not<br />Available</span><br /><br /><img src=\"./ajax-images/AQI0.jpg\" width=\"75\" height=\"75\" alt=\"Data Not Available\" />";
} else {
 echo "<td>"getGraphic($realIndex1, $aqiLevels, $aqiGraphic, $imagesDir)"</td>";
}
?>
       <td style="text-decoration: none; text-align: center;"><span style="font-size:85%;"><?php langtrans('Density'); ?>:<br />
        <?php echo $airdensity . " kg/m<sup>3</sup>" ?></span></td>

        </tr>
<?php } // end $showAQI - PLASE YOUR CODE INPLACE OF THIS SECTION AND END HERE  ?></td>
     </tr>
    </tbody></table>

What is it that I am not seeing?

 

-Thanks

remove substring from end of string

$
0
0

I want to remove the last ' AND' from my string im using to build a mySQL query. I thought using rtrim was the way to go but either im wrong or im not using it correctly:

foreach ($dupArray as $k => $v) {
			$whereStr = $whereStr . "$k='$v' AND ";
		}
		
		rtrim($whereStr, "AND");
		echo $whereStr;

Anyone got any ideas? I swear ive seen this done else where but i cant find any examples

JS or PHP problem? Not sure

$
0
0

Hello everybody!

 

I'm writing an application that, among other things, allows users to send messages to admin of the page. Then, admin access it trough their CMS. After they successfully send the message, a window saying that the message was sent successfully has to appear. After clicking on OK, the message fades out with JQuery.

 

This is the code of the message

<input type='hidden' class='hidden-elem' value='<?php if(isset($_SESSION['prikaz']))
                                                            {
                                                               echo 'prijava';
                                                               unset($_SESSION['prikaz']);
                                                            } ?>'>
      <div class='prijava'>
        <div class='welcome'>
        <?php
           if(isset($_SESSION['poslana']))
           {
              ?>
              <p class='uspjeh'>Vaša poruka je uspješno poslana</p>
              <p><span>Sa poštovanjem,</span><span>Tim Cvjećarnice Oliva.</span></p>
              <img src='images/ikone/success.png' class='ukras'>
              <?php
              
              unset($_SESSION['poslana']);
           }
           elseif(isset($_SESSION['dobrodoslica']))
           {
              ?>
              <h1>Dobrodošlao/la na stranicu <span>Cvjećarnice Oliva</span></h1>
              <p>Na ovoj stranici možete naći najbolji asortiman cvijeća i ukrasnih aranžmana u Osijeku. Ako vas
                 zanima nešto više o pojedinom cvijetu koji vam se sviđa, za vas smo pripremili i članke, koji na zanimljiv način opisuju i govore o cvijeću.
                 Nadamo se da ste zadovoljni. Također, možete nas osobno posjetiti na našoj adresi, Vjenceslava Hodaka 16, Osijek. Veselimo se budućem susretu!
              <span>Sa poštovanjem,</span><span>Tim Cvjećarnice Oliva.</span>
              </p>
              <img src='images/dekoracija.png' class='ukras'>
              <?php
              
              unset($_SESSION['dobrodoslica']);
           }
           elseif(isset($_SESSION['fail']))
           {
              ?>
                 <p class='fail'>Došlo je do pogreške. Ispričavamo se na neugodnosti i molimo da, nakona nekog vremena ponovno pokušate. Hvala vam na strpljenju.</p>
                 <p><span>Sa poštovanjem,</span><span>Tim Cvjećarnice Oliva.</span></p>
                 <img src='images/ikone/close.png' class='ukras'>
              <?php
              
              unset($_SESSION['fail']);
           }
         ?>
         <button>Ok</button>
        </div>
        <?php
           
        ?>
      </div>

The language is croatian and the content is irrelevant. The main thing is, if $_SESSION['prikaz'] is set, then the value of the hidden field is populated with the string 'prijava'. The $_SESSION['prikaz'] gets populated in antoher script and he isn't the problem beacuse, he is set every time and in every situation. That input field is important for the JQuery code that follows...

$('.prijava').hide();
   
      var tip = $('.hidden-elem').attr('value');
       if(tip == 'prijava')
       {
	      $('.prijava').show();
		  $('.prijava .welcome button').click(function()
		  {
		     $('.prijava').fadeOut(500);
		  });
       }

JQuery then takes the value of the value attribute of .hidden-elem and checks if its equal to 'prijava'. If it is, then it shows the <div class='prijava'>.

 

The problem is this. When the user is logged in, the messages shows with no problem. But when the user is not logged in, the message does not show, but it gets proccessed with inline style='display:none'. The value of the .hidden-elem is populated with the string 'prijava' but $('hidden-elem').attr('value') doesn't return the value of that hidden input element, thus if(tip == 'prijava') doesn't evaluate to true.

 

I don't understand how can one behaviour be valid for, when the user is logged in and when he isn't if the script is operating with identical data in both cases?

 

I know this is a long post and I thank anyone who tries to solve it.

Problem with PHP/SQL Select where

$
0
0

Hi All,

 

I'm fairly new to php and after spending many hours searching forums i thought this would be the best place to post!

 

I have a table, pt_roomcount with four fields, index, room, category, totcount

 

When I run this SQL in PHPMYADMin I get the results I require (2 results - "Paints" and "Patio")

)

 

"SELECT * FROM `pt_roomcount` WHERE `room`='Outdoors' group by `category`"

 

But when I run it in PHP using the following I only get one results (Patio - the lata of the two)

 

 <?php
 $data = mysql_query("SELECT * FROM `pt_roomcount` WHERE `room`='Outdoors' group by `category` ")
 or die(mysql_error());
 
 $info = mysql_fetch_array( $data );
 
 while($info = mysql_fetch_array( $data ))

 {
 
//This bit is irrelevant, its working fine
 Print "<li style='width:210px;'>";
 Print "<a href='/shopping/".$info['room']."' style='padding:2px 0px 2px 0px;'>".$info['category']." (".$info['totcount'].")</a></li>";

   
 }

 
 ?>
 

 

Please can you advise?

 

Thanks in advance!

Chris

 

Need help making this backward compatible until php upgrade

$
0
0

Can some help me make this code backward compatible?

 

 

This code works with php 5.3 and above. I need it to work with 5.2.17.

$columns = 'col1, col2, col3';
$values = '$value1, $value2, $value3';

$result = implode(
', ',
array_map(
function ($c, $v) {
return $c . ' = ' . $v;
},
explode(',', $columns),
explode(',', $values)
)
);

var_dump($result); //this returns: col1 = $value1, col2 = $value2, col3 = $value3

Cheers.

 

Query based on option in dropdown list

$
0
0

I want to see the content of a query on a webpage based on an option selected in a dropdown list (sort of filter function)

I made following javascript and PHP script but doesn't receive the desired result (no records).

What do I do wrong ?

< script type="text/javascript">
function MM_callJS(jsStr) { //v2.0
var opd = document.form1.opdstatus.options[document.form1.opdstatus.selectedIndex].text;
alert (opd);
< ?php
mysql_select_db($database_myconnection, $myconnection);
if (opd == "Started") {
$query_dashboard = "SELECT * FROM dashboard WHERE Status = 'ST' ORDER BY Deadline ASC";
$dashboard = mysql_query($query_dashboard, $myconnection) or die(mysql_error());
$row_dashboard = mysql_fetch_assoc($dashboard);
$totalRows_dashboard = mysql_num_rows($dashboard);
}
if (opd == "Finished") {
$query_dashboard = "SELECT * FROM dashboard WHERE Status = 'FN' ORDER BY Deadline ASC";
$dashboard = mysql_query($query_dashboard, $myconnection) or die(mysql_error());
$row_dashboard = mysql_fetch_assoc($dashboard);
$totalRows_dashboard = mysql_num_rows($dashboard);
}
if (opd == "Pending") {
$query_dashboard = "SELECT * FROM dashboard WHERE Status = 'PN' ORDER BY Deadline ASC";
$dashboard = mysql_query($query_dashboard, $myconnection) or die(mysql_error());
$row_dashboard = mysql_fetch_assoc($dashboard);
$totalRows_dashboard = mysql_num_rows($dashboard);
}
if (opd == "All") {
$query_dashboard = "SELECT * FROM dashboard ORDER BY Deadline ASC";
$dashboard = mysql_query($query_dashboard, $myconnection) or die(mysql_error());
$row_dashboard = mysql_fetch_assoc($dashboard);
$totalRows_dashboard = mysql_num_rows($dashboard);
}
?>
}
< /script>

 

PHP Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in

$
0
0

So I am getting this error and I don't understand what I'm doing wrong.

 

PHP Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in \\PDC3\sites\c\cupboard2stomach.com\public_html\index.php on line 102

 

 

<?php


    $recipes = mysql_query("
        SELECT `id`,`name`, `image`, `description`
        FROM `recipe` 
ORDER BY RAND() LIMIT 4;
    ");


while ($recipe = mysql_fetch_assoc($recipes)) {
echo '<section id="recipeslide">';




echo "<a href='php/recipe.php?id=$recipe_id'><img src=\"{$recipe['image']}\" height=100 width=100 /></a><br />";
echo '</section>';


    }


echo '</section>';


echo '<section id="indexcenter">';


$recipegallery = mysql_query("
        SELECT `id`,`name`, `image`, `description`
        FROM `recipe` 
ORDER BY RAND () LIMIT 10;
    ");


while ($recipegallery = mysql_fetch_assoc($recipegallery)) {
echo '<section id="recipegallery">';
$recipe_id = $recipegallery['id']; 
echo $recipegallery['name'];
echo '<br />';
echo "<a href='php/recipe.php?id=$recipe_id'><img src=\"{$recipegallery['image']}\" height=100 width=100 /></a><br />";


echo '<section id="description">';
echo $recipegallery['description'];
echo '</section>';


} 


echo '</section>';
echo '</section>';
?>

I have two queries running;

 

The first query pulls out 4 random recipes and displays them in a row at the top of the page.

 

The second one is meant to pull 10 random ones out that are display in a main container on the home page but at the moment it's only displaying one recipe and displaying that error.

 

Any thoughts?

 


Timezone error : Invalid date.timezone value 'Asia/Calcuttaextension', we selected the timezone 'UTC' for now

$
0
0

Hello,

This is my first post on the website. Sorry, I din't went to the introduction section straight up. I am getting the following error on the website. The website was working fine before upgrading the php version. It would be a great help if someone could help me sort this out.

I have searched many other forum and this seems to be right place to ask for help. You guys seems to have a giant active community.

 

I don't have much knowledge about the php and stuff and I can't pay my developer to fix this :(

 

Warning: Unknown: Invalid date.timezone value 'Asia/Calcuttaextension', we selected the timezone 'UTC' for now. in Unknown on line 0

Fatal error: Uncaught exception 'Exception' with message 'DateTimeZone::__construct() expects exactly 1 parameter, 0 given' in /home/user/public_html/fw/init.php:59 Stack trace: #0 /home/user/public_html/fw/init.php(59): DateTimeZone->__construct() #1 /home/user/public_html/fw/init.php(82): fw::connect(Array) #2 /home/user/public_html/application.php(17): fw::config(Array) #3 {main} thrown in /home/user/public_html/fw/init.php on line 59

# Database
        require FW.'db'.DIRECTORY_SEPARATOR.DB_ADAPTER.'.php';
        
        db::connect(DB_HOST, DB_USER, DB_PASS);
        db::select_db(DB_NAME);
        
        # Timezone
        if(class_exists('DateTime'))
        {
            $date = new DateTime;
            
            if(method_exists($date, 'getOffset'))
            {
                $offset = $date->getOffset()/60;
                
                $minutes = abs($offset);
                $hours = floor($minutes/60);
                $minutes -= $hours*60;
                
                db::query('SET time_zone="'.sprintf('%+d:%02d', $hours*($minutes<0?-1:1), $minutes).'"');
            }
        }
    }

Problem storing data from this form fileds

$
0
0

I have been practicing mysql and then i have came accross a issu that i can't solve ... i have also asked in different forum and dont find any suitable ans ..... so here i am ...

 

I am making a large form that will be able to store information from user in the database .. I have managed to make and store data from simple form fields like Name, Country , Age , Interest and etc using mysql and php ...

I have a table called users in my database which have approximate 15 column for different data like Name , Country , Age etc ....

Now I have added this from field to my from and confused about how to store data from this field ..

here is the img of my form ....

 

temp.jpg

 

the above table says.....each separate user will have separate employment histroy which will be submitted through row 1-4 and Employer's Name , Country , Position etc  (4 row of them) will go in columns called emp_name , emp_country, emp_pos etc. .

 

Even if i create a different table ex - emp_history then how to store data from this form for each user ?

than you for understanding ...

 

 

 

Need Help In Fetching File Name Title - Image Gallery

$
0
0

Hello guys,

 

First of all thank you for your support and I have learned many new things from this forum. Secondly, I am again facing an issue which I want to take help from you guys.

 

I have a php image hosting script and when I upload images and go to the image page the alt text in that image html source code comes only 'image' while I want to transfer it to the file name.

 

I mean that whenever I upload an image its alt tag is automatically assigned by its file name.but there another issue arrises that my script automatically changes the file title. 

 

here is a demonstration of it.Here is an image of lamborghini with its source file:

 

http://toorhamza.hostingsiteforfree.com/img-51909f559674b.html

 

view-source:http://toorhamza.hostingsiteforfree.com/img-51909f559674b.html

 

Now what should I do, because this will not be good for SEO.

 

Here is my function code if you can find something to help me from here:

<?php
/**
 * Created by Zamfi
 * Image Hosting Script
 * more informations about this script on
 * http://imagehost.iuhu.org
 * Copyright of Zamfirescu Alexandru Costin - © Iuhu 2012 - All rights reserved
 * Copyright notice - Zamfi Image Hosting Script

 * This script and its content is copyright of Zamfirescu Alexandru Costin - © Iuhu 2012. All rights reserved.
 * Any redistribution or reproduction of part or all of the contents in any form is prohibited other than the following:
 * This script is for personal and comercial use only.
 * You may not, except with our express written permission, distribute or commercially exploit the content.
 * You may you transmit it or store it in any other website or other form of electronic retrieval system.
 **/


function filter($data) {
    $data = trim(htmlentities(strip_tags($data)));

    if (get_magic_quotes_gpc())
        $data = stripslashes($data);

    $data = mysql_real_escape_string($data);

    return $data;
}

function limitedChars($string){
    if (preg_match("/[^-a-z 0-9_.-]/i", $string)) {
        return false;
    } else {
        return true;
    }
}

function banIPcheck(){
    $q = "SELECT reason FROM banned_ip WHERE ip LIKE '{$_SERVER['REMOTE_ADDR']}'";
    $result = mysql_query($q);
    if($result && mysql_num_rows($result) > 0) {
        $rowReason = mysql_fetch_assoc($result);
        if(isset($_SESSION['user_id'])) {
            header('Location: logout.php');
        }
        die($rowReason['reason']);
    }
}



function sendMail($address, $username, $subject, $message){
global $site_name;
    require_once('phpmail/class.phpmailer.php');
    //include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded


    $mail             = new PHPMailer();

    //$body             = file_get_contents('contents.html');
    //$body             = eregi_replace("[\]",'',$body);

    $mail->IsSMTP(); // telling the class to use SMTP
    //$mail->SMTPDebug  = 1;                     // enables SMTP debug information (for testing)
    // 1 = errors and messages
    // 2 = messages only
    $mail->SMTPAuth   = true;                  // enable SMTP authentication
    $mail->Host       = PHPMAIL_HOST; // sets the SMTP server
    $mail->Port       = PHPMAIL_PORT;                    // set the SMTP port for the GMAIL server
    $mail->Username   = PHPMAIL_MAIL; // SMTP account username
    $mail->Password   = PHPMAIL_PASSWORD;        // SMTP account password

    $mail->SetFrom(PHPMAIL_MAIL, $site_name);
    $mail->AddReplyTo(PHPMAIL_MAIL, $site_name);
    $mail->Subject    = "$subject - $site_name";
    $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
    //$mail->AltBody($message);
    //$mail->MsgHTML($body);
    $mail->MsgHTML($message);
    //$mail->Body = $message;

    //$usernname = $_SESSION['user_name'];
    //$address = $rowUsers['user_email'];
    $mail->AddAddress($address, $username);

    //$mail->AddAttachment("images/phpmailer.gif");      // attachment
    //$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

    if(!$mail->Send()) {
        return true;
        //echo "Mailer Error: " . $mail->ErrorInfo;

    } else {
        //echo "Message sent!";
        return false;
    }
}

/*
* File: SimpleImage.php
* Author: Simon Jarvis
* Copyright: 2006 Simon Jarvis
* Date: 08/11/06
* Link: http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*
*/

class SimpleImage {

    var $image;
    var $image_type;

    function load($filename) {
        $image_info = getimagesize($filename);
        $this->image_type = $image_info[2];
        if( $this->image_type == IMAGETYPE_JPEG ) {
            $this->image = imagecreatefromjpeg($filename);
        } elseif( $this->image_type == IMAGETYPE_GIF ) {
            $this->image = imagecreatefromgif($filename);
        } elseif( $this->image_type == IMAGETYPE_PNG ) {
            $this->image = imagecreatefrompng($filename);
        }
    }
    function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
        if( $image_type == IMAGETYPE_JPEG ) {
            imagejpeg($this->image,$filename,$compression);
        } elseif( $image_type == IMAGETYPE_GIF ) {
            imagegif($this->image,$filename);
        } elseif( $image_type == IMAGETYPE_PNG ) {
            imagepng($this->image,$filename);
        }
        if( $permissions != null) {
            chmod($filename,$permissions);
        }
    }
    function output($image_type=IMAGETYPE_JPEG) {
        if( $image_type == IMAGETYPE_JPEG ) {
            imagejpeg($this->image);
        } elseif( $image_type == IMAGETYPE_GIF ) {
            imagegif($this->image);
        } elseif( $image_type == IMAGETYPE_PNG ) {
            imagepng($this->image);
        }
    }
    function getWidth() {
        return imagesx($this->image);
    }
    function getHeight() {
        return imagesy($this->image);
    }
    function resizeToHeight($height) {
        $ratio = $height / $this->getHeight();
        $width = $this->getWidth() * $ratio;
        $this->resize($width,$height);
    }
    function resizeToWidth($width) {
        $ratio = $width / $this->getWidth();
        $height = $this->getheight() * $ratio;
        $this->resize($width,$height);
    }
    function scale($scale) {
        $width = $this->getWidth() * $scale/100;
        $height = $this->getheight() * $scale/100;
        $this->resize($width,$height);
    }
    function resize($width,$height) {
        $new_image = imagecreatetruecolor($width, $height);
        imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
        $this->image = $new_image;
    }
}


class login{
function page_protect() {
    session_start();

    global $db;

    /* Secure against Session Hijacking by checking user agent */
    if (isset($_SESSION['HTTP_USER_AGENT']))
    {
        if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
        {
            $this->logout();
            exit;
        }
    }

    // before we allow sessions, we need to check authentication key - ckey and ctime stored in database

    /* If session not set, check for cookies set by Remember me */
    if (!isset($_SESSION['user_id']) && !isset($_SESSION['user_name']) )
    {
        if(isset($_COOKIE['user_id']) && isset($_COOKIE['user_key'])){

            /* we double check cookie expiry time against stored in database */

            $cookie_user_id  = filter($_COOKIE['user_id']);
            $rs_ctime = mysql_query("select `ckey`,`ctime` from `users` where `id` ='$cookie_user_id'") or die(mysql_error());
            list($ckey,$ctime) = mysql_fetch_row($rs_ctime);
            // coookie expiry
            if( (time() - $ctime) > 60*60*24*COOKIE_TIME_OUT) {

                $this->logout();
            }
            /* Security check with untrusted cookies - dont trust value stored in cookie.
/* We also do authentication check of the `ckey` stored in cookie matches that stored in database during login*/

            if( !empty($ckey) && is_numeric($_COOKIE['user_id']) && $this->isUserID($_COOKIE['user_name']) && $_COOKIE['user_key'] == sha1($ckey)  ) {
                session_regenerate_id(); //against session fixation attacks.

                $_SESSION['user_id'] = $_COOKIE['user_id'];
                $_SESSION['user_name'] = $_COOKIE['user_name'];
                /* query user level from database instead of storing in cookies */
                list($user_level) = mysql_fetch_row(mysql_query("select user_level from users where id='$_SESSION[user_id]'"));

                $_SESSION['user_level'] = $user_level;
                $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);

            } else {
                $this->logout();
            }

        } else {
            header("Location: login.php");
            exit();
        }
    }

    // BANNING
    $userBanCheck = mysql_query("SELECT id FROM banned_users WHERE id_user = {$_SESSION['user_id']}");
    if($userBanCheck && mysql_num_rows($userBanCheck) > 0) {
        $this->logout();
    }
}



function EncodeURL($url)
{
    $new = strtolower(preg_replace(' ','_',$url));
    return($new);
}

function DecodeURL($url)
{
    $new = ucwords(preg_replace('_',' ',$url));
    return($new);
}

function ChopStr($str, $len)
{
    if (strlen($str) < $len)
        return $str;

    $str = substr($str,0,$len);
    if ($spc_pos = strrpos($str," "))
        $str = substr($str,0,$spc_pos);

    return $str . "...";
}

function isEmail($email){
    return preg_match('/^\S+@[\w\d.-]{2,}\.[\w]{2,6}$/iU', $email) ? TRUE : FALSE;
}

function isUserID($username)
{
    if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
        return true;
    } else {
        return false;
    }
}

function isURL($url)
{
    if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
        return true;
    } else {
        return false;
    }
}

function checkPwd($x,$y)
{
    if(empty($x) || empty($y) ) { return false; }
    if (strlen($x) < 4 || strlen($y) < 4) { return false; }

    if (strcmp($x,$y) != 0) {
        return false;
    }
    return true;
}

function GenPwd($length = 7)
{
    $password = "";
    $possible = "0123456789bcdfghjkmnpqrstvwxyz"; //no vowels

    $i = 0;

    while ($i < $length) {


        $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);


        if (!strstr($password, $char)) {
            $password .= $char;
            $i++;
        }

    }

    return $password;

}

function GenKey($length = 7)
{
    $password = "";
    $possible = "0123456789abcdefghijkmnopqrstuvwxyz";

    $i = 0;

    while ($i < $length) {


        $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);


        if (!strstr($password, $char)) {
            $password .= $char;
            $i++;
        }

    }

    return $password;

}


function logout()
{
    global $db;
    session_start();

    if(isset($_SESSION['user_id']) || isset($_COOKIE['user_id'])) {
        mysql_query("update `users`
			set `ckey`= '', `ctime`= ''
			where `id`='$_SESSION[user_id]' OR  `id` = '$_COOKIE[user_id]'") or die(mysql_error());
    }

    /************ Delete the sessions****************/
    unset($_SESSION['user_id']);
    unset($_SESSION['user_name']);
    unset($_SESSION['user_level']);
    unset($_SESSION['HTTP_USER_AGENT']);
    session_unset();
    session_destroy();

    /* Delete the cookies*******************/
    setcookie("user_id", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
    setcookie("user_name", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
    setcookie("user_key", '', time()-60*60*24*COOKIE_TIME_OUT, "/");

    header("Location: login.php");
}

// Password and salt generation
function PwdHash($pwd, $salt = null)
{
    if ($salt === null)     {
        $salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
    }
    else     {
        $salt = substr($salt, 0, SALT_LENGTH);
    }
    return $salt . sha1($pwd . $salt);
}

function checkAdmin() {

    if($_SESSION['user_level'] == ADMIN_LEVEL) {
        return 1;
        } else {
        return 0 ;
        }
    }

}
class ZIP{
    function zipIsValid($path) {
        $zip = zip_open($path);
        if (is_resource($zip)) {
            // it's ok
            zip_close($zip); // always close handle if you were just checking
            return true;
        } else {
            return false;
        }
    }
    function zipFileUpload($inputname){
        global $uniquezipnamenumber;
        global $site_url;
        $ok=1;
        $upload_name = $inputname;
        // AICI VERIFICAM DACA A FOST ADAUGATA O FILA
        if (!isset($_FILES[$upload_name])) {
            //header('Location: index.php');
            echo 'No upload found in \$_FILES for ' . $upload_name;
            $ok=0;
            //exit();
        } else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0) {
            // echo $uploadErrors[$_FILES[$upload_name]['error']];
            echo "<p class='error'>No files</p>";
            $ok=0;
            //exit();
        } else if (!isset($_FILES[$upload_name]['tmp_name']) || !@is_uploaded_file($_FILES[$upload_name]['tmp_name'])) {
            echo "<p class='error'>Upload failed is_uploaded_file test.</p>";
            $ok=0;
            //exit();
        } else if (!isset($_FILES[$upload_name]['name'])) {
            $ok=0;
            echo "<p class='error'>File has no name.</p>";
            //exit();
        }

/*
        if($ok == 1) {
            // check if is a zip

            $imageinfo = getimagesize($_FILES[$upload_name]['tmp_name']);
            if($imageinfo['mime'] != 'application/zip') {
                echo "<p class='error'>That is not a ZIP file !</p>";
                $ok=0;
                //exit();
            }
        }
*/ // NEAPARAT DE REZOLVAT AICI
        if($ok == 1) {
            if($this->zipIsValid($_FILES[$upload_name]['tmp_name'])){
                $ok = 1;
            } else {
                $ok = 0;
                echo "<p class='error'>Invalid ZIP file</p>";
            }
        }



        if($ok == 1) {
            // blacklist ce nu tre sa fie
            $filename = strtolower($_FILES[$upload_name]['name']);
            $blacklist = array('php', 'php3', 'php4', 'phtml','exe'); #example of black list

            foreach ($blacklist as $item) {
                if(preg_match("/$item\$/i", $filename)) {
                    echo "<p class='error'>We do not allow uploading PHP files</p>";
                    $ok=0;
                    //exit();
                }
            }
        }

        if($ok == 1) {
            $dir = "cache/zip";

            if(!file_exists($dir) OR !is_dir($dir)){
                mkdir($dir, 0777, true);
            }

            //$uniquenumber = uniqid('', true);
            $uniquezipnamenumber = uniqid();

            $target = $dir;
            $extension = pathinfo($_FILES[$upload_name]['name'], PATHINFO_EXTENSION);
            //$filename =  $_FILES['uploaded']['name'];
            $target = $target  . "/"  . $uniquezipnamenumber . "." . $extension;


            $uploaded_size = $_FILES[$upload_name]['size'];

            //echo $uploaded_size;

            //This is our size condition
            if ($uploaded_size > MAX_UPLOAD_SIZE_ZIP*1024) {
                echo "<p class='error'>Your file is too large.</p>";
                $ok=0;
            }
        }
        //This is our limit file type condition



        if ($ok==0) {
            echo "<p class='error'>Sorry your file was not uploaded </p>";
        } else {

            //If everything is ok we try to upload it
            if(move_uploaded_file($_FILES[$upload_name]['tmp_name'], $target)) {
                echo "<p class='success'> ZIP file has been succesfuly uploaded </p>";

            } else {
                echo "<p class='error'>Sorry, there was a problem uploading your ZIP file.</p>";
            }
        }



    }

    function extract_upload($name, $destination){
        $zip = new ZipArchive;
        if ($zip->open($name) === TRUE) {
            $zip->extractTo($destination);
            $zip->close();
            //echo 'ok';
        } else {
            //echo 'failed';
        }
    }

    function delTree($dir) {
        $files = glob( $dir . '*', GLOB_MARK );
        foreach( $files as $file ){
            if( substr( $file, -1 ) == '/' )
                $this->delTree( $file );
            else
                unlink( $file );
        }
        rmdir( $dir );
    }
}

class FTP{
    function mkdir_recusive($con_id,$path){
        $parts = explode("/",$path);
        $return = true;
        $fullpath = "";
        foreach($parts as $part){
            if(empty($part)){
                $fullpath .= "/";
                continue;
            }
            $fullpath .= $part."/";
            if(@ftp_chdir($con_id, $fullpath)){
                ftp_chdir($con_id, $fullpath);
            }else{
                if(@ftp_mkdir($con_id, $part)){
                    ftp_chdir($con_id, $part);
                }else{
                    $return = false;
                }
            }
        }
        return $return;
    }
    function directory_exists($ftp, $dir)
    {
        // Get the current working directory
        $origin = ftp_pwd($ftp);

        // Attempt to change directory, suppress errors
        if (@ftp_chdir($ftp, $dir))
        {
            // If the directory exists, set back to origin
            ftp_chdir($ftp, $origin);
            return true;
        }

        // Directory does not exist
        return false;
    }

    function connect($ftp_server, $ftp_user, $ftp_pass) {

    global $ftp_conn_id;

        // set up a connection or die
        $ftp_conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");

        // try to login
        if (@ftp_login($ftp_conn_id, $ftp_user, $ftp_pass)) {
            return true;
        } else {
            return false;
        }
    }
    function disconnect($ftp_conn_id){
        ftp_close($ftp_conn_id);
    }
}

class upload{
    function regular_upload($inputname, $ftp_server){
        global $site_url;
        $ok=1;
        $upload_name = $inputname;
        // AICI VERIFICAM DACA A FOST ADAUGATA O FILA
        if (!isset($_FILES[$upload_name])) {
            //header('Location: index.php');
            echo 'No upload found in \$_FILES for ' . $upload_name;
            $ok=0;
            //exit();
        } else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0) {
            // echo $uploadErrors[$_FILES[$upload_name]['error']];
            echo "<p class='error'>No files</p>";
            $ok=0;
            //exit();
        } else if (!isset($_FILES[$upload_name]['tmp_name']) || !@is_uploaded_file($_FILES[$upload_name]['tmp_name'])) {
            echo "<p class='error'>Upload failed is_uploaded_file test.</p>";
            $ok=0;
            //exit();
        } else if (!isset($_FILES[$upload_name]['name'])) {
            $ok=0;
            echo "<p class='error'>File has no name.</p>";
            //exit();
        }
        // DACA ADULT NU E NUMERIC DIEEEEE
        if (isset($_POST['adult']) && is_numeric($_POST['adult']) && $_POST['adult'] >= 0 && $_POST['adult'] <= 1) {
            $adult = $_POST['adult'];
        } else {
            die("You didn't specify if your file(s) are Adult or Non-Adult");
        }

        if(is_numeric($_POST['thumb_size_contaner'])) {
            $thumbnail_size = $_POST['thumb_size_contaner'];
        } else {
            die("Injection detected");
        }

        if($ok == 1) {
        // verificare tipul de imagini - un fel de whitelist
        $imageinfo = getimagesize($_FILES[$upload_name]['tmp_name']);
        if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg' && $imageinfo['mime'] != 'image/png' && $imageinfo['mime'] != 'image/jpg') {
            echo "<p class='error'>Sorry, we only accept GIF, JPEG and PNG images</p>";
            $ok=0;
            //exit();
        }
        }

        if($ok == 1) {
        // blacklist ce nu tre sa fie
        $filename = strtolower($_FILES[$upload_name]['name']);
        $blacklist = array('php', 'php3', 'php4', 'phtml','exe'); #example of black list

        foreach ($blacklist as $item) {
            if(preg_match("/$item\$/i", $filename)) {
                echo "<p class='error'>We do not allow uploading PHP files</p>";
                $ok=0;
                //exit();
            }
        }
        }

        if($ok == 1) {
        // de aici setam dimensiunea maxima a imaginii
        list($width, $height, $type, $attr) = getimagesize($_FILES[$upload_name]['tmp_name']);
        if ($width > MAX_UPLOAD_WIDTH || $height > MAX_UPLOAD_HEIGHT)
        {
            echo "<p class='error'>Maximum width and height exceeded. Please upload images below ".MAX_UPLOAD_WIDTH." x ".MAX_UPLOAD_HEIGHT." px size</p>";
            $ok=0;
            //exit();
        }
        }

        if($ok == 1) {
        $q = "SELECT img, thumb FROM sources WHERE id = '1'";
        $result = mysql_query($q);
        if(mysql_num_rows($result) > 0) {
            $rowSources = mysql_fetch_array($result);
        } else {
            die("Something went wrong : ". mysql_error());
        }



        $data_year = date('Y');
        $data_month = date('m');
        $data_day = date('d');

            if($ftp_server == 0) {
        $dir = $rowSources['img'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
        $dirthumb = $rowSources['thumb'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";

        if(!file_exists($dir) OR !is_dir($dir)){
            mkdir($dir, 0777, true);
        }

        if(!file_exists($dirthumb) OR !is_dir($dirthumb)){
            mkdir($dirthumb, 0777, true);
        }

        } else {
                $q = "SELECT * FROM ftp_logins
                INNER JOIN sources ON ftp_logins.source_id = sources.id
                WHERE ftp_logins.id = $ftp_server
                ";
                $result = mysql_query($q);
                if(!$result) {
                    echo mysql_error();
                }
                $rowFTP = mysql_fetch_assoc($result);

                $dir = $rowFTP['img'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
                $dir2 = $rowFTP['img2'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
                $dirthumb = $rowFTP['thumb'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
                $dirthumb2 = $rowFTP['thumb2'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";



                $FTP = new FTP();
                $FTP->connect($rowFTP['host'], $rowFTP['user'], $rowFTP['pass']);
                global $ftp_conn_id;

                if(!$FTP->directory_exists($ftp_conn_id, "/". $dir)) {
                    $FTP->mkdir_recusive($ftp_conn_id, "/". $dir);
                }
                if(!$FTP->directory_exists($ftp_conn_id, "/". $dirthumb)) {
                    $FTP->mkdir_recusive($ftp_conn_id, "/". $dirthumb);
                }
            }

        //$uniquenumber = uniqid('', true);
        $uniquenumber = uniqid();
        $view_id = uniqid();

        $target = $dir;
        $extension = pathinfo($_FILES[$upload_name]['name'], PATHINFO_EXTENSION);
        //$filename =  $_FILES['uploaded']['name'];
        $nameimage = $uniquenumber . "." .  $extension;
        $target = $target  . "/"  . $uniquenumber . "." . $extension;


        $uploaded_size = $_FILES[$upload_name]['size'];

        //echo $uploaded_size;

        //This is our size condition
        if ($uploaded_size > MAX_UPLOAD_SIZE*1024) { // IN KB
            echo "<p class='error'>Your file is too large.</p>";
            $ok=0;
        }
        }
        //This is our limit file type condition



        if ($ok==0) {
            echo "<p class='error'>Sorry your file was not uploaded </p>";
        } else {

            //If everything is ok we try to upload it
if($ftp_server == 0) {

            if(move_uploaded_file($_FILES[$upload_name]['tmp_name'], $target)) {
                echo "<p class='success'> ". basename( $_FILES[$upload_name]['name']). " has been succesfuly uploaded </p>";

                //aici se transforma RESIZE PENTRU THUMBNAIL din $_POST[''];
                $thumbnail_size_final = 180;
                switch($thumbnail_size) {
                    case 1:
                        $thumbnail_size_final = SMALL_THUMB;
                        break;
                    case 2:
                        $thumbnail_size_final = MEDIUM_THUMB;
                        break;
                    case 3;
                        $thumbnail_size_final = LARGE_THUMB;
                        break;
                    case 4;
                        $thumbnail_size_final = LARGER_THUMB;
                        break;
                    case 5;
                        $thumbnail_size_final = COVER_THUMB;
                        break;
                }



                // aici se face resizeul imaginilor
                $target_thumb = $dirthumb;
                $resizeuploadpatch = $target_thumb . "/" . $uniquenumber . "." . $extension ;
                $image = new SimpleImage();
                $image->load($target);

                if($width > $thumbnail_size_final) {
                $image->resizeToWidth($thumbnail_size_final);
                }

                $image->save($resizeuploadpatch);


                $data = date('Y-m-d');
                //$ImageId = $randomnumber . "-" . $basenameFilesUploaded;
                //$ThumbSpreImagine = $website . "/" . $thumb . "/" . $ImageId;


                //INSERARE IN BAZA DE DATE
                if(isset($_SESSION['user_id'])) {
                    $user_id = $_SESSION['user_id'];
                } else {
                    $user_id = 0;
                }

                if(isset($_SESSION['user_id']) && isset($_POST['set_gallery']) && is_numeric($_POST['set_gallery']) && strlen($_POST['set_gallery']) > 0) {
                    $qG = "SELECT id FROM galleries WHERE id = {$_POST['set_gallery']} AND id_user = {$_SESSION['user_id']}";
                    $resultQg = mysql_query($qG);
                    if($resultQg && mysql_num_rows($resultQg) > 0){
                        $gallery = $_POST['set_gallery'];
                    } else {
                        $gallery = 0;
                    }
                } else {
                    $gallery = 0;
                }

                $q = "INSERT INTO images (`id_user`,`gallery`,`name`,`view_id`, `date_added`, `last_view`, `source`, `adult`, `thumb_size`, `ftp`) VALUES
                            ('{$user_id}','{$gallery}','{$nameimage}', '{$view_id}', '{$data}', '{$data}', '1', '{$adult}', '{$thumbnail_size}', '{$ftp_server}')";
                $result = mysql_query($q);
                $id_inserted = mysql_insert_id();
                if(!$result) {
                    die("Database error : " . mysql_error());
                }

                if(isset($_POST['download_links']) && strlen($_POST['download_links']) > 2) {
                    $download_links = filter($_POST['download_links']);
                    $download_links = trim($download_links);
                    $q = "INSERT INTO images_opt (`id_img`, `download_links`) VALUES ('{$id_inserted}', '{$download_links}')";
                    $result = mysql_query($q);
                    if(!$result) {
                        die("Database error : " . mysql_error());
                    }
                }

                ?>

            <div id="uploadedimage">
                <a target='_blank' href="<?php echo "{$site_url}/img-{$view_id}.html"; ?>"><img border="0" src="<?php echo $site_url . "/" . $resizeuploadpatch; ?>" alt="any image" /></a>
            </div>

            <div id="uploadcodes">
                <label>BB Code:</label><br />
                <input type='text' onclick="this.select();" value="<?php echo "[URL={$site_url}/img-{$view_id}.html][IMG]{$site_url}/{$resizeuploadpatch}[/IMG][/URL] "; ?>">
                <br /> <br />
                <label>HTML:</label><br />
                <input type='text' onclick="this.select();" value="<?php echo "<a href='{$site_url}/img-{$view_id}.html'><img src='{$site_url}/{$resizeuploadpatch}' alt='image' /></a> "; ?>">
                <br /> <br />
                <label>Link:</label><br />
                <input type='text' onclick="this.select();" value="<?php echo "{$site_url}/img-{$view_id}.html "; ?>">
                <?php
                if(DIRECT_LINK_SHOW == 1) {
                    echo "
                        <br /> <br />
                        <label>Direct Link to image:</label><br />
                        <input type='text' onclick='this.select();' value='{$site_url}/{$dir}/{$nameimage}'>
                        ";
                }
                ?>
            </div>

            <?php

                global $BBCode_global;
                global $HTMLCode_global;
                global $DirectLink_global;
                global $DirectLinkToImg_global;

                $BBCode_global[] = "[URL={$site_url}/img-{$view_id}.html][IMG]{$site_url}/{$resizeuploadpatch}[/IMG][/URL]";
                $HTMLCode_global[] = "<a href='{$site_url}/img-{$view_id}.html'><img src='{$site_url}/{$resizeuploadpatch}' alt='image' /></a>";
                $DirectLink_global[] = "{$site_url}/img-{$view_id}.html";
                $DirectLinkToImg_global[] = "{$site_url}/{$dir}/{$nameimage}";


                echo "<div style='display:none;' class='ajax_BBCode'>[URL={$site_url}/img-{$view_id}.html][IMG]{$site_url}/{$resizeuploadpatch}[/IMG][/URL]</div>";
                echo "<div style='display:none;' class='ajax_HTMLCode'><a href='{$site_url}/img-{$view_id}.html'><img src='{$site_url}/{$resizeuploadpatch}' alt='image' /></a></div>";
                echo "<div style='display:none;' class='ajax_DirectLink'>{$site_url}/img-{$view_id}.html</div>";
                echo "<div style='display:none;' class='ajax_DirectLinkToImg'>{$site_url}/{$dir}/{$nameimage}</div>";

            } else {
                echo "<p class='error'>Sorry, there was a problem uploading your file.</p>";
            }

} else { // if FTP SERVER
    $ftp_temp_img = "cache/ftp/".$nameimage."";
    $ftp_temp_thumb = "cache/ftp/thumb/".$nameimage."";
    if(move_uploaded_file($_FILES[$upload_name]['tmp_name'], $ftp_temp_img)) {
        //aici se transforma RESIZE PENTRU THUMBNAIL din $_POST[''];
        $thumbnail_size_final = 180;
        switch($thumbnail_size) {
            case 1:
                $thumbnail_size_final = SMALL_THUMB;
                break;
            case 2:
                $thumbnail_size_final = MEDIUM_THUMB;
                break;
            case 3;
                $thumbnail_size_final = LARGE_THUMB;
                break;
            case 4;
                $thumbnail_size_final = LARGER_THUMB;
                break;
            case 5;
                $thumbnail_size_final = COVER_THUMB;
                break;
        }



        // aici se face resizeul imaginilor
        $image = new SimpleImage();
        $image->load($ftp_temp_img);

        if($width > $thumbnail_size_final) {
            $image->resizeToWidth($thumbnail_size_final);
        }

        $image->save($ftp_temp_thumb);
    }


    if (ftp_put($ftp_conn_id, "/".$dir . "/$nameimage/", $ftp_temp_img, FTP_BINARY)) {
        //echo "successfully uploaded image $ftp_temp_img in $target\n";
    } else {
        //echo "There was a problem while uploading $ftp_temp_img in $target\n";
    }

    if (ftp_put($ftp_conn_id, "/".$dirthumb . "/$nameimage/", $ftp_temp_thumb, FTP_BINARY)) {
        //echo "successfully uploaded image $ftp_temp_thumb in $ftp_temp_thumb\n";
    } else {
        //echo "There was a problem while uploading $ftp_temp_thumb in $dirthumb\n";
    }

    $FTP->disconnect($ftp_conn_id);

    unlink($ftp_temp_img);
    unlink($ftp_temp_thumb);


    $data = date('Y-m-d');
    //$ImageId = $randomnumber . "-" . $basenameFilesUploaded;
    //$ThumbSpreImagine = $website . "/" . $thumb . "/" . $ImageId;


    //INSERARE IN BAZA DE DATE
    if(isset($_SESSION['user_id'])) {
        $user_id = $_SESSION['user_id'];
    } else {
        $user_id = 0;
    }

    if(isset($_SESSION['user_id']) && isset($_POST['set_gallery']) && is_numeric($_POST['set_gallery']) && strlen($_POST['set_gallery']) > 0) {
        $qG = "SELECT id FROM galleries WHERE id = {$_POST['set_gallery']} AND id_user = {$_SESSION['user_id']}";
        $resultQg = mysql_query($qG);
        if($resultQg && mysql_num_rows($resultQg) > 0){
            $gallery = $_POST['set_gallery'];
        } else {
            $gallery = 0;
        }
    } else {
        $gallery = 0;
    }

    $q = "INSERT INTO images (`id_user`,`gallery`,`name`,`view_id`, `date_added`, `last_view`, `source`, `adult`, `thumb_size`, `ftp`) VALUES
                            ('{$user_id}','{$gallery}','{$nameimage}', '{$view_id}', '{$data}', '{$data}', '{$rowFTP['source_id']}', '{$adult}', '{$thumbnail_size}', '{$ftp_server}')";
    $result = mysql_query($q);
    $id_inserted = mysql_insert_id();
    if(!$result) {
        die("Database error : " . mysql_error());
    }

    if(isset($_POST['download_links']) && strlen($_POST['download_links']) > 2) {
        $download_links = filter($_POST['download_links']);
        $download_links = trim($download_links);
        $q = "INSERT INTO images_opt (`id_img`, `download_links`) VALUES ('{$id_inserted}', '{$download_links}')";
        $result = mysql_query($q);
        if(!$result) {
            die("Database error : " . mysql_error());
        }
    }

    ?>

<div id="uploadedimage">
    <a target='_blank' href="<?php echo "{$site_url}/img-{$view_id}.html"; ?>"><img border="0" src="<?php echo "{$rowFTP['url']}/{$dirthumb2}/{$nameimage}"; ?>" alt="uploaded_image" /></a>
</div>

<div id="uploadcodes">
    <label>BB Code:</label><br />
    <input type='text' onclick="this.select();" value="<?php echo "[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL] "; ?>">
    <br /> <br />
    <label>HTML:</label><br />
    <input type='text' onclick="this.select();" value="<?php echo "<a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a> "; ?>">
    <br /> <br />
    <label>Link:</label><br />
    <input type='text' onclick="this.select();" value="<?php echo "{$site_url}/img-{$view_id}.html "; ?>">
    <?php
    if(DIRECT_LINK_SHOW == 1) {
        echo "
                        <br /> <br />
                        <label>Direct Link to image:</label><br />
                        <input type='text' onclick='this.select();' value='{$rowFTP['url']}/{$dir2}/{$nameimage}'>
                        ";
    }
    ?>
</div>

<?php

    global $BBCode_global;
    global $HTMLCode_global;
    global $DirectLink_global;
    global $DirectLinkToImg_global;

    $BBCode_global[] = "[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL]";
    $HTMLCode_global[] = "<a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a>";
    $DirectLink_global[] = "{$site_url}/img-{$view_id}.html";
    $DirectLinkToImg_global[] = "{$rowFTP['url']}/{$dir2}/{$nameimage}";

    echo "<div style='display:none;' class='ajax_BBCode'>[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL]</div>";
    echo "<div style='display:none;' class='ajax_HTMLCode'><a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a></div>";
    echo "<div style='display:none;' class='ajax_DirectLink'>{$site_url}/img-{$view_id}.html</div>";
    echo "<div style='display:none;' class='ajax_DirectLinkToImg'>{$rowFTP['url']}/{$dir2}/{$nameimage}</div>";

} // ftp end





        } // ELSE IF EVERYTING IS OK, IF ERROR = 0
    } // END FUNCTION

    function valid_url($str)
    {
        return ( ! preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $str)) ? FALSE : TRUE;
    }

    function isImage($url)
    {
        $params = array('http' => array(
            'method' => 'HEAD'
        ));
        $ctx = stream_context_create($params);
        $fp = @fopen($url, 'rb', false, $ctx);
        if (!$fp)
            return false;  // Problem with url

        $meta = stream_get_meta_data($fp);
        if ($meta === false)
        {
            fclose($fp);
            return false;  // Problem reading data from url
        }

        $wrapper_data = $meta["wrapper_data"];
        if(is_array($wrapper_data)){
            foreach(array_keys($wrapper_data) as $hh){
                if (substr($wrapper_data[$hh], 0, 19) == "Content-Type: image") // strlen("Content-Type: image") == 19
                {
                    fclose($fp);
                    return true;
                }
            }
        }

        fclose($fp);
        return false;
    }

    function remoteUpload($url, $ftp_server){
        global $site_url;
        $ok = 1;
        if(!$this->valid_url($url) || !$this->isImage($url)) {
        $ok = 0;
            echo "Image or URL not valid";
        }

        // DACA ADULT NU E NUMERIC DIEEEEE
        if (isset($_POST['adult']) && is_numeric($_POST['adult']) && $_POST['adult'] >= 0 && $_POST['adult'] <= 1) {
            $adult = $_POST['adult'];
        } else {
            die("You didn't specify if your file(s) are Adult or Non-Adult");
        }

        if(is_numeric($_POST['thumb_size_contaner'])) {
            $thumbnail_size = $_POST['thumb_size_contaner'];
        } else {
            die("Injection detected");
        }

        if($ok == 1) {
            // verificare tipul de imagini - un fel de whitelist
            $imageinfo = getimagesize($url);
            if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg' && $imageinfo['mime'] != 'image/png' && $imageinfo['mime'] != 'image/jpg') {
                echo "<p class='error'>Sorry, we only accept GIF, JPEG and PNG images</p>";
                $ok=0;
                //exit();
            }
        }



        if($ok == 1) {
            // de aici setam dimensiunea maxima a imaginii
            list($width, $height, $type, $attr) = getimagesize($url);
            if ($width > MAX_UPLOAD_WIDTH || $height > MAX_UPLOAD_HEIGHT)
            {
                echo "<p class='error'>Maximum width and height exceeded. Please upload images below ".MAX_UPLOAD_WIDTH." x ".MAX_UPLOAD_HEIGHT." px size</p>";
                $ok=0;
                //exit();
            }
        }
        if($ok == 1) {
            $path_upload = explode('/', $url);
            $nameupload=$path_upload[count($path_upload)-1];

            $q = "SELECT img, thumb FROM sources WHERE id = '1'";
            $result = mysql_query($q);
            if(mysql_num_rows($result) > 0) {
                $rowSources = mysql_fetch_array($result);
            } else {
                $ok=0;
                die("Something went wrong : ". mysql_error());
            }
        }

        if($ok == 1) {

            $data_year = date('Y');
            $data_month = date('m');
            $data_day = date('d');

            if($ftp_server == 0) {
            $dir = $rowSources['img'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
            $dirthumb = $rowSources['thumb'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";


            if(!file_exists($dir) OR !is_dir($dir)){
                mkdir($dir, 0777, true);
            }

            if(!file_exists($dirthumb) OR !is_dir($dirthumb)){
                mkdir($dirthumb, 0777, true);
            }

            } else {
                $q = "SELECT * FROM ftp_logins
                INNER JOIN sources ON ftp_logins.source_id = sources.id
                WHERE ftp_logins.id = $ftp_server
                ";
                $result = mysql_query($q);
                if(!$result) {
                    echo mysql_error();
                }
                $rowFTP = mysql_fetch_assoc($result);

                $dir = $rowFTP['img'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
                $dir2 = $rowFTP['img2'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
                $dirthumb = $rowFTP['thumb'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
                $dirthumb2 = $rowFTP['thumb2'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";


                $FTP = new FTP();
                $FTP->connect($rowFTP['host'], $rowFTP['user'], $rowFTP['pass']);
                global $ftp_conn_id;

                if(!$FTP->directory_exists($ftp_conn_id, "/". $dir)) {
                    $FTP->mkdir_recusive($ftp_conn_id, "/". $dir);
                }
                if(!$FTP->directory_exists($ftp_conn_id, "/". $dirthumb)) {
                    $FTP->mkdir_recusive($ftp_conn_id, "/". $dirthumb);
                }
            }

            //$uniquenumber = uniqid('', true);
            $uniquenumber = uniqid();
            $view_id = uniqid();

            $target = $dir;
            switch($imageinfo['mime']) {
                case 'image/gif':
                    $extension = "gif";
                    break;
                case 'image/jpeg':
                    $extension = "jpeg";
                    break;
                case 'image/png':
                    $extension = "png";
                    break;
                case 'image/jpg':
                    $extension = "jpg";
                    break;
            }
            //$extension = pathinfo($_FILES[$upload_name]['name'], PATHINFO_EXTENSION);
            //$filename =  $_FILES['uploaded']['name'];
            $target = $target  . "/"  . $uniquenumber . "." . $extension;
            $nameimage = $uniquenumber . "." .  $extension;


            //$uploaded_size = $_FILES[$upload_name]['size'];
            // NU MAI FILTRAM DIMENSIUNEA IMAGINII !!!!!!!!!!!!!!!!@@@@@@@@!!!!!!!!!!!

        }

        if ($ok==0) {
            echo "<p class='error'>Sorry your file was not uploaded </p>";
        } else {


            if($ftp_server == 0) {
        if(copy($url, $target)) {
            echo "<p class='success'> ". $nameupload . " has been succesfuly uploaded </p>";
            $thumbnail_size_final = 180;
            switch($thumbnail_size) {
                case 1:
                    $thumbnail_size_final = SMALL_THUMB;
                    $thumbnail_size_final_height = 100;
                    break;
                case 2:
                    $thumbnail_size_final = MEDIUM_THUMB;
                    $thumbnail_size_final_height = 200;
                    break;
                case 3;
                    $thumbnail_size_final = LARGE_THUMB;
                    $thumbnail_size_final_height = 300;
                    break;
                case 4;
                    $thumbnail_size_final = LARGER_THUMB;
                    $thumbnail_size_final_height = 400;
                    break;
            }

            // aici se face resizeul imaginilor
            $target_thumb = $dirthumb;
            $resizeuploadpatch = $target_thumb . "/" . $uniquenumber . "." . $extension ;
            $image = new SimpleImage();
            $image->load($target);
            if($width > $thumbnail_size_final) {
            $image->resizeToWidth($thumbnail_size_final);
            }
            $image->save($resizeuploadpatch);


            $data = date('Y-m-d');
            //$ImageId = $randomnumber . "-" . $basenameFilesUploaded;
            //$ThumbSpreImagine = $website . "/" . $thumb . "/" . $ImageId;


            //INSERARE IN BAZA DE DATE
            if(isset($_SESSION['user_id'])) {
                $user_id = $_SESSION['user_id'];
            } else {
                $user_id = 0;
            }

            $q = "INSERT INTO images (`id_user`,`name`,`view_id`, `date_added`, `last_view`, `source`, `adult`, `thumb_size`, `ftp`) VALUES
                            ('{$user_id}','{$nameimage}', '{$view_id}', '{$data}', '{$data}', '1', '{$adult}', '{$thumbnail_size}', '{$ftp_server}')";
            $result = mysql_query($q);
            $id_inserted = mysql_insert_id();
            if(!$result) {
                die("Database error : " . mysql_error());
            }

            if(isset($_POST['download_links']) && strlen($_POST['download_links']) > 2) {
                $download_links = filter($_POST['download_links']);
                $download_links = trim($download_links);
                $q = "INSERT INTO images_opt (`id_img`, `download_links`) VALUES ('{$id_inserted}', '{$download_links}')";
                $result = mysql_query($q);
                if(!$result) {
                    die("Database error : " . mysql_error());
                }
            }

            ?>

        <div id="uploadedimage">
            <a href="<?php echo "{$site_url}/img-{$view_id}.html"; ?>"><img border="0" src="<?php echo $site_url . "/" . $resizeuploadpatch; ?>" alt="uploaded_image" /></a>
        </div>

        <div id="uploadcodes">
            <label>BB Code:</label><br />
            <input type='text' onclick="this.select();" value="<?php echo "[URL={$site_url}/img-{$view_id}.html][IMG]{$site_url}/{$resizeuploadpatch}[/IMG][/URL]"; ?>">
            <br /> <br />
            <label>HTML:</label><br />
            <input type='text' onclick="this.select();" value="<?php echo "<a href='{$site_url}/img-{$view_id}.html'><img src='{$site_url}/{$resizeuploadpatch}' alt='image' /></a>"; ?>">
            <br /> <br />
            <label>Link:</label><br />
            <input type='text' onclick="this.select();" value="<?php echo "{$site_url}/img-{$view_id}.html"; ?>">
            <?php
            if(DIRECT_LINK_SHOW == 1) {
                echo "
                        <br /> <br />
                        <label>Direct Link to image:</label><br />
                        <input type='text' onclick='this.select();' value='{$site_url}/{$dir}/{$nameimage}'>
                        ";
            }
            ?>
        </div>

        <?php


        } else {
            echo "<p class='error'>Sorry, there was a problem uploading your file.</p>";
        }


            } else { // ELSE FTP SERVER IS NOT 0


                $ftp_temp_img = "cache/ftp/".$nameimage."";
                $ftp_temp_thumb = "cache/ftp/thumb/".$nameimage."";

                if(copy($url, $ftp_temp_img)) {
                    //aici se transforma RESIZE PENTRU THUMBNAIL din $_POST[''];
                    $thumbnail_size_final = 180;
                    switch($thumbnail_size) {
                        case 1:
                            $thumbnail_size_final = SMALL_THUMB;
                            break;
                        case 2:
                            $thumbnail_size_final = MEDIUM_THUMB;
                            break;
                        case 3;
                            $thumbnail_size_final = LARGE_THUMB;
                            break;
                        case 4;
                            $thumbnail_size_final = LARGER_THUMB;
                            break;
                        case 5;
                            $thumbnail_size_final = COVER_THUMB;
                            break;
                    }



                    // aici se face resizeul imaginilor
                    $image = new SimpleImage();
                    $image->load($ftp_temp_img);

                    if($width > $thumbnail_size_final) {
                        $image->resizeToWidth($thumbnail_size_final);
                    }

                    $image->save($ftp_temp_thumb);



                if (ftp_put($ftp_conn_id, "/".$dir . "/$nameimage/", $ftp_temp_img, FTP_BINARY)) {
                    //echo "successfully uploaded image $ftp_temp_img in $target\n";
                } else {
                    //echo "There was a problem while uploading $ftp_temp_img in $target\n";
                }

                if (ftp_put($ftp_conn_id, "/".$dirthumb . "/$nameimage/", $ftp_temp_thumb, FTP_BINARY)) {
                    //echo "successfully uploaded image $ftp_temp_thumb in $ftp_temp_thumb\n";
                } else {
                    //echo "There was a problem while uploading $ftp_temp_thumb in $dirthumb\n";
                }

                $FTP->disconnect($ftp_conn_id);

                unlink($ftp_temp_img);
                unlink($ftp_temp_thumb);


                $data = date('Y-m-d');
                //$ImageId = $randomnumber . "-" . $basenameFilesUploaded;
                //$ThumbSpreImagine = $website . "/" . $thumb . "/" . $ImageId;


                //INSERARE IN BAZA DE DATE
                if(isset($_SESSION['user_id'])) {
                    $user_id = $_SESSION['user_id'];
                } else {
                    $user_id = 0;
                }

                if(isset($_SESSION['user_id']) && isset($_POST['set_gallery']) && is_numeric($_POST['set_gallery']) && strlen($_POST['set_gallery']) > 0) {
                    $qG = "SELECT id FROM galleries WHERE id = {$_POST['set_gallery']} AND id_user = {$_SESSION['user_id']}";
                    $resultQg = mysql_query($qG);
                    if($resultQg && mysql_num_rows($resultQg) > 0){
                        $gallery = $_POST['set_gallery'];
                    } else {
                        $gallery = 0;
                    }
                } else {
                    $gallery = 0;
                }

                $q = "INSERT INTO images (`id_user`,`gallery`,`name`,`view_id`, `date_added`, `last_view`, `source`, `adult`, `thumb_size`, `ftp`) VALUES
                            ('{$user_id}','{$gallery}','{$nameimage}', '{$view_id}', '{$data}', '{$data}', '{$rowFTP['source_id']}', '{$adult}', '{$thumbnail_size}', '{$ftp_server}')";
                $result = mysql_query($q);
                $id_inserted = mysql_insert_id();
                if(!$result) {
                    die("Database error : " . mysql_error());
                }

                if(isset($_POST['download_links']) && strlen($_POST['download_links']) > 2) {
                    $download_links = filter($_POST['download_links']);
                    $download_links = trim($download_links);
                    $q = "INSERT INTO images_opt (`id_img`, `download_links`) VALUES ('{$id_inserted}', '{$download_links}')";
                    $result = mysql_query($q);
                    if(!$result) {
                        die("Database error : " . mysql_error());
                    }
                }

                ?>

            <div id="uploadedimage">
                <a target='_blank' href="<?php echo "{$site_url}/img-{$view_id}.html"; ?>"><img border="0" src="<?php echo "{$rowFTP['url']}/{$dirthumb2}/{$nameimage}"; ?>" alt="uploaded_image" /></a>
            </div>

            <div id="uploadcodes">
                <label>BB Code:</label><br />
                <input type='text' onclick="this.select();" value="<?php echo "[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL] "; ?>">
                <br /> <br />
                <label>HTML:</label><br />
                <input type='text' onclick="this.select();" value="<?php echo "<a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a> "; ?>">
                <br /> <br />
                <label>Link:</label><br />
                <input type='text' onclick="this.select();" value="<?php echo "{$site_url}/img-{$view_id}.html "; ?>">
                <?php
                if(DIRECT_LINK_SHOW == 1) {
                    echo "
                        <br /> <br />
                        <label>Direct Link to image:</label><br />
                        <input type='text' onclick='this.select();' value='{$rowFTP['url']}/{$dir2}/{$nameimage}'>
                        ";
                }
                ?>
            </div>

            <?php

                global $BBCode_global;
                global $HTMLCode_global;
                global $DirectLink_global;
                global $DirectLinkToImg_global;

                $BBCode_global[] = "[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL]";
                $HTMLCode_global[] = "<a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a>";
                $DirectLink_global[] = "{$site_url}/img-{$view_id}.html";
                $DirectLinkToImg_global[] = "{$rowFTP['url']}/{$dir2}/{$nameimage}";

                echo "<div style='display:none;' class='ajax_BBCode'>[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL]</div>";
                echo "<div style='display:none;' class='ajax_HTMLCode'><a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a></div>";
                echo "<div style='display:none;' class='ajax_DirectLink'>{$site_url}/img-{$view_id}.html</div>";
                echo "<div style='display:none;' class='ajax_DirectLink'>{$rowFTP['url']}/{$dir2}/{$nameimage}</div>";




                } else {
                    echo "<p class='error'>Sorry, there was a problem uploading your file.</p>";
                }
          }

        } // ELSE IF EVERYTING IS OK, IF ERROR = 0
    } // END FUNCTION





    function zipUpload($patch, $ftp_server){
        global $site_url;
        $ok = 1;

        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            //echo 'This is a server using Windows!';
            if(!file_exists($patch)) {
                $ok = 0;
                echo "File " . $patch . " does not exist";

            }
        } else {
            //echo 'This is a server not using Windows!';
            if(!file_exists($_SERVER['DOCUMENT_ROOT']  . "/" . $patch)) {
                $ok = 0;
                echo "File " . $_SERVER['DOCUMENT_ROOT'] . "/"  . $patch . " does not exist";

            }
        }




        //TEMP DELETE
        $_POST['adult'] = 0;
        $_POST['thumb_size_contaner'] = 2;
        // END TEMP DELETE
        // DACA ADULT NU E NUMERIC DIEEEEE
        if (isset($_POST['adult']) && is_numeric($_POST['adult']) && $_POST['adult'] >= 0 && $_POST['adult'] <= 1) {
            $adult = $_POST['adult'];
        } else {
            die("You didn't specify if your file(s) are Adult or Non-Adult");
        }

        if(is_numeric($_POST['thumb_size_contaner'])) {
            $thumbnail_size = $_POST['thumb_size_contaner'];
        } else {
            die("Injection detected");
        }

        if($ok == 1) {
            // verificare tipul de imagini - un fel de whitelist
            $imageinfo = getimagesize($patch);
            if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg' && $imageinfo['mime'] != 'image/png' && $imageinfo['mime'] != 'image/jpg') {
                echo "<p class='error'>Sorry, we only accept GIF, JPEG and PNG images</p>";
                $ok=0;
                //exit();
            }
        }



        if($ok == 1) {
            // de aici setam dimensiunea maxima a imaginii
            list($width, $height, $type, $attr) = getimagesize($patch);
            if ($width > MAX_UPLOAD_WIDTH || $height > MAX_UPLOAD_HEIGHT)
            {
                echo "<p class='error'>Maximum width and height exceeded. Please upload images below ".MAX_UPLOAD_WIDTH." x ".MAX_UPLOAD_HEIGHT." px size</p>";
                $ok=0;
                //exit();
            }
        }
        if($ok == 1) {
            $path_upload = explode('/', $patch);
            $nameupload=$path_upload[count($path_upload)-1];

            $q = "SELECT img, thumb FROM sources WHERE id = '1'";
            $result = mysql_query($q);
            if(mysql_num_rows($result) > 0) {
                $rowSources = mysql_fetch_array($result);
            } else {
                $ok=0;
                die("Something went wrong : ". mysql_error());
            }
        }

        if($ok == 1) {

            $data_year = date('Y');
            $data_month = date('m');
            $data_day = date('d');

            if($ftp_server == 0) {
            $dir = $rowSources['img'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
            $dirthumb = $rowSources['thumb'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";

            if(!file_exists($dir) OR !is_dir($dir)){
                mkdir($dir, 0777, true);
            }

            if(!file_exists($dirthumb) OR !is_dir($dirthumb)){
                mkdir($dirthumb, 0777, true);
            }

            } else {
                $q = "SELECT * FROM ftp_logins
                INNER JOIN sources ON ftp_logins.source_id = sources.id
                WHERE ftp_logins.id = $ftp_server
                ";
                $result = mysql_query($q);
                if(!$result) {
                    echo mysql_error();
                }
                $rowFTP = mysql_fetch_assoc($result);

                $dir = $rowFTP['img'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
                $dir2 = $rowFTP['img2'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
                $dirthumb = $rowFTP['thumb'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
                $dirthumb2 = $rowFTP['thumb2'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";



                $FTP = new FTP();
                $FTP->connect($rowFTP['host'], $rowFTP['user'], $rowFTP['pass']);
                global $ftp_conn_id;

                if(!$FTP->directory_exists($ftp_conn_id, "/". $dir)) {
                    $FTP->mkdir_recusive($ftp_conn_id, "/". $dir);
                }
                if(!$FTP->directory_exists($ftp_conn_id, "/". $dirthumb)) {
                    $FTP->mkdir_recusive($ftp_conn_id, "/". $dirthumb);
                }
            }

            //$uniquenumber = uniqid('', true);
            $uniquenumber = uniqid();
            $view_id = uniqid();

            $target = $dir;
            switch($imageinfo['mime']) {
                case 'image/gif':
                    $extension = "gif";
                    break;
                case 'image/jpeg':
                    $extension = "jpeg";
                    break;
                case 'image/png':
                    $extension = "png";
                    break;
                case 'image/jpg':
                    $extension = "jpg";
                    break;
            }
            //$extension = pathinfo($_FILES[$upload_name]['name'], PATHINFO_EXTENSION);
            //$filename =  $_FILES['uploaded']['name'];
            $target = $target  . "/"  . $uniquenumber . "." . $extension;
            $nameimage = $uniquenumber . "." .  $extension;


            //$uploaded_size = $_FILES[$upload_name]['size'];
            // NU MAI FILTRAM DIMENSIUNEA IMAGINII !!!!!!!!!!!!!!!!@@@@@@@@!!!!!!!!!!!

        }

        if ($ok==0) {
            echo "<p class='error'>Sorry your file was not uploaded </p>";
        } else {


            if($ftp_server == 0) {
            if(copy($patch, $target)) {
                echo "<p class='success'> ". $nameupload . " has been succesfuly uploaded </p>";
                $thumbnail_size_final = 180;
                switch($thumbnail_size) {
                    case 1:
                        $thumbnail_size_final = SMALL_THUMB;
                        $thumbnail_size_final_height = 100;
                        break;
                    case 2:
                        $thumbnail_size_final = MEDIUM_THUMB;
                        $thumbnail_size_final_height = 200;
                        break;
                    case 3;
                        $thumbnail_size_final = LARGE_THUMB;
                        $thumbnail_size_final_height = 300;
                        break;
                    case 4;
                        $thumbnail_size_final = LARGER_THUMB;
                        $thumbnail_size_final_height = 400;
                        break;
                }

                // aici se face resizeul imaginilor
                $target_thumb = $dirthumb;
                $resizeuploadpatch = $target_thumb . "/" . $uniquenumber . "." . $extension ;
                $image = new SimpleImage();
                $image->load($target);
                if($width > $thumbnail_size_final) {
                    $image->resizeToWidth($thumbnail_size_final);
                }
                $image->save($resizeuploadpatch);


                $data = date('Y-m-d');
                //$ImageId = $randomnumber . "-" . $basenameFilesUploaded;
                //$ThumbSpreImagine = $website . "/" . $thumb . "/" . $ImageId;


                //INSERARE IN BAZA DE DATE
                if(isset($_SESSION['user_id'])) {
                    $user_id = $_SESSION['user_id'];
                } else {
                    $user_id = 0;
                }

                if(isset($_SESSION['user_id']) && isset($_POST['set_gallery']) && is_numeric($_POST['set_gallery']) && strlen($_POST['set_gallery']) > 0) {
                    $qG = "SELECT id FROM galleries WHERE id = {$_POST['set_gallery']} AND id_user = {$_SESSION['user_id']}";
                    $resultQg = mysql_query($qG);
                    if($resultQg && mysql_num_rows($resultQg) > 0){
                        $gallery = $_POST['set_gallery'];
                    } else {
                        $gallery = 0;
                    }
                } else {
                    $gallery = 0;
                }

                $q = "INSERT INTO images (`id_user`,`gallery`,`name`,`view_id`, `date_added`, `last_view`, `source`, `adult`, `thumb_size`, `ftp`) VALUES
                            ('{$user_id}','{$gallery}','{$nameimage}', '{$view_id}', '{$data}', '{$data}', '1', '{$adult}', '{$thumbnail_size}', '{$ftp_server}')";
                $result = mysql_query($q);
                $id_inserted = mysql_insert_id();
                if(!$result) {
                    die("Database error : " . mysql_error());
                }

                if(isset($_POST['download_links']) && strlen($_POST['download_links']) > 2) {
                    $download_links = filter($_POST['download_links']);
                    $download_links = trim($download_links);
                    $q = "INSERT INTO images_opt (`id_img`, `download_links`) VALUES ('{$id_inserted}', '{$download_links}')";
                    $result = mysql_query($q);
                    if(!$result) {
                        die("Database error : " . mysql_error());
                    }
                }

                ?>

            <div id="uploadedimage">
                <a target='_blank' href="<?php echo "{$site_url}/img-{$view_id}.html"; ?>"><img border="0" src="<?php echo $site_url . "/" . $resizeuploadpatch; ?>" alt="uploaded_image" /></a>
            </div>

            <div id="uploadcodes">
                <label>BB Code:</label><br />
                <input type='text' onclick="this.select();" value="<?php echo "[URL={$site_url}/img-{$view_id}.html][IMG]{$site_url}/{$resizeuploadpatch}[/IMG][/URL] "; ?>">
                <br /> <br />
                <label>HTML:</label><br />
                <input type='text' onclick="this.select();" value="<?php echo "<a href='{$site_url}/img-{$view_id}.html'><img src='{$site_url}/{$resizeuploadpatch}' alt='image' /></a> "; ?>">
                <br /> <br />
                <label>Link:</label><br />
                <input type='text' onclick="this.select();" value="<?php echo "{$site_url}/img-{$view_id}.html "; ?>">
                <?php
                if(DIRECT_LINK_SHOW == 1) {
                    echo "
                        <br /> <br />
                        <label>Direct Link to image:</label><br />
                        <input type='text' onclick='this.select();' value='{$site_url}/{$dir}/{$nameimage}'>
                        ";
                }
                ?>
            </div>

            <?php

                global $BBCode_global;
                global $HTMLCode_global;
                global $DirectLink_global;
                global $DirectLinkToImg_global;

                $BBCode_global[] = "[URL={$site_url}/img-{$view_id}.html][IMG]{$site_url}/{$resizeuploadpatch}[/IMG][/URL]";
                $HTMLCode_global[] = "<a href='{$site_url}/img-{$view_id}.html'><img src='{$site_url}/{$resizeuploadpatch}' alt='image' /></a>";
                $DirectLink_global[] = "{$site_url}/img-{$view_id}.html";
                $DirectLinkToImg_global[] = "{$site_url}/{$dir}/{$nameimage}";

                echo "<div style='display:none;' class='ajax_BBCode'>[URL={$site_url}/img-{$view_id}.html][IMG]{$site_url}/{$resizeuploadpatch}[/IMG][/URL]</div>";
                echo "<div style='display:none;' class='ajax_HTMLCode'><a href='{$site_url}/img-{$view_id}.html'><img src='{$site_url}/{$resizeuploadpatch}' alt='image' /></a></div>";
                echo "<div style='display:none;' class='ajax_DirectLink'>{$site_url}/img-{$view_id}.html</div>";
                echo "<div style='display:none;' class='ajax_DirectLinkToImg'>{$site_url}/{$dir}/{$nameimage}</div>";

            } else {
                echo "<p class='error'>Sorry, there was a problem uploading your file.</p>";
            }

            } else { // ELSE FTP SERVER IS NOT 0

                $ftp_temp_img = "cache/ftp/".$nameimage."";
                $ftp_temp_thumb = "cache/ftp/thumb/".$nameimage."";

                if(copy($patch, $ftp_temp_img)) {
                    echo "<p class='success'> ". $nameupload . " has been succesfuly uploaded </p>";
                    $thumbnail_size_final = 180;
                    switch($thumbnail_size) {
                        case 1:
                            $thumbnail_size_final = SMALL_THUMB;
                            $thumbnail_size_final_height = 100;
                            break;
                        case 2:
                            $thumbnail_size_final = MEDIUM_THUMB;
                            $thumbnail_size_final_height = 200;
                            break;
                        case 3;
                            $thumbnail_size_final = LARGE_THUMB;
                            $thumbnail_size_final_height = 300;
                            break;
                        case 4;
                            $thumbnail_size_final = LARGER_THUMB;
                            $thumbnail_size_final_height = 400;
                            break;
                    }

                    // aici se face resizeul imaginilor

                    $image = new SimpleImage();
                    $image->load($ftp_temp_img);

                    if($width > $thumbnail_size_final) {
                        $image->resizeToWidth($thumbnail_size_final);
                    }

                    $image->save($ftp_temp_thumb);

                    if (ftp_put($ftp_conn_id, "/".$dir . "/$nameimage/", $ftp_temp_img, FTP_BINARY)) {
                        //echo "successfully uploaded image $ftp_temp_img in $target\n";
                    } else {
                        //echo "There was a problem while uploading $ftp_temp_img in $target\n";
                    }

                    if (ftp_put($ftp_conn_id, "/".$dirthumb . "/$nameimage/", $ftp_temp_thumb, FTP_BINARY)) {
                        //echo "successfully uploaded image $ftp_temp_thumb in $ftp_temp_thumb\n";
                    } else {
                        //echo "There was a problem while uploading $ftp_temp_thumb in $dirthumb\n";
                    }

                    $FTP->disconnect($ftp_conn_id);

                    unlink($ftp_temp_img);
                    unlink($ftp_temp_thumb);

                    $data = date('Y-m-d');
                    //$ImageId = $randomnumber . "-" . $basenameFilesUploaded;
                    //$ThumbSpreImagine = $website . "/" . $thumb . "/" . $ImageId;


                    //INSERARE IN BAZA DE DATE
                    if(isset($_SESSION['user_id'])) {
                        $user_id = $_SESSION['user_id'];
                    } else {
                        $user_id = 0;
                    }

                    if(isset($_SESSION['user_id']) && isset($_POST['set_gallery']) && is_numeric($_POST['set_gallery']) && strlen($_POST['set_gallery']) > 0) {
                        $qG = "SELECT id FROM galleries WHERE id = {$_POST['set_gallery']} AND id_user = {$_SESSION['user_id']}";
                        $resultQg = mysql_query($qG);
                        if($resultQg && mysql_num_rows($resultQg) > 0){
                            $gallery = $_POST['set_gallery'];
                        } else {
                            $gallery = 0;
                        }
                    } else {
                        $gallery = 0;
                    }

                    $q = "INSERT INTO images (`id_user`,`gallery`,`name`,`view_id`, `date_added`, `last_view`, `source`, `adult`, `thumb_size`, `ftp`) VALUES
                            ('{$user_id}','{$gallery}','{$nameimage}', '{$view_id}', '{$data}', '{$data}', '{$rowFTP['source_id']}', '{$adult}', '{$thumbnail_size}', '{$ftp_server}')";
                    $result = mysql_query($q);
                    $id_inserted = mysql_insert_id();
                    if(!$result) {
                        die("Database error : " . mysql_error());
                    }

                    if(isset($_POST['download_links']) && strlen($_POST['download_links']) > 2) {
                        $download_links = filter($_POST['download_links']);
                        $download_links = trim($download_links);
                        $q = "INSERT INTO images_opt (`id_img`, `download_links`) VALUES ('{$id_inserted}', '{$download_links}')";
                        $result = mysql_query($q);
                        if(!$result) {
                            die("Database error : " . mysql_error());
                        }
                    }

                    ?>

                <div id="uploadedimage">
                    <a target='_blank' href="<?php echo "{$site_url}/img-{$view_id}.html"; ?>"><img border="0" src="<?php echo "{$rowFTP['url']}/{$dirthumb2}/{$nameimage}"; ?>" alt="uploaded_image" /></a>
                </div>

                <div id="uploadcodes">
                    <label>BB Code:</label><br />
                    <input type='text' onclick="this.select();" value="<?php echo "[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL] "; ?>">
                    <br /> <br />
                    <label>HTML:</label><br />
                    <input type='text' onclick="this.select();" value="<?php echo "<a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a> "; ?>">
                    <br /> <br />
                    <label>Link:</label><br />
                    <input type='text' onclick="this.select();" value="<?php echo "{$site_url}/img-{$view_id}.html "; ?>">
                    <?php
                    if(DIRECT_LINK_SHOW == 1) {
                        echo "
                        <br /> <br />
                        <label>Direct Link to image:</label><br />
                        <input type='text' onclick='this.select();' value='{$rowFTP['url']}/{$dir2}/{$nameimage}'>
                        ";
                    }
                    ?>
                </div>

                <?php

                    global $BBCode_global;
                    global $HTMLCode_global;
                    global $DirectLink_global;
                    global $DirectLinkToImg_global;

                    $BBCode_global[] = "[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL]";
                    $HTMLCode_global[] = "<a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a>";
                    $DirectLink_global[] = "{$site_url}/img-{$view_id}.html";
                    $DirectLinkToImg_global[] = "{$rowFTP['url']}/{$dir2}/{$nameimage}";

                    echo "<div style='display:none;' class='ajax_BBCode'>[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL]</div>";
                    echo "<div style='display:none;' class='ajax_HTMLCode'><a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a></div>";
                    echo "<div style='display:none;' class='ajax_DirectLink'>{$site_url}/img-{$view_id}.html</div>";
                    echo "<div style='display:none;' class='ajax_DirectLinkToImg'>{$rowFTP['url']}/{$dir2}/{$nameimage}</div>";

                } else {
                    echo "<p class='error'>Sorry, there was a problem uploading your file.</p>";
                }


            } // END ELSE IF FTP IS NOT 0

        } // END ELSE IF OK IS OK OK OK :D 0 = OK
    } // END FUNCTION ZIP UPLOAD
} // END CLASS


class db{
    function connect(){
        $link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
        $db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
        return $db;
    }

    function backup_tables($host,$user,$pass,$name,$tables = '*')
    {

        $link = mysql_connect($host,$user,$pass);
        mysql_select_db($name,$link);

        //get all of the tables
        if($tables == '*')
        {
            $tables = array();
            $result = mysql_query('SHOW TABLES');
            while($row = mysql_fetch_row($result))
            {
                $tables[] = $row[0];
            }
        }
        else
        {
            $tables = is_array($tables) ? $tables : explode(',',$tables);
        }

        //cycle through
        $return = "";
        foreach($tables as $table)
        {
            $result = mysql_query('SELECT * FROM '.$table);
            $num_fields = mysql_num_fields($result);


            $return.= 'DROP TABLE '.$table.';';
            $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
            $return.= "\n\n".$row2[1].";\n\n";

            for ($i = 0; $i < $num_fields; $i++)
            {
                while($row = mysql_fetch_row($result))
                {
                    $return.= 'INSERT INTO '.$table.' VALUES(';
                    for($j=0; $j<$num_fields; $j++)
                    {
                        $row[$j] = addslashes($row[$j]);
                        $row[$j] = preg_replace("/\n/","\\n",$row[$j]);
                        if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                        if ($j<($num_fields-1)) { $return.= ','; }
                    }
                    $return.= ");\n";
                }
            }
            $return.="\n\n\n";
        }

        //save file
        $handle = fopen('backup/db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
        fwrite($handle,$return);
        fclose($handle);
    }
}

class galery {
    private function randomImages(){
        $q = "SELECT * FROM images ORDER BY RAND() LIMIT 20";
        $result = mysql_query($q);
        while($rowRandomGallery = mysql_fetch_assoc($result)) {

        }
    }
    function userGalleries(){
        $q = "SELECT * FROM galleries WHERE id_user = '$_SESSION[user_id]'";
        $result = mysql_query($q);
        if(mysql_num_rows($result) > 0) {
            echo "<table class='userGalleries' border=0>
            <tr>
            <td style='min-width:200px;'>Name</td>
            <td>Edit</td>
            </tr>";
            while($rowGalleries = mysql_fetch_assoc($result)) {
                echo "<tr><td><a class='nicelinks' href='view_galleries.php?id=".$rowGalleries['id']."'>" . $rowGalleries['name'] . "</a></td> <td><a class='nicelinks' href='edit_gallery.php?id=".$rowGalleries['id']."'><img src='css/img/modify.gif' /></a></td></tr>";
            }
            echo "</table>";
            } else {
                    echo "No galleries added yet ... ";
            }
    }

    function moreFromThisGallery($idgallery){
        global $site_url;
        if($idgallery > 0) {

        $q = "SELECT images.view_id, images.views, images.name, images.date_added, images.ftp, sources.thumb2, sources.img, ftp_logins.url FROM images
             INNER JOIN sources ON images.source=sources.id
             LEFT JOIN ftp_logins ON images.ftp = ftp_logins.id
             WHERE images.gallery = '{$idgallery}'
             ORDER BY RAND() LIMIT 24";
            $result = mysql_query($q);
        while($rowMoreFromThis = mysql_fetch_assoc($result)){
            if($rowMoreFromThis['ftp'] > 0) {
                $real_site_url = $rowMoreFromThis['url'];
            } else {
                $real_site_url = $site_url;
            }
            $dirDate = preg_replace('/-/', '/', $rowMoreFromThis['date_added']);
            $dirThumb = $real_site_url . "/" . $rowMoreFromThis['thumb2'] . "/" . $dirDate . "/" . $rowMoreFromThis['name'];
            //$dirImg = $site_url . "/" . $rowMoreFromThis['img'] . "/" . $dirDate . "/" . $rowMoreFromThis['name'];
            echo "<div class='more_from_this_gallery'>";
            echo "<a href='img-{$rowMoreFromThis['view_id']}.html'><img src='{$dirThumb}' /></a>";
            echo "</div>";
        }




        }
    }




}

class configs {
private $config = array();
private $rowConfigs = array();


    public function fetch() {
        $this->config = array();
        $q = "SELECT title, text FROM configs";
        $result = mysql_query($q);
        while($this->rowConfigs = mysql_fetch_assoc($result)) {
            $this->config[''.$this->rowConfigs['title'].''] = htmlspecialchars_decode($this->rowConfigs['text']);
        }
        return $this->config;
    }


    public function update($text, $id) {
        $text = mysql_real_escape_string($text);
        if(is_numeric($id)) {
        $q = "UPDATE configs SET text = '$text' WHERE id = '$id'";
        $result = mysql_query($q);
            if($result) {
                return true;
            }
        }
    }

    public function account_expired($exp_date){
    $todays_date = date("Y-m-d");

    $today = strtotime($todays_date);
    $expiration_date = strtotime($exp_date);

        if ($expiration_date > $today) {
            return true;
        } else {
            return false;
        }
    }

    function checkData($mydate) {

        list($yy,$mm,$dd)=explode("-",$mydate);
        if (is_numeric($yy) && is_numeric($mm) && is_numeric($dd))
        {
            return checkdate($mm,$dd,$yy);
        }
        return false;
    }

    public function isPremium($id_user){
        if(isset($id_user) && $id_user !== 0 && is_numeric($id_user)) {
                $q = "SELECT user_level, premium FROM users WHERE id = {$id_user}";
                $result = mysql_query($q);
                $rowUserPremium = mysql_fetch_assoc($result);

            if($this->account_expired($rowUserPremium['premium'])){
                return true;
            } else {
                return false;
            }

            }  else {
            return false;
        }
    }

    public function isLocked($id_user){
        if(isset($id_user) && $id_user !== 0 && is_numeric($id_user)) {

            $q = "SELECT locked FROM users WHERE id = {$id_user}";
            $result = mysql_query($q);
            $rowUserPremium = mysql_fetch_assoc($result);
            switch($rowUserPremium['locked']){
                case 0:
                    return false;
                    break;
                case 1:
                    return true;
                    break;
            }
        }  else {
            return false;
        }
    }





}

class pagination
{
    public function __construct()
    {
    }
    public function calculate_pages($total_rows, $rows_per_page, $page_num)
    {
        $arr = array();
        // calculate last page
        $last_page = ceil($total_rows / $rows_per_page);
        // make sure we are within limits
        $page_num = (int) $page_num;
        if ($page_num < 1)
        {
            $page_num = 1;
        }
        elseif ($page_num > $last_page)
        {
            $page_num = $last_page;
        }
        $upto = ($page_num - 1) * $rows_per_page;
        $arr['limit'] = 'LIMIT '.$upto.',' .$rows_per_page;
        $arr['current'] = $page_num;
        if ($page_num == 1)
            $arr['previous'] = $page_num;
        else
            $arr['previous'] = $page_num - 1;
        if ($page_num == $last_page)
            $arr['next'] = $last_page;
        else
            $arr['next'] = $page_num + 1;
        $arr['last'] = $last_page;
        $arr['info'] = 'Page ('.$page_num.' of '.$last_page.')';
        $arr['pages'] = $this->get_surrounding_pages($page_num, $last_page, $arr['next']);
        return $arr;
    }
    function get_surrounding_pages($page_num, $last_page, $next)
    {
        $arr = array();
        $show = 5; // how many boxes
        // at first
        if ($page_num == 1)
        {
            // case of 1 page only
            if ($next == $page_num) return array(1);
            for ($i = 0; $i < $show; $i++)
            {
                if ($i == $last_page) break;
                array_push($arr, $i + 1);
            }
            return $arr;
        }
        // at last
        if ($page_num == $last_page)
        {
            $start = $last_page - $show;
            if ($start < 1) $start = 0;
            for ($i = $start; $i < $last_page; $i++)
            {
                array_push($arr, $i + 1);
            }
            return $arr;
        }
        // at middle
        $start = $page_num - $show;
        if ($start < 1) $start = 0;
        for ($i = $start; $i < $page_num; $i++)
        {
            array_push($arr, $i + 1);
        }
        for ($i = ($page_num + 1); $i < ($page_num + $show); $i++)
        {
            if ($i == ($last_page + 1)) break;
            array_push($arr, $i);
        }
        return $arr;
    }
}

?>

PHP Login system?

$
0
0

I'm trying to make a login system using two PHP scripts, a html and a text file. The html should link to the login.php which should get a name from the text file with all the usernames and passwords, then allow entry if correct while setting a cookie. The four files are called:

login.html

login.php

secured.php

user.txt

 

The code for the html is: 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
</head>
 
<body>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="login.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
 
</body>
</html>
 

 

 

The code for the login.php is:

 

<?php
 
while(!feof($fileHandle)) {
$Data=fgets($fileHandle);
$user=explode("|",$data);
$user[0];
$user[1];
$name=trim($user[0]);
$pass=trim($user[1]);
}
 
if($usern==$user && $passw==$password)
{
setcookie("uname",$usern);
header("Location:home.php");
exit();
}
?>
 

 

 

The code for the secured.php is:

 

<?php
 
$usern=$_GET['username'];
$passw=$_GET['password'];
 
$fileHandle=fopen('user.txt','r');
?>

 

 

 

I uploaded all four files to my local server then ran the html off that server by connecting to it directly within the URL bar. The login will just stay there not loading anything. I'll upload the files too.

Attached Files

mysql_num_rows() expects parameter 1 to be resource, boolean given in

$
0
0

The below is my code.... it works from webserver, not works in local host

 

<?php
include "connect.php";
if(isset($_POST["signup"]))
{
 $un=$_POST["uname"];
 $pw=$_POST["pwd"];
 $fn=$_POST["fname"];
 $ln=$_POST["lname"];
 $eml=$_POST["email"];
 $ph=$_POST["phone"];
 $gen=$_POST["radiobutton"];
 $ad=$_POST["add"];
 /*$phot=$_FILES["photo"]["name"];
 move_uploaded_file($_FILES["photo"]["tmp_name"],'../photo/'.$phot);*/
 $res=mysql_query("select * from users where uname='$un'"); 
 /*or email='$eml'"*/
 $row=mysql_num_rows($res);
 if($row==0)
 {
 mysql_query("insert into users(rdate,uname,pwd,fname,lname,email,phone,gender,address,sdate)values(CURDATE(),'$un','$pw','$fn','$ln','$eml','$ph','$gen','$ad',CURDATE())");
 echo "<script language='javascript'>alert('Registration Successfull, An activation email will be send in 24 hours to your email account, Pleace check and confirm, Thanks')</script>";
 
 }
 else
 {
  echo "<script language='javascript'>alert('Username or email already registered before, Please use different username or email')</script>";
 }
}
?>

 

Handling DB Connection

$
0
0

I'm in the process of coding  a PDO wrapper class, really as a learning project but want to get it right so I can expand it in the future.

 

Basically, I've written the following constructor to connect to the database:

public function __construct() {

//Set up the Database Source Name
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->name;

// Set up options
$option = array(
PDO::ATTR_PERSISTENT => true
);

// Create a new PDO instance
try {
$this->conn = new PDO($dsn, $this->user, $this->pass, $options);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

// Catch any errors
catch(PDOException $e) {
$this->error = $e->getMessage();
}

}

My question relates to creating a $db object, then using it in my other classes. I've read much about a singleton pattern (how it's best to avoid) and I like the ease of just being able to say DB::Query etc but I'm learning so I want to use best practices. At the moment, I use a factory class for creating objects and then using Dependency Injection to set up objects based on other classes.

 

So I have a couple of questions about the best way to go about this:

 

If I were to continue using my factory class, how do I got about using just one DB connection/object in that file? I had the thought of creating a base class for the factory which enables the DB connection, then setting it as a property so then I can just pass that property into the create object methods. Or when creating objects I could use $db = new Database(); but how do I ensure that I'm just using the one db connection (will my persistent attr in the constructor help there)? Return an instance?

 

Am I going in the right direction or is there a better way?

 

Is having an extrmely easy to use DB object (a singleton approach) actually okay in this instance?

 

Thanks in advance.

Unset variable/array which has been passed to function

$
0
0

Just a thought...

 

Is it possible to unset a global variable/array from within a function?  So basically I want to pass an array to a function to convert to a string then destroy the original array.  I'd like to keep it all contained within the function to reduce any additional clear-up scripting required.

 

Here's my example code below:

$GLOBALARRAY = array("keyname1" => "value1", "keyname2" => "value2");

$newstring = convertArrayToString($GLOBALARRAY, true);



function convertArrayToString($array, $unset = false) {

    $string = '';

    //Loop for each array value
    foreach ($array as $key => $value) {
        $string = $string . $key . '=' . $value ';';
    }

    if ($unset === true) {
        unset($GLOBALARRAY_WHICH_WAS_PASSED);
    }

    return $string;
} 

My guess is that I need to either get the name of the passed array or pass by reference?

 

Thanks for your thoughts.

 

Matt


product page - help

$
0
0
         Hi All,
   
   I don't know how to start better, but here goes. I'm a rookie when it comes to html/php codes(I've used dreamweaver), but this is my problem.. I've created a product page in html, but in 3 steps(3 html pages), and lets say I will give the link of my product to a potential customer. And he buys the product through all the 3 steps. And the 3th step the product is bought. 
   How can I do when the clients access the link again after he bought the product so that the product can appear "item has been bought". I don't want after clicking the link to begin again at first step. Hope you understand and I'll be waiting for opinion.
          Thanks

Trying to create an edit page using Quickform2

$
0
0

I've been trying to improve my php skills by reading and going through the examples (step by step in order) from the book "PHP Advanced and Object-Oriented Programming". I'll try to explain it the best that I can the problem I have followed with some code. I think I'll will start with code:

 

I have to grab the data for after all it's an edit page:

<?php # edit_page
// This page both displays and handles the "edit the page" form.
// Need the utilities file:
require('includes/utilities.inc.php');

     try {
        
         // Validate the page ID:
         if (!isset($_GET['id']) || !filter_var($_GET['id'], FILTER_VALIDATE_INT, array('min_range' => 1))) {
             throw new Exception('An invalid page ID was provided to this page.');
         }
        
         // Fetch the page from the database:
         $query = 'SELECT id, title, content, DATE_FORMAT(dateUpdated, "%e %M %Y") as dateUpdated FROM pages WHERE id=:id';
         $stmt = $pdo->prepare($query);
         $result = $stmt->execute(array(':id' => $_GET['id']));
        
         // If the query ran OK, fetch the record into an object:
         if($result) {
             $stmt->setFetchMode(PDO::FETCH_CLASS, 'Page');
             $page = $stmt->fetch();                
         } else {
             throw new Exception('An invalid page ID was provided to this page');
         }
        
     } catch(Exception $e) { // catch generic Exceptions
    
         $pageTitle = 'Error!';
         include('includes/header.inc.php');
         include('views/error.html');
        
     }

Then I have to setup my Quickform2 form

// Creat a new QuickForm2 form:
// set_include_path(get_include_path() . PATH_SEPARATOR . '/usr/local/pear/share/pear/');
require('HTML/QuickForm2.php');
$form = new HTML_QuickForm2('editPageForm' );

// Add the title field:
$title = $form->addElement('text', 'title');
$title->setLabel('Page Title');
$title->addFilter('strip_tags');
//$title->addRule('required', 'Please enter a page title');

// Add the content field:
$content = $form->addElement('textarea', 'content');
$content->setLabel('Page Content');
$content->addFilter('strip_tags');
$content->addFilter('trim');

//$content->addRule('required', 'Please enter the page content');
// Set defaults for the form elements
$form->addDataSource(new HTML_QuickForm2_DataSource_Array(array(
    'title' => $page->getTitle(),
    'content' => $page->getContent()
)));
// Add the submit button:
$submit = $form->addElement('submit', 'submit', array('value' => 'Edit This Page'));

and then I have to validate and submit the edited data to the database (This is where I run into problems)

// Check for a form submission:
if (!isset($_SERVER) && $_SERVER['REQUEST_METHOD'] == 'POST') { // Handle the form submission

    // Validate the form data:
    if ($form->validate()) {

        $query = 'UPDATE pages
                  SET creatorId=:creatorId,
                    title=:title,
                    content=:content,
                    dateUpdated=NOW()
                WHERE id=:id';
        // Insert into the database:
        //$query = 'INSERT INTO pages (creatorId, title, content, dateAdded) VALUES (:creatorId, :title, :content, NOW())';
        $stmt = $pdo->prepare($query);
        $result = $stmt->execute(array(':creatorId' => $user->getId(), ':title' => $title->getValue(), ':content' => $content->getValue(), ':id' => $page->getId()));
        
        // Freeze the form upon success:
        if ($result) {
            $form->toggleFrozen(true);
            $form->removeChild($submit);
        }
        
    } // End of form validation IF.
    
} // End of form submission IF.

 This is the error it gives:

Details (not for public consumption): An invalid page ID was provided to this page.

 
Notice: Undefined variable: page in C:\xampp\htdocs\php_test\chapter-09-CMS-with-OOP\edit_page.php on line 56

Fatal error: Call to a member function getTitle() on a non-object in C:\xampp\htdocs\php_test\chapter-09-CMS-with-OOP\edit_page.php on line 56

 

I think it might have something to do with the url being different (edit_page.php?id=5) vs (edit_page.php) when it kicks out the error.  I don't know if I have my query right or the POST right or what have you. This is the first time I really have been using PDO for previously I've been using mysqli to go back and forth to the MySQL database. I believe I have it right? Anyways, I apologize if I didn't make myself clear and I can always reply with more information if needed. I have gone to the author's forums, check the Quckform2 documentation, php.net manual  and have done a bunch of Google searches to no avail to fix the problem.

 

Well at least I know now how to catch an error, but now the thing is how to fix them. :happy-04:
 

Thanks,

           John

MySQL UNION help

$
0
0

I'm still working on my helpdesk report and am a long way down the line thanks to the help I've received in here.

 

Now, imagine a chart with the list of helpdesk members going across, left to right. Underneath each of them they have two headings (calls logged, calls resolved).

Going down the page we have months of the year. Using the following code I can populate an individual month's calls logged and calls resolved, but is there any way I can do a super-complicated UNION to fill in all the data, or even just one person's which could then be looped? Or is it a case of looping the query, replacing the user and the date?

Here's the code - clearly 'user1' and '2012-11%' need replacing with variables.


SELECT member, SUM(logged) as logged_count, SUM(resolved) as 

resolved_count
FROM
(
    SELECT logged_by as member, COUNT(item) as logged, 0 as 

resolved
    FROM incidents
    WHERE logged_by = 'user1'
    AND logged LIKE '2012-11%'
    GROUP BY logged_by
    UNION
    SELECT resolved_by as member, 0 as logged, COUNT(item) as 

resolved
    FROM incidents
    WHERE resolved_by = 'user1'
    AND logged LIKE '2012-11%'
    GROUP BY resolved_by
) as results

GROUP BY member

Please help me with this riddle

$
0
0

Hello

 

Can you help me?

I have 2 pc's A en B.

There is a program that I run.

 

If I run a particular php script then on pc A it hangs, on B it does not.

But when I do write statements to an out file I see that both programs have calculated and the script even returns after doing his work to the calling program.

So on pc A it does not 'see' it is finished.

 

To help:

There is a loop that loops around 2000 times each time after reading a record from a sql database.

If I break earlier for instance after 1500 times, then suddenly both programs end normally.

 

So the question. What could happen in a loop, that prevents a program from ending and hangs, while an other pc does not?

There is lots of processing after the loop, that is executed in both situations.

 

Both PC use IE but also Firefox does the same. On top of that also IE's version is the same on both PC's.

 

I am out of clues. Can you point me in the right direction?

please mail to empieters@gmail.com if you have questions.

Create a Breadcrumbs Trail For a Website

$
0
0

I've been trying to make a breadcrumbs navigation for a simple website which uses GET variables to determine what content to display, but it's proving a little bit more tricky than I thought. I've typed up a simple code already, but I'm looking to improve it and make it more dynamic:

<?php
$url_vars = array();//the correct GET variables
$url_vars[0] = 'girls';//www.mywebsite.com/girls
$url_vars[1] = 'boys';//www.mywebsite.com/boys

$url_exp = explode('/', $_SERVER['REQUEST_URI']);
$url_path = array();

foreach($url_exp as $shard){
	foreach($url_vars as $var){
		if($var == $shard){
			$url_path[] = $shard;
			break;
		}
	}
}


require 'pre_breadcrumbs.html';//displays home crumb
foreach($url_path as $crumb){
	echo ' -> ';
	$full_crumb = ucfirst($crumb);

	require 'breadcrumbs.html';//creates all the crumbs
}
?>

Any ideas?

 

Thanks.

Viewing all 13200 articles
Browse latest View live