Jump to content

cobusbo

Members
  • Posts

    224
  • Joined

  • Last visited

Posts posted by cobusbo

  1. Hi, Ive got a few records stored in my database and would wish to remove records older than 30 days. The thing is I got a field in my database table called pprofilepic which contains the directory of an image stored on my host. I would like to delete the image before removing the record from the database. Would I need to use the while loop to do so?

     

    Here is an example of database records output in php array

    $Users2 = array(
      array('ID' => '1','Username' => 'Cobus','mxitid' => 'Debater','mxitlogin' => '','nick' => '','phone' => '','location' => '','rank' => '1','registered' => '1443554980','last_online' => '1446482291','ip1' => '165.255.107.53','ip2' => '165.255.107.53','pprofilepic' => 'uploads/resized_1_1444068533.jpg','aprove' => 'yes','pname' => '','psname' => '','pgender' => '','pmarital' => '','plocation' => '','phobbies' => '','pabout_myself' => '','pdob' => '0000-00-00'),
      array('ID' => '2','Username' => 'AKA IV LEAGUE','mxitid' => 'm61831903002','mxitlogin' => '1998xtreme25','nick' => 'king"othello','phone' => 'ZTE/V795','location' => 'ZA,,,,,,212881,29608915838,1387f57','rank' => '2','registered' => '1443555418','last_online' => '1446731775','ip1' => '1c6ff112add9dc7a5594dec967be0f7a','ip2' => '196.35.255.31','pprofilepic' => 'images/resized_2_1446642825.jpg','aprove' => 'no','pname' => 'Akaworldwide','psname' => '','pgender' => 'Male','pmarital' => 'Not Saying','plocation' => 'South Africa »»KZN»»Durban','phobbies' => 'Programming - watching & playing soccer ','pabout_myself' => 'Humble guy down to earth- also short tempered - so watch what to say to me:)','pdob' => '1998-03-25'),
    
    

    And here is my Code I put together so far but not sure if im on the right track.

    <?
    
    $result9 = mysql_query("SELECT * FROM Users2 WHERE last_online < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 DAY))");
            while($row = mysql_fetch_array($result9)){
             $ppic = $row['pprofilepic'];
    $id = $row['ID'];
    
    $unlink($ppic);
        $query = "DELETE FROM Users2 WHERE ID ='".$id."'"; 
        mysql_query($query);
    
    
    }
    
    
    
    
    
    ?>
    
    
  2. Because you use SELECT * there is no way I can know what you really want from the table. You could

    SELECT name, MAX(date) FROM table GROUP BY name

    but, as I said, I don't know what else you want

    I'm using a chat but with each post the person make it stores the current date in database in the StringyChat_time field.

     

    So What I'm basically trying to do is creating an active unique users list for the last hour sorted according to the latest post made in the chat, but since I'm grouping the Names it select the first date stored by the name and not the last post made

    <html><head>
            <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
            <meta name="mxit" content="clearscreen" />
    
    
    </head>
    <body><br>
    <?
        include("chat_code_header.php");
    
    header('Content-Type: text/html; charset=ISO-8859-1');
    
    ////////Users/////////
    ?><br>
    <b><u>Chatters</u></b><br>
    <?
    
    // find out how many rows are in the table 
    
    $galleries = array('ADMIN','Moderator','Global Helper','Helper','!!!ANNOUNCEMENT!!!','!!!TOPIC CHANGE!!!');
    
    $sql = "SELECT COUNT(*) FROM StringyChat WHERE StringyChat_time  >= (UNIX_TIMESTAMP() - 3600) AND StringyChat_name NOT IN ( '" . implode($galleries, "', '") . "' ) GROUP BY StringyChat_name";
    $result = mysql_query($sql, $db) or trigger_error("SQL", E_USER_ERROR);
    $r = mysql_fetch_row($result);
    $numrows = $r[0];
    
    // number of rows to show per page
    $rowsperpage = 10;
    // find out total pages
    $totalpages = ceil($numrows / $rowsperpage);
    
    // get the current page or set a default
    if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
       // cast var as int
       $currentpage = (int) $_GET['currentpage'];
    } else {
       // default page num
       $currentpage = 1;
    } // end if
    
    // if current page is greater than total pages...
    if ($currentpage > $totalpages) {
       // set current page to last page
       $currentpage = $totalpages;
    } // end if
    // if current page is less than first page...
    if ($currentpage < 1) {
       // set current page to first page
       $currentpage = 1;
    } // end if
    
    // the offset of the list, based on current page 
    $offset = ($currentpage - 1) * $rowsperpage;
    
    $testip = $_SERVER["HTTP_X_MXIT_USERID_R"];
    if(!isset($testip))
    {
    	$testip = "Debater";
    
    }
    
    
    $galleries = array('ADMIN','Moderator','Global Helper','Helper','!!!ANNOUNCEMENT!!!','!!!TOPIC CHANGE!!!');
    
    
    $sql = "SELECT StringyChat_name, StringyChat_ip, StringyChat_time FROM StringyChat WHERE StringyChat_time  >= (UNIX_TIMESTAMP() - 3600) AND StringyChat_name NOT IN ( '" . implode($galleries, "', '") . "' ) GROUP BY StringyChat_name ORDER BY StringyChat_time DESC LIMIT $offset, $rowsperpage";
    $result1 = mysql_query($sql, $db)or die($sql."<br/><br/>".mysql_error());
    
    
    
    while($myrow = mysql_fetch_array($result1))
    {
    $ipi = $myrow['StringyChat_ip'];
    
    $sqlid = "SELECT * FROM Users2 WHERE mxitid = '$ipi'";
    $resultid = mysql_query($sqlid, $db)or die($sqlid."<br/><br/>".mysql_error());
    
    $myrowid = mysql_fetch_array($resultid);
    
    
    
    
    
    
    
    $time = time();
    
    
    $id = $myrowid['ID'];
    $nname = $myrow['StringyChat_name'];
    
    
    
    $ip = mysql_real_escape_string($myrow["ip"]);
    $expire = $myrow["StringyChat_time"];
    $dt1 = new DateTime();
    $dt1->setTimestamp($expire);      // SET TIMESTAMP VALUE (RTFM)
    
    $dt2=new DateTime(); // Now
    $dif = $dt2->diff($dt1);
    if ($dif->i < 1) {        // if more than 1000 years
        $diff = 'now';
    } else {
        $diff = $dif->format('%m mnths, %d d, %h hrs, %i min, %s secs');
    }
    $banu = '<a href="' . $domain . '/ranklist.php?ban=' . 'demote' . '&nname=' . $nname . '&ip=' . $ipi .'">Demote</a>';
    
    print '<a href="' . $domain . '/pmr.php?id=' . $id . '&ip=' . $ipi . '&nname=' . $nname . '">' .  $myrow['StringyChat_name']. '</a>' . ' - ' . $diff . '<br>';
    
    }
    
    
  3. When you GROUP BY (in this case) name you get ONE row for each name. If a particular name has 100 records with different times it can only display the time from one of the records. The manuals states the choice will be arbitrary but it usually takes the first value from the group - hence the oldest.

    So there isn't a way to recall the Unique names and display it according to latest date?

  4. Hi I'm trying to recall a list of names of people who posted something according to the StringyChat_time field within the hour. The problem is it doesn't select the latest record, but rather the oldest one within the hour how can I select the latest time record?

    $galleries = array('ADMIN','Moderator','Global Helper','Helper','!!!ANNOUNCEMENT!!!','!!!TOPIC CHANGE!!!');
    
    
    $sql = "SELECT * FROM StringyChat WHERE StringyChat_time  >= (UNIX_TIMESTAMP() - 3600) AND StringyChat_name NOT IN ( '" . implode($galleries, "', '") . "' ) GROUP BY StringyChat_name ORDER BY StringyChat_time DESC LIMIT $offset, $rowsperpage";
    $result1 = mysql_query($sql, $db)or die($sql."<br/><br/>".mysql_error());
    
    
  5.  

    Hi there guys,

    I've a little problem with inserting a file name into a database table. I can't see wich is the problem. The code is bellow and i think the problem is at INSERT INTO part.

        <?php
      $path = "./cv/";
    
    $valid_formats = array("doc", "pdf");
    if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
    {
      $name = $_FILES['photoimg']['name'];
      $size = $_FILES['photoimg']['size'];
      if(strlen($name))
      {
        list($txt, $ext) = explode(".", $name);
        if(in_array($ext,$valid_formats))
        {
          if($size<(20480*20480)) // Image size max 20 MB
          {
            $actual_image_name = time().$id.".".$ext;
            $tmp = $_FILES['photoimg']['tmp_name'];
            if(move_uploaded_file($tmp, $path.$actual_image_name))
            {
              mysqli_query($mysqli,"INSERT INTO formular_client (client_cv = '$actual_image_name')");
            }
            else
              echo "failed";
          } 
          else
            echo "Image file size max 20 MB"; 
        }
        else
          echo "Invalid file format.."; 
      }
    }
    ?>
    
    <input type="file" name="photoimg" id="photoimg" />
    

    Check my topic

     

    I had similar situation regarding Mime checking I think You should use mime types as well and not explode to get file ext.

     

     

    I'm not an expert with mysqli but try 

    mysqli_query($mysqli,"INSERT INTO `formular_client` (`client_cv`) = (`$actual_image_name`)");
    
  6. Thank you!

     

    For someone else who wish to use something similar here is my final script

    <?php
        include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php';
        include $_SERVER['DOCUMENT_ROOT'] . '/chat2/smart_resize_image.function.php';
    
    
    $ip = $_SERVER["HTTP_X_MXIT_USERID_R"];
    if(!isset($ip))
    {
    	$ip = "Debater";
    }
    
    $time = date_create()->getTimestamp();
    
    $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\"");
            $row = mysql_fetch_array($result9);
    $id = $row['ID'];
    
    
    
    
    
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
       $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    $extensions = array(
        'image/jpeg' => 'jpg',
        'image/png'  => 'png',
        'image/gif'  => 'gif',
        'image/bmp'  => 'bmp',
    );
    
    $extension = $extensions[$check['mime']]; 
    $target_dir = "images/";
    $target_file = $target_dir . $id . "_" . $time . "." . $extension;
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    
    
    
    
    
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if (!in_array($check['mime'], array_keys($extensions))) {    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    
    
         //indicate which file to resize (can be any type jpg/png/gif/etc...)
          $file = $target_file;
    
          //indicate the path and name for the new resized file
          $resizedFile = $target_dir . "resized_" . $id . "_" . $time . "." . $extension;
    
          //call the function (when passing path to pic)
          smart_resize_image($file , null, 320, 240, false , $resizedFile , true , false ,75 );
    
    
    $resultc = mysql_query("SELECT * FROM Users2 WHERE mxitid = '$ip'");
    
            $rowc = mysql_fetch_array($resultc);
             $ppica = $rowc['pprofilepic'];
    
    unlink($ppica);
    $naam = "ADMIN";
    $naam2 = $rowc['Username'];
    
    $msg = "You Requested a Profile Picture change, please wait till an Admin can manage the request";
    $msg1 = "Please aprove my Profile Picture";
    
    $post_time = date("U");
    $read1 = "unread";
    $banby2 = "ADMIN";
    $result = mysql_query("UPDATE Users2 SET pprofilepic='$resizedFile', aprove='requested' WHERE mxitid='$ip'") 
    or die(mysql_error());  
    
    
    
    
    $query1 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam\",\"$ip\",\"$msg\",\"$post_time\",\"$read1\",\"$banby2\")";
    
        $result1 = mysql_query($query1, $db) or die("Invalid query: " . mysql_error());
    
    $query2 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam2\",\"$banby2\",\"$msg1\",\"$post_time\",\"$read1\",\"$ip\")";
    
        $result2 = mysql_query($query2, $db) or die("Invalid query: " . mysql_error());
    
    
    
    
    
    
    
    
    
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
    
    if($result){
    header('Location: ../profile/thankyou.php');
    }
    else {
    echo "ERROR";
    }
    
    ?>
    
  7. Thank you

     

    Just one last question I'm storing the path the file in my database table, How would I first check my table field if it already have the path to a previous picture and if it does unlink the picture from the directory before storing the new file in the directory and update the field in my database?

     

    To retrieve the field I will use

    $resultc = mysql_query("SELECT * FROM Users2 WHERE mxitid = '$ip'");
    
            $rowc = mysql_fetch_array($resultc);
             $ppica = $rowc['pprofilepic'];
    

    Here is my latest code

    <?php
        include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php';
        include $_SERVER['DOCUMENT_ROOT'] . '/chat2/smart_resize_image.function.php';
    
    
    $ip = $_SERVER["HTTP_X_MXIT_USERID_R"];
    if(!isset($ip))
    {
    	$ip = "Debater";
    }
    
    $time = date_create()->getTimestamp();
    
    $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\"");
            $row = mysql_fetch_array($result9);
    $id = $row['ID'];
    
    
    
    
    
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
       $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    $extensions = array(
                'image/jpeg' => 'jpg',
        'image/png'  => 'png',
        'image/gif'  => 'gif',
    );
    
    $extension = $extensions[$check['mime']]; 
    $target_dir = "uploads/";
    $target_file = $target_dir . $id . "_" . $time . "." . $extension;
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    
    
    
    
    
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if (!in_array($check['mime'], array_keys($extensions))) {    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    
    
         //indicate which file to resize (can be any type jpg/png/gif/etc...)
          $file = $target_file;
    
          //indicate the path and name for the new resized file
          $resizedFile = $target_dir . "resized_" . $id . "_" . $time . "." . $extension;
    
          //call the function (when passing path to pic)
          smart_resize_image($file , null, 320, 240, false , $resizedFile , true , false ,75 );
    
    
    $resultc = mysql_query("SELECT * FROM Users2 WHERE mxitid = '$ip'");
    
            $rowc = mysql_fetch_array($resultc);
             $ppica = $rowc['pprofilepic'];
    $naam = "ADMIN";
    $naam2 = $rowc['Username'];
    
    $msg = "You Requested a Profile Picture change, please wait till an Admin can manage the request";
    $msg1 = "Please aprove my Profile Picture";
    
    $post_time = date("U");
    $read1 = "unread";
    $banby2 = "ADMIN";
    $result = mysql_query("UPDATE Users2 SET pprofilepic='$resizedFile', aprove='requested' WHERE mxitid='$ip'") 
    or die(mysql_error());  
    unlink($ppica);
    
    
    
    $query1 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam\",\"$ip\",\"$msg\",\"$post_time\",\"$read1\",\"$banby2\")";
    
        $result1 = mysql_query($query1, $db) or die("Invalid query: " . mysql_error());
    
    $query2 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam2\",\"$banby2\",\"$msg1\",\"$post_time\",\"$read1\",\"$ip\")";
    
        $result2 = mysql_query($query2, $db) or die("Invalid query: " . mysql_error());
    
    
    
    
    
    
    
    
    
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
    
    if($result){
    header('Location: ../profile/thankyou.php');
    }
    else {
    echo "ERROR";
    }
    
    ?>
    
  8. It's cleaner to have a list of allowed MIME types and compare the uploaded file's MIME type to that list, as I have demonstrated in my earlier post.

     

     

    You checked that it's a valid image as determined by getimagesize(), but you have not checked that it matches the file types that you want to allow.

     

    Another problem that I see is that you're assuming a specific naming convention for a file.

    A file can have many dots in the name and still be valid. Instead, you should use the extension that is associated with the MIME type of the file.

    $extensions = array(
        'image/jpeg' => 'jpg',
        'image/png'  => 'png',
        'image/gif'  => 'gif',
    );
    
    $extension = $extensions($check['mime']);
    You can also use that array to check if the image is an allowed MIME type. You can either just do a simple isset($extensions[$check['mime']]), or use in_array:

    if (!in_array($check['mime'], array_keys($extensions))) {
        // not a valid image
    }

    Ok so I implemented the changes but getting the error

     

     

     

     

    File is an image - image/jpeg.

    Fatal error: Function name must be a string in /home/u342037492/public_html/chat2/profile/new.php on line 44
    <?php
        include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php';
        include $_SERVER['DOCUMENT_ROOT'] . '/chat2/smart_resize_image.function.php';
    
    
    $ip = $_SERVER["HTTP_X_MXIT_USERID_R"];
    if(!isset($ip))
    {
    	$ip = "Debater";
    }
    
    $time = date_create()->getTimestamp();
    
    $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\"");
            $row = mysql_fetch_array($result9);
    $id = $row['ID'];
    
    
    
    
    
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
       $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    $extensions = array(
      'png' => 'image/png',
                'jpe' => 'image/jpeg',
                'jpeg' => 'image/jpeg',
                'jpg' => 'image/jpeg',
                'gif' => 'image/gif',
                'bmp' => 'image/bmp',);
    
    $extension = $extensions($check['mime']);
    $target_dir = "uploads/";
    $target_file = $target_dir . $id . "_" . $time . "." . $extension;
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    
    
    
    
    
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if (!in_array($check['mime'], array_keys($extensions))) {    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    
    
         //indicate which file to resize (can be any type jpg/png/gif/etc...)
          $file = $target_file;
    
          //indicate the path and name for the new resized file
          $resizedFile = $target_dir . "resized_" . $id . "_" . $time . "." . $extension;
    
          //call the function (when passing path to pic)
          smart_resize_image($file , null, 320, 240, false , $resizedFile , true , false ,100 );
    
    
    
    
    
    
    
    
    
    
    
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
    ?>
    
  9. But not here:

    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {

    So I should change it to

    if($check["mime"] != "image/jpg" && $check["mime"] != "image/png" && $check["mime"] != "image/jpeg"
    && $check["mime"] != "image/gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;

    or just remove it because I've already checked it before?

  10. You're still only checking the file extension to determine if it is a valid jpg, png, or gif. The file extension is completely made up. You need to check the MIME type.

    
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
    
    

    I am checking the mime type here?

  11. Ok so after a lot of tries I decided to put something new together

    <?php
        include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php';
        include $_SERVER['DOCUMENT_ROOT'] . '/chat2/smart_resize_image.function.php';
    
    
    $ip = $_SERVER["HTTP_X_MXIT_USERID_R"];
    if(!isset($ip))
    {
    	$ip = "Debater";
    }
    
    $time = date_create()->getTimestamp();
    
    $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\"");
            $row = mysql_fetch_array($result9);
    $id = $row['ID'];
    
    
    
    
    
    
    $target_dir = "images/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    
    
         //indicate which file to resize (can be any type jpg/png/gif/etc...)
          $file = $target_file;
    
          //indicate the path and name for the new resized file
          $resizedFile = 'your_path_to_file/resized_File.png';
    
          //call the function (when passing path to pic)
          smart_resize_image($file , null, 320, 240, false , $resizedFile , true , false ,100 );
    
    
    
    
    
    
    
    
    
    
    
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
    ?>
    
    smart_resize_image.function.php

    <?php
    /**
     * easy image resize function
     * @param  $file - file name to resize
     * @param  $string - The image data, as a string
     * @param  $width - new image width
     * @param  $height - new image height
     * @param  $proportional - keep image proportional, default is no
     * @param  $output - name of the new file (include path if needed)
     * @param  $delete_original - if true the original image will be deleted
     * @param  $use_linux_commands - if set to true will use "rm" to delete the image, if false will use PHP unlink
     * @param  $quality - enter 1-100 (100 is best quality) default is 100
     * @return boolean|resource
     */
      function smart_resize_image($file,
                                  $string             = null,
                                  $width              = 0, 
                                  $height             = 0, 
                                  $proportional       = false, 
                                  $output             = 'file', 
                                  $delete_original    = true, 
                                  $use_linux_commands = false,
      							  $quality = 100
      		 ) {
          
        if ( $height <= 0 && $width <= 0 ) return false;
        if ( $file === null && $string === null ) return false;
        # Setting defaults and meta
        $info                         = $file !== null ? getimagesize($file) : getimagesizefromstring($string);
        $image                        = '';
        $final_width                  = 0;
        $final_height                 = 0;
        list($width_old, $height_old) = $info;
    	$cropHeight = $cropWidth = 0;
        # Calculating proportionality
        if ($proportional) {
          if      ($width  == 0)  $factor = $height/$height_old;
          elseif  ($height == 0)  $factor = $width/$width_old;
          else                    $factor = min( $width / $width_old, $height / $height_old );
          $final_width  = round( $width_old * $factor );
          $final_height = round( $height_old * $factor );
        }
        else {
          $final_width = ( $width <= 0 ) ? $width_old : $width;
          $final_height = ( $height <= 0 ) ? $height_old : $height;
    	  $widthX = $width_old / $width;
    	  $heightX = $height_old / $height;
    	  
    	  $x = min($widthX, $heightX);
    	  $cropWidth = ($width_old - $width * $x) / 2;
    	  $cropHeight = ($height_old - $height * $x) / 2;
        }
        # Loading image to memory according to type
        switch ( $info[2] ) {
          case IMAGETYPE_JPEG:  $file !== null ? $image = imagecreatefromjpeg($file) : $image = imagecreatefromstring($string);  break;
          case IMAGETYPE_GIF:   $file !== null ? $image = imagecreatefromgif($file)  : $image = imagecreatefromstring($string);  break;
          case IMAGETYPE_PNG:   $file !== null ? $image = imagecreatefrompng($file)  : $image = imagecreatefromstring($string);  break;
          default: return false;
        }
        
        
        # This is the resizing/resampling/transparency-preserving magic
        $image_resized = imagecreatetruecolor( $final_width, $final_height );
        if ( ($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG) ) {
          $transparency = imagecolortransparent($image);
          $palletsize = imagecolorstotal($image);
          if ($transparency >= 0 && $transparency < $palletsize) {
            $transparent_color  = imagecolorsforindex($image, $transparency);
            $transparency       = imagecolorallocate($image_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
            imagefill($image_resized, 0, 0, $transparency);
            imagecolortransparent($image_resized, $transparency);
          }
          elseif ($info[2] == IMAGETYPE_PNG) {
            imagealphablending($image_resized, false);
            $color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
            imagefill($image_resized, 0, 0, $color);
            imagesavealpha($image_resized, true);
          }
        }
        imagecopyresampled($image_resized, $image, 0, 0, $cropWidth, $cropHeight, $final_width, $final_height, $width_old - 2 * $cropWidth, $height_old - 2 * $cropHeight);
    	
    	
        # Taking care of original, if needed
        if ( $delete_original ) {
          if ( $use_linux_commands ) exec('rm '.$file);
          else @unlink($file);
        }
        # Preparing a method of providing result
        switch ( strtolower($output) ) {
          case 'browser':
            $mime = image_type_to_mime_type($info[2]);
            header("Content-type: $mime");
            $output = NULL;
          break;
          case 'file':
            $output = $file;
          break;
          case 'return':
            return $image_resized;
          break;
          default:
          break;
        }
        
        # Writing image according to type to the output destination and image quality
        switch ( $info[2] ) {
          case IMAGETYPE_GIF:   imagegif($image_resized, $output);    break;
          case IMAGETYPE_JPEG:  imagejpeg($image_resized, $output, $quality);   break;
          case IMAGETYPE_PNG:
            $quality = 9 - (int)((0.9*$quality)/10.0);
            imagepng($image_resized, $output, $quality);
            break;
          default: return false;
        }
        return true;
      }
    
    The new problem I have now is the renaming of the files I uploaded to $id . "_" . $time . "File Ext"..... and with the resized file I want to rename the resized file to resiezed_$id . "_". $time . "File Ext"

     

    Ok so I used $kaboom to explode the filename, but now the script don't seem to run correctly it tells me that its an image/jpeg mime but also tells me its not a jpg png or gif 

     

    File is an image - image/jpeg.Sorry, only JPG, JPEG, PNG & GIF files are allowed.Sorry, your file was not uploaded.

    I have no idea where I'm going wrong with this code?

    <?php
        include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php';
        include $_SERVER['DOCUMENT_ROOT'] . '/chat2/smart_resize_image.function.php';
    
    
    $ip = $_SERVER["HTTP_X_MXIT_USERID_R"];
    if(!isset($ip))
    {
    	$ip = "Debater";
    }
    
    $time = date_create()->getTimestamp();
    
    $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\"");
            $row = mysql_fetch_array($result9);
    $id = $row['ID'];
    
    $fileName = $_FILES["fileToUpload"]["name"]; // The file name
    $kaboom = explode(".", $fileName); // Split file name into an array using the dot
    
    
    
    
    $target_dir = "uploads/";
    $target_file = $target_dir . $id . "_" . $time . "." . $kaboom[2];
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    
    
         //indicate which file to resize (can be any type jpg/png/gif/etc...)
          $file = $target_file;
    
          //indicate the path and name for the new resized file
          $resizedFile = $target_dir . "resized_" . $id . "_" . $time . "." . $kaboom[2];
    
          //call the function (when passing path to pic)
          smart_resize_image($file , null, 320, 240, false , $resizedFile , true , false ,100 );
    
    
    
    
    
    
    
    
    
    
    
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
    ?>
    
  12. I think i know why it won't insert a new data in PHPmyadmin, It show the error in the function in the database, the message showed "A fatal JavaScript error has occur". It must prevent the add a new data in the database. 

     

    Of course, I removed StudentiD and NULL from function already, but still won't add the new data...

    Where is the form?

  13. how can i use implode() on a multi dimensional array?

    say I have:

    $cars = array
      (
      array("Volvo",22,18),
      array("BMW",15,13),
      array("Saab",5,2),
      array("Land Rover",17,15)
      );
    

    And  i say:

     implode('||',$cars);
    
    

    what will it be like in the string ?what effect will it have on the inner child arrays of $cars?will they also have the  '||' as separator?

    Test it

    $str = implode('||',$cars);
    echo $string;

    and read here

  14.  

    Hi everyone,

     

    I'm sure you have seen me around in here by learning PHP, I am getting advance now. But I don't understand why it won't insert in PHPmyadmin (MySQL) with my prompt in php. Can you find why it won't add name as insert into my database?

     

    if ($_POST['submmited']) 
    {
    $first = $_POST['firstname'];
    $last = $_POST['lastname'];
    $email = $_POST['email'];
     
    if ($first && $last && $email) {
    $sql = "INSERT INTO Student (StudentID,Firstname,LastName,Email) VALUES (NULL,'$first','$last','$email')";
    mysqli_query($Garydb, $sql);
    }
    else {
    echo "Failed to add register";
    }
    }
     
    I checked around, there is no mistake but it won't add a new as insert into my database...why? What Did I do wrong?
     
    Thank you in advance
     
    Gary

     

    If the StudentID is an Auto Increase Int don't mention it in your query and try the delimited sign

    $sql = "INSERT INTO Student (`Firstname`,`LastName`,`Email`) VALUES (`$first`,`$last`,`$email`)";
  15. Ok so after a lot of tries I decided to put something new together

    <?php
        include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php';
        include $_SERVER['DOCUMENT_ROOT'] . '/chat2/smart_resize_image.function.php';
    
    
    $ip = $_SERVER["HTTP_X_MXIT_USERID_R"];
    if(!isset($ip))
    {
    	$ip = "Debater";
    }
    
    $time = date_create()->getTimestamp();
    
    $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\"");
            $row = mysql_fetch_array($result9);
    $id = $row['ID'];
    
    
    
    
    
    
    $target_dir = "images/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    
    
         //indicate which file to resize (can be any type jpg/png/gif/etc...)
          $file = $target_file;
    
          //indicate the path and name for the new resized file
          $resizedFile = 'your_path_to_file/resized_File.png';
    
          //call the function (when passing path to pic)
          smart_resize_image($file , null, 320, 240, false , $resizedFile , true , false ,100 );
    
    
    
    
    
    
    
    
    
    
    
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
    ?>
    

    smart_resize_image.function.php

    <?php
    /**
     * easy image resize function
     * @param  $file - file name to resize
     * @param  $string - The image data, as a string
     * @param  $width - new image width
     * @param  $height - new image height
     * @param  $proportional - keep image proportional, default is no
     * @param  $output - name of the new file (include path if needed)
     * @param  $delete_original - if true the original image will be deleted
     * @param  $use_linux_commands - if set to true will use "rm" to delete the image, if false will use PHP unlink
     * @param  $quality - enter 1-100 (100 is best quality) default is 100
     * @return boolean|resource
     */
      function smart_resize_image($file,
                                  $string             = null,
                                  $width              = 0, 
                                  $height             = 0, 
                                  $proportional       = false, 
                                  $output             = 'file', 
                                  $delete_original    = true, 
                                  $use_linux_commands = false,
      							  $quality = 100
      		 ) {
          
        if ( $height <= 0 && $width <= 0 ) return false;
        if ( $file === null && $string === null ) return false;
        # Setting defaults and meta
        $info                         = $file !== null ? getimagesize($file) : getimagesizefromstring($string);
        $image                        = '';
        $final_width                  = 0;
        $final_height                 = 0;
        list($width_old, $height_old) = $info;
    	$cropHeight = $cropWidth = 0;
        # Calculating proportionality
        if ($proportional) {
          if      ($width  == 0)  $factor = $height/$height_old;
          elseif  ($height == 0)  $factor = $width/$width_old;
          else                    $factor = min( $width / $width_old, $height / $height_old );
          $final_width  = round( $width_old * $factor );
          $final_height = round( $height_old * $factor );
        }
        else {
          $final_width = ( $width <= 0 ) ? $width_old : $width;
          $final_height = ( $height <= 0 ) ? $height_old : $height;
    	  $widthX = $width_old / $width;
    	  $heightX = $height_old / $height;
    	  
    	  $x = min($widthX, $heightX);
    	  $cropWidth = ($width_old - $width * $x) / 2;
    	  $cropHeight = ($height_old - $height * $x) / 2;
        }
        # Loading image to memory according to type
        switch ( $info[2] ) {
          case IMAGETYPE_JPEG:  $file !== null ? $image = imagecreatefromjpeg($file) : $image = imagecreatefromstring($string);  break;
          case IMAGETYPE_GIF:   $file !== null ? $image = imagecreatefromgif($file)  : $image = imagecreatefromstring($string);  break;
          case IMAGETYPE_PNG:   $file !== null ? $image = imagecreatefrompng($file)  : $image = imagecreatefromstring($string);  break;
          default: return false;
        }
        
        
        # This is the resizing/resampling/transparency-preserving magic
        $image_resized = imagecreatetruecolor( $final_width, $final_height );
        if ( ($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG) ) {
          $transparency = imagecolortransparent($image);
          $palletsize = imagecolorstotal($image);
          if ($transparency >= 0 && $transparency < $palletsize) {
            $transparent_color  = imagecolorsforindex($image, $transparency);
            $transparency       = imagecolorallocate($image_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
            imagefill($image_resized, 0, 0, $transparency);
            imagecolortransparent($image_resized, $transparency);
          }
          elseif ($info[2] == IMAGETYPE_PNG) {
            imagealphablending($image_resized, false);
            $color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
            imagefill($image_resized, 0, 0, $color);
            imagesavealpha($image_resized, true);
          }
        }
        imagecopyresampled($image_resized, $image, 0, 0, $cropWidth, $cropHeight, $final_width, $final_height, $width_old - 2 * $cropWidth, $height_old - 2 * $cropHeight);
    	
    	
        # Taking care of original, if needed
        if ( $delete_original ) {
          if ( $use_linux_commands ) exec('rm '.$file);
          else @unlink($file);
        }
        # Preparing a method of providing result
        switch ( strtolower($output) ) {
          case 'browser':
            $mime = image_type_to_mime_type($info[2]);
            header("Content-type: $mime");
            $output = NULL;
          break;
          case 'file':
            $output = $file;
          break;
          case 'return':
            return $image_resized;
          break;
          default:
          break;
        }
        
        # Writing image according to type to the output destination and image quality
        switch ( $info[2] ) {
          case IMAGETYPE_GIF:   imagegif($image_resized, $output);    break;
          case IMAGETYPE_JPEG:  imagejpeg($image_resized, $output, $quality);   break;
          case IMAGETYPE_PNG:
            $quality = 9 - (int)((0.9*$quality)/10.0);
            imagepng($image_resized, $output, $quality);
            break;
          default: return false;
        }
        return true;
      }
    

    The new problem I have now is the renaming of the files I uploaded to $id . "_" . $time . "File Ext"..... and with the resized file I want to rename the resized file to resiezed_$id . "_". $time . "File Ext"

  16. You see the problem I'm experiencing is the fact that if the photo is jpeg the photo get resized and stored as .JPEG but if a photo is png or gif it gets converted to jpg and stored as  .jpg. I cant change the the file Ext to jpg after resizing it because my script need to know the file type to convert it. I made a few changes to my script this is how it is now but I still have the same problem... If there is another better simpler way to do it can someone please point me in the right direction because after searching all over its the best example I could find to support my needs...

    <?php
        include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php';
    $ip = $_SERVER["HTTP_X_MXIT_USERID_R"];
    if(!isset($ip))
    {
    	$ip = "Debater";
    }
    
    $time = date_create()->getTimestamp();
    
    $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\"");
            $row = mysql_fetch_array($result9);
    $id = $row['ID'];
    
    // Access the $_FILES global variable for this specific file being uploaded
    // and create local PHP variables from the $_FILES array of information
    $fileName = $_FILES["uploaded_file"]["name"]; // The file name
    $fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder
    $fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is
    $fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes
    $fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true
    $fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); // filter the $filename
    
    
    $kaboom = explode(".", $fileName); // Split file name into an array using the dot
    
    
    
    
     $imageTypeArray = array
        (
            0=>'UNKNOWN',
            1=>'GIF',
            2=>'JPEG',
            3=>'PNG',
            4=>'SWF',
            5=>'PSD',
            6=>'BMP',
            7=>'TIFF_II',
            8=>'TIFF_MM',
            9=>'JPC',
            10=>'JP2',
            11=>'JPX',
            12=>'JB2',
            13=>'SWC',
            14=>'IFF',
            15=>'WBMP',
            16=>'XBM',
            17=>'ICO',
            18=>'COUNT'  
        );
        
        $size = getimagesize($fileTmpLoc);
        
        $size[2] = $imageTypeArray[$size[2]];
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    $fileExt = $size[2]; // Now target the last array element to get the file extension
    
    
    // START PHP Image Upload Error Handling --------------------------------
    if (!$fileTmpLoc) { // if file not chosen
        echo "ERROR: Please browse for a file before clicking the upload button.";
        exit();
    } else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes
        echo "ERROR: Your file was larger than 5 Megabytes in size.";
        unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
        exit();
    } else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) {
         // This condition is only if you wish to allow uploading of specific file types    
         echo "ERROR: Your image was not .gif, .jpg, or .png.";
         unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
         exit();
    } else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
        echo "ERROR: An error occured while processing the file. Try again.";
        exit();
    }
    // END PHP Image Upload Error Handling ----------------------------------
    // Place it into your "uploads" folder mow using the move_uploaded_file() function
    $moveResult = move_uploaded_file($fileTmpLoc, "images/".$id."_".$time.".".$fileExt);
    // Check to make sure the move result is true before continuing
    if ($moveResult != true) {
        echo "ERROR: File not uploaded. Try again.";
        exit();
    }
    // Include the file that houses all of our custom image functions
    include_once("ak_php_img_lib_1.0.php");
    // ---------- Start Universal Image Resizing Function --------
    $target_file = "images/".$id."_".$time.".".$fileExt;
    $resized_file = "images/resized_".$id."_".$time."." . $fileExt;
    $wmax = 320;
    $hmax = 240;
    ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
    unlink($target_file);
    // ----------- End Universal Image Resizing Function ----------
    // ---------- Start Convert to JPG Function --------
    if (strtolower($fileExt) != "jpg") {
        $target_file = "images/resized_".$id."_".$time."." . $fileExt;
        $new_jpg = "images/resized_".$id."_".$time.".jpg";
        ak_img_convert_to_jpg($target_file, $new_jpg, $fileExt);
    unlink($target_file);
    }
    
        $new_jpg = "images/resized_".$id."_".$time.".jpg";
    
    if(!get_magic_quotes_gpc())
    {
        $new_jpg = addslashes($new_jpg);
        $filePath = addslashes($filePath);
    }
    $resultc = mysql_query("SELECT * FROM Users2 WHERE mxitid = '$ip'");
    
            $rowc = mysql_fetch_array($resultc);
             $ppica = $rowc['pprofilepic'];
    $naam = "ADMIN";
    $naam2 = $rowc['pprofilepic'];
    
    $msg = "You Requested a Profile Picture change, please wait till an Admin can manage the request";
    $msg1 = "Please aprove my Profile Picture";
    
    $post_time = date("U");
    $read1 = "unread";
    $banby2 = "ADMIN";
    $result = mysql_query("UPDATE Users2 SET pprofilepic='$new_jpg', aprove='requested' WHERE mxitid='$ip'") 
    or die(mysql_error());  
    unlink($ppica);
    
    
    
    $query1 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam\",\"$ip\",\"$msg\",\"$post_time\",\"$read1\",\"$banby2\")";
    
        $result1 = mysql_query($query1, $db) or die("Invalid query: " . mysql_error());
    
    $query2 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam2\",\"$banby2\",\"$msg1\",\"$post_time\",\"$read1\",\"$ip\")";
    
        $result2 = mysql_query($query2, $db) or die("Invalid query: " . mysql_error());
    
    
    
    
    // ----------- End Convert to JPG Function -----------
    // Display things to the page so you can see what is happening for testing purposes
    echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />";
    echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />";
    echo "It is an <strong>$fileType</strong> type of file.<br /><br />";
    echo "The file extension is <strong>$fileExt</strong><br /><br />";
    echo "The Error Message output for this upload is: $fileErrorMsg";
    
    
    if($result){
    header('Location: ../profile/thankyou.php');
    }
    else {
    echo "ERROR";
    }
    
    // close mysql
    mysql_close();
    
    
    
    
    ?>
    
    

    ak_php_img_lib_1.0.php

    <?php
    // ----------------------- RESIZE FUNCTION -----------------------
    // Function for resizing any jpg, gif, or png image files
    function ak_img_resize($target, $newcopy, $w, $h, $ext) {
        list($w_orig, $h_orig) = getimagesize($target);
        $scale_ratio = $w_orig / $h_orig;
        if (($w / $h) > $scale_ratio) {
               $w = $h * $scale_ratio;
        } else {
               $h = $w / $scale_ratio;
        }
        $img = "";
        $ext = strtolower($ext);
        if ($ext == "gif"){ 
        $img = imagecreatefromgif($target);
        } else if($ext =="png"){ 
        $img = imagecreatefrompng($target);
        } else { 
        $img = imagecreatefromjpeg($target);
        }
        $tci = imagecreatetruecolor($w, $h);
        // imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h)
        imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);
        if ($ext == "gif"){ 
            imagegif($tci, $newcopy);
        } else if($ext =="png"){ 
            imagepng($tci, $newcopy);
        } else { 
            imagejpeg($tci, $newcopy, 84);
        }
    }
    // ---------------- THUMBNAIL (CROP) FUNCTION ------------------
    // Function for creating a true thumbnail cropping from any jpg, gif, or png image files
    function ak_img_thumb($target, $newcopy, $w, $h, $ext) {
        list($w_orig, $h_orig) = getimagesize($target);
        $src_x = ($w_orig / 2) - ($w / 2);
        $src_y = ($h_orig / 2) - ($h / 2);
        $ext = strtolower($ext);
        $img = "";
        if ($ext == "gif"){ 
        $img = imagecreatefromgif($target);
        } else if($ext =="png"){ 
        $img = imagecreatefrompng($target);
        } else { 
        $img = imagecreatefromjpeg($target);
        }
        $tci = imagecreatetruecolor($w, $h);
        imagecopyresampled($tci, $img, 0, 0, $src_x, $src_y, $w, $h, $w, $h);
        if ($ext == "gif"){ 
            imagegif($tci, $newcopy);
        } else if($ext =="png"){ 
            imagepng($tci, $newcopy);
        } else { 
            imagejpeg($tci, $newcopy, 84);
        }
    }
    // ------------------ IMAGE CONVERT FUNCTION -------------------
    // Function for converting GIFs and PNGs to JPG upon upload
    function ak_img_convert_to_jpg($target, $newcopy, $ext) {
        list($w_orig, $h_orig) = getimagesize($target);
        $ext = strtolower($ext);
        $img = "";
        if ($ext == "gif"){ 
            $img = imagecreatefromgif($target);
        } else if($ext =="png"){ 
            $img = imagecreatefrompng($target);
        }
        $tci = imagecreatetruecolor($w_orig, $h_orig);
        imagecopyresampled($tci, $img, 0, 0, 0, 0, $w_orig, $h_orig, $w_orig, $h_orig);
        imagejpeg($tci, $newcopy, 84);
    }
    ?>
    
  17. You really should be working with MIME type, instead of doing it how you are. You can use finfo to do that.

     

    Something like this. Untested, but should work

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    
    $mimetype = $finfo->file($fileTmpLoc);
    
    $allowedMimeTypes = array(
    	'image/jpeg',
    	'image/png',
    	'image/gif',
    );
    
    if (in_array($mimetype, $allowedMimeTypes)) {
    	// file is good
    } else {
    	// invalid mime type
    }

    The allowed MimTypes doesn't seem to be my problem the problem seems to be the renaming of my files and adding it to the database with another name....

  18. Because your $imageTypeArray contains JPEG but you're later looking for jpg with: } else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) {

    The thing is people rename png files to jpg then I need to check what its real format type is. The photos get uploaded but its not saved as jpg it get saved as JPEG not jpg with a millisecond difference in the filename so if the file is named ....321.JPEG in my images directory but in my MySQL field its stored as .... 322.jpg then I cant recall the right picture...

  19.  

    Why don't you use DateTime object like I showed you in your other post?

    http://forums.phpfreaks.com/topic/298299-string-to-array-and-date/?do=findComment&comment=1521469

     

    It saves you a shedload of code

    $targetDate = new DateTime('2015-12-25 12:00:00');
    
    $remaining = $targetDate->diff(new DateTime());
    
    echo $remaining->format('%a D - %H:%I:%S');   //--> 86 D - 19:44:24
    

    Thank you Barand I tried your code and its Displaying the time in the correct format, but When the counter reaches 0 it starts to count up again and doesn't do my action in the if function

    <html>
    <?
    define('TIMEZONE', 'Africa/Harare');
    date_default_timezone_set(TIMEZONE);
    
    
    $targetDate = new DateTime('2015-09-29 20:00:00');
    
    $remaining = $targetDate->diff(new DateTime());
    
    // not done
    if( $remaining > 0 )
    { 
    echo '<span style="color:red"><b>
    We need to add some changes and need to disable chat to do so. Hopefully we will be back within an hour or so. Chat will go offline in: </b></span>'; 
    echo $remaining->format('%a D - %H:%I:%S');   //--> 86 D - 19:44:24
    }
    
    // done
    else
    { 
    header("Location: offline.php");
    			exit();
    
    
     }
    ?>
    </html>
    
  20. Hi I'm currently stuck with an image upload script that doesn't seem to rename my files correctly and if its a jpg file the conversion doesn't take place correctly as well any assistance please?

    All I'm trying to do is to change a random photo to jpg format and resize it to be less than 100kb

    <?php
        include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php';
    $ip = $_SERVER["HTTP_X_MXIT_USERID_R"];
    if(!isset($ip))
    {
    	$ip = "Debater";
    }
    
    
    
    $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\"");
            $row = mysql_fetch_array($result9);
    $id = $row['ID'];
    
    // Access the $_FILES global variable for this specific file being uploaded
    // and create local PHP variables from the $_FILES array of information
    $fileName = $_FILES["uploaded_file"]["name"]; // The file name
    $fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder
    $fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is
    $fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes
    $fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true
    $fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); // filter the $filename
    
    
    $kaboom = explode(".", $fileName); // Split file name into an array using the dot
    
    
    
    
     $imageTypeArray = array
        (
            0=>'UNKNOWN',
            1=>'GIF',
            2=>'JPEG',
            3=>'PNG',
            4=>'SWF',
            5=>'PSD',
            6=>'BMP',
            7=>'TIFF_II',
            8=>'TIFF_MM',
            9=>'JPC',
            10=>'JP2',
            11=>'JPX',
            12=>'JB2',
            13=>'SWC',
            14=>'IFF',
            15=>'WBMP',
            16=>'XBM',
            17=>'ICO',
            18=>'COUNT'  
        );
        
        $size = getimagesize($fileTmpLoc);
        
        $size[2] = $imageTypeArray[$size[2]];
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    $fileExt = $size[2]; // Now target the last array element to get the file extension
    
    
    // START PHP Image Upload Error Handling --------------------------------
    if (!$fileTmpLoc) { // if file not chosen
        echo "ERROR: Please browse for a file before clicking the upload button.";
        exit();
    } else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes
        echo "ERROR: Your file was larger than 5 Megabytes in size.";
        unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
        exit();
    } else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) {
         // This condition is only if you wish to allow uploading of specific file types    
         echo "ERROR: Your image was not .gif, .jpg, or .png.";
         unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
         exit();
    } else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
        echo "ERROR: An error occured while processing the file. Try again.";
        exit();
    }
    // END PHP Image Upload Error Handling ----------------------------------
    // Place it into your "uploads" folder mow using the move_uploaded_file() function
    $moveResult = move_uploaded_file($fileTmpLoc, "images/".$id."_".date_create()->getTimestamp().".".$fileExt);
    // Check to make sure the move result is true before continuing
    if ($moveResult != true) {
        echo "ERROR: File not uploaded. Try again.";
        exit();
    }
    // Include the file that houses all of our custom image functions
    include_once("ak_php_img_lib_1.0.php");
    // ---------- Start Universal Image Resizing Function --------
    $target_file = "images/".$id."_".date_create()->getTimestamp().".".$fileExt;
    $resized_file = "images/resized_".$id."_".date_create()->getTimestamp()."." . $fileExt;
    $wmax = 320;
    $hmax = 240;
    ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
    unlink($target_file);
    // ----------- End Universal Image Resizing Function ----------
    // ---------- Start Convert to JPG Function --------
        $target_file = "images/resized_".$id."_".date_create()->getTimestamp()."." . $fileExt;
        $new_jpg = "images/resized_".$id."_".date_create()->getTimestamp().".jpg";
        ak_img_convert_to_jpg($target_file, $new_jpg, $fileExt);
    unlink($target_file);
    
    
        $new_jpg = "images/resized_".$id."_".date_create()->getTimestamp().".jpg";
    
    if(!get_magic_quotes_gpc())
    {
        $new_jpg = addslashes($new_jpg);
        $filePath = addslashes($filePath);
    }
    $resultc = mysql_query("SELECT * FROM Users2 WHERE mxitid = '$ip'");
    
            $rowc = mysql_fetch_array($resultc);
             $ppica = $rowc['pprofilepic'];
    $naam = "ADMIN";
    $naam2 = $rowc['pprofilepic'];
    
    $msg = "You Requested a Profile Picture change, please wait till an Admin can manage the request";
    $msg1 = "Please aprove my Profile Picture";
    
    $post_time = date("U");
    $read1 = "unread";
    $banby2 = "ADMIN";
    $result = mysql_query("UPDATE Users2 SET pprofilepic='$new_jpg', aprove='requested' WHERE mxitid='$ip'") 
    or die(mysql_error());  
    unlink($ppica);
    
    
    
    $query1 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam\",\"$ip\",\"$msg\",\"$post_time\",\"$read1\",\"$banby2\")";
    
        $result1 = mysql_query($query1, $db) or die("Invalid query: " . mysql_error());
    
    $query2 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam2\",\"$banby2\",\"$msg1\",\"$post_time\",\"$read1\",\"$ip\")";
    
        $result2 = mysql_query($query2, $db) or die("Invalid query: " . mysql_error());
    
    
    
    
    // ----------- End Convert to JPG Function -----------
    // Display things to the page so you can see what is happening for testing purposes
    echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />";
    echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />";
    echo "It is an <strong>$fileType</strong> type of file.<br /><br />";
    echo "The file extension is <strong>$fileExt</strong><br /><br />";
    echo "The Error Message output for this upload is: $fileErrorMsg";
    
    
    if($result){
    header('Location: ../profile/thankyou.php');
    }
    else {
    echo "ERROR";
    }
    
    // close mysql
    mysql_close();
    
    
    
    
    ?>
    
    
  21.  

    php is server-side.  meaning it will not update the time display on your page unless you refresh the page.  if you want a dynamic timer that ticks down in your browser, you will need to use a client-side solution like javascript.  i suck at js so not sure about this but you might be able to trigger your php script via AJAX and have the page update on time intervals rather than user refresh.

    <?php
    // Define your target date here
        $targetYear = 2007;
        $targetMonth = 9;
        $targetDay = 10;
        $targetHour = 12;
        $targetMinute= 00;
        $targetSecond= 00;
    // End target date definition
    
    // Define date format
    $dateFormat = "Y-m-d H:i:s";
    
    $targetDate = mktime($targetHour,$targetMinute,$targetSecond,$targetMonth,$targetDay,$targetYear);
    $actualDate = time();
    
    $secondsDiff = $targetDate - $actualDate;
    
    $remainingDay = floor($secondsDiff/60/60/24);
    $remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
    $remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
    $remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
    
    $targetDateDisplay = date($dateFormat,$targetDate);
    $actualDateDisplay = date($dateFormat,$actualDate);
    
    // not done
    if( $secondsDiff > 0 )
    { echo "$remainingDay days, $remainingHour hours, $remainingMinutes minutes, $remainingSeconds seconds"; }
    
    // done
    else
    {  }
    ?>

    The User refresh is fine but how to output it as example 01 D - 23:01:10 format since the above code only provide 1 days 23 hours 10minutes 15 seconds etc...

  22. Hi I'm trying to create a countdown timer strictly php only and do an action once the time runs out I found an example of a countdown timer but I'm uncertain on how to use it to show in the format  D H:m:s ( 01 Days 23:01:20) and how to chaeck if the time is done and do the action and afterwards remove the countdown timer from showing on the page

    <?php
    // Define your target date here
    	$targetYear  = 2007;
    	$targetMonth = 9;
    	$targetDay   = 10;
    	$targetHour  = 12;
    	$targetMinute= 00;
    	$targetSecond= 00;
    // End target date definition
    
    // Define date format
    $dateFormat = "Y-m-d H:i:s";
    
    $targetDate = mktime($targetHour,$targetMinute,$targetSecond,$targetMonth,$targetDay,$targetYear);
    $actualDate = time();
    
    $secondsDiff = $targetDate - $actualDate;
    
    $remainingDay     = floor($secondsDiff/60/60/24);
    $remainingHour    = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
    $remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
    $remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
    
    $targetDateDisplay = date($dateFormat,$targetDate);
    $actualDateDisplay = date($dateFormat,$actualDate);
    
    
    echo "$remainingDay days, $remainingHour hours, $remainingMinutes minutes, $remainingSeconds seconds";
    ?>
    
    
  23.  

    Perhaps this?

    if (!function_exists('is_json')) {
        function is_json($json) {
            $json = json_decode($json);
            if (is_array($json)) {
                return True;
            }
            return False;
        }
    }

    This ended up giving me the error 

     

     

    Fatal error: Uncaught exception 'Exception' with message 'Invalid scope specified for send_message() method, should be: message/user' in /home/a5664480/public_html/chat2/MxitAPI.php:173 Stack trace: #0 /home/a5664480/public_html/chat2/MxitAPI.php(511): MxitAPI->_check_scope('send_message', 'message/user') #1 /home/a5664480/public_html/chat2/page.php(1148): MxitAPI->send_message('spamchat', 'm70141099002,m5...', '#8A2BE2 *The Bo...', 'true') #2 {main} thrown in /home/a5664480/public_html/chat2/MxitAPI.php on line 173

     
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.