Trying to determine file types - php

I would be glad if you help me with this PHP code .
I made an upload form which only supports .pdf , .docx and .rtf files .
the file gets uploaded but it can't determine if the file type is pdf , docx or rtl or just non of them . Any solutions to fix this?
well I did a few searches in stackoverflow , some of the members did same as i do but mine still doesn't work.
This code gets a file from an input . It uploads the file to server , on a specific folder , and then it saves the file's name on database.
<?php
function query($q)
{
$dbconnection = mysql_connect('127.0.0.1' , 'root' , '');
$database = mysql_select_db('hire_requests');
mysql_set_charset("utf8",$dbconnection);
$res = mysql_query($q,$dbconnection);
mysql_close($dbconnection);
return $res;
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$error = '';
$alarm = false;
$success = false;
$changedname = '';
$name = '';
$lastname = '';
$phonenumber;
$nnumber;
$type ='';
$mail = '';
$resume;
$type = '';
$notify = '';
$nameErr= "";
$mailErr = "";
$resumeErr = "";
$nnumberErr = "";
$lastnameErr = "";
$phonenumberErr = "";
$notsentErr = "";
$sizeErr = "";
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$name = mysql_real_escape_string($_POST['name']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$phonenumber = mysql_real_escape_string($_POST['phonenumber']);
$nnumber = mysql_real_escape_string($_POST['nnumber']);
$mail = mysql_real_escape_string($_POST['mail']);
if(isset($_FILES['resume']))
{
$filename = $_FILES['resume']['name'];
$filesize = $_FILES['resume']['size'];
$filetype = $_FILES['resume']['type'];
$filetmp = $_FILES['resume']['tmp_name'];
if($_FILES['resume']['error'] !== 0)
{
$alarm = true;
}
$AllowedTypesArray = array('docx' , 'rtf' , 'pdf');
$changedname = 'Rayka_' . rand(1000,9000) . '_' . '5SV4DFS_A245DFA' . '_' . time() . '_' . $name;
$info = pathinfo($filename , PATHINFO_EXTENSION);
if($alarm = true)
{
}
if($filetype == 'application/pdf' )
{
$type = '.pdf';
}
if($filetype == 'application/msword' )
{
$type = '.docx';
}
if($filetype == 'application/rtf')
{
$type = '.rtf';
}
if(!$type)
{
$resumeErr = "file's type is not supported";
}
if(!in_array($info , $AllowedTypesArray)) //checks if filetype is pdf , rtl or docx and also , checks if the file is less than 2 mbs or not .
{
$error = "file's type is not supported";
$alarm = true;
}
if($filesize > 2097152)
{
$sizeErr ="Your file must be less than 2 Mbs";
}
$path = dirname(__FILE__).'/_ufile/'.$changedname . $type;
var_dump($path);
if(!move_uploaded_file($_FILES['resume']['tmp_name'] , $path) )
{
$alarm = true;
$notsentErr = 'File was not sent';
}
}
if(!isset($_FILES['resume']))
{
$resumeErr = 'attachment is not chosen';
$alarm = true;
}
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (empty($_POST["name"]))
{
$nameErr = "Enter your name";
}
else
{
$name = test_input($_POST["name"]);
}
}
if(empty($_POST['lastname']))
{
$lastnameErr = "Enter your last name";
}
else {
$lastname = test_input($_POST['lastname']);
}
if(empty($_POST['phonenumber']))
{
$phonenumberErr = "Enter your phone number";
}
else
{
$phonenumber = test_input($_POST['phonenumber']);
}
if(empty($_POST['nnumber']))
{
$nnumberErr = "Enter your second phone number";
}
else
{
$nnumber = test_input($_POST['nnumber']);
}
if(empty($_POST['mail']))
{
$mailErr = "enter your email address";
}
else
{
$mail = test_input($_POST['mail']);
}
if((!$nameErr) && (!$lastnameErr) && (!$mailErr) && (!$phonenumberErr) && (!$nnumberErr) && (!$notsentErr) && (!$sizeErr))
{
$query = "INSERT INTO users (`id`,`name`, `lastname`, `phonenumber`, `nnumber`, `mail`, `resume`) VALUES (NULL , \"$name\",\"$lastname\",\"$phonenumber\",\"$nnumber\",\"$mail\",\"$changedname\")";
$notify = "Successful";
$success = true;
$insert = query($query);
$error2 = mysql_error();
}
}
?>

Here what i use (i changed for you needs) :
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['resume']['tmp_name']);
$ok = false;
switch ($mime) {
case 'application/pdf':
case 'application/msword':
case 'text/pdf':
case 'application/rtf':
case 'application/x-rtf':
case 'text/richtext':
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
$ok = true;
break;
default:
die();
}
Here the complete mime type list : https://www.sitepoint.com/web-foundations/mime-types-complete-list/

Related

Profile url unable to get result

So I am wanting to allow my members to view a profile via a url such as: mywebsite.com/account/Username
however, at the moment my members can view via the url: mywebsite.com/account?username=username.
This doesn't look profesional and I've tried nearly everything to get it to the url I'm looking to get.
(Please be aware; I'm very new to this website and cannot use it properly, If I have done anything wrong, please notify me and I will justify it.)
The code:
//get config
$config = $base->loadConfig();
full code:
https://pastebin.com/UmAmF9Rt
<?php
require('../includes/config.php');
require('../structure/base.php');
require('../structure/forum.php');
require('../structure/forum.index.php');
require('../structure/forum.thread.php');
require('../structure/forum.post.php');
require('../structure/database.php');
require('../structure/user.php');
$database = new database($db_host, $db_name, $db_user, $db_password);
$base = new base($database);
$user = new user($database);
$forum = new forum($database);
$forum_index = new forum_index($database);
$thread = new thread($database);
$post = new post($database);
$user->updateLastActive();
//get config
$config = $base->loadConfig();
//set some variables that are used a lot throughout the page
if (!empty($_GET['username'])) {
$profile_name = htmlspecialchars($_GET["username"]);
}
else{
$profile_name = $user->getUsername($_COOKIE['user'], 2);
}
$username = $user->getUsername($_COOKIE['user'], 2);
$rank = $user->getRank($username);
$f = $_GET['forum'];
$i = $_GET['id'];
//assign data to details[] array
$details['lock'] = $detail_query[0]['lock'];
$details['sticky'] = $detail_query[0]['sticky'];
$details['title'] = stripslashes(htmlentities($detail_query[0]['title']));
$details['username'] = $detail_query[0]['username'];
$details['status'] = $detail_query[0]['status'];
$details['content'] = $detail_query[0]['content'];
$details['date'] = $detail_query[0]['date'];
$details['lastedit'] = $detail_query[0]['lastedit'];
$details['qfc'] = $detail_query[0]['qfc'];
$details['moved'] = $detail_query[0]['moved'];
$details['hidden'] = $detail_query[0]['hidden'];
$details['autohiding'] = $detail_query[0]['autohiding'];
//get forum details
$forum_details = $database->processQuery("SELECT `title` FROM `forums` WHERE `id` = ?", array($f), true);
if(isset($_GET['username'])){
if($user->doesExist($_GET['username'])){;
}
}else{
if(!$user->isLoggedIn()){
$base->redirect('../login.php');
}else{
$user_s = $username;
}
}
$messages = array();
$avatar = $user->getAvatar($profile_user);
$usr = $user->getUsername($profile_user);
if($username == $profile_user && $user->isLoggedIn() && isset($_REQUEST['cust_title'])) {
$user->setTitle($username, htmlentities($_REQUEST['cust_title']));
}
if($user_s == $username && $user->isLoggedIn() && isset($_FILES['uploaded'])) {
if(isset($_REQUEST['delete'])) {
$user->setAvatar($username, '');
$messages[] = "Your avatar has been removed.";
} else {
$ok = false;
$info = getimagesize($_FILES['uploaded']['tmp_name']);
if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
$messages[] = ("Upload failed with error code " . $_FILES['uploaded']['error']);
} else if($info === FALSE) {
$messages[] = ("Unable to determine image type of uploaded file");
} else if(($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {
$messages[] = ("Not a gif/jpeg/png");
} else if($_FILES['uploaded']['size'] > 350000) {
$messages[] = "Your file is too large.";
} else if($_FILES['uploaded']['type'] == "text/php") {
$messages[] = "No PHP files";
} else {
$ok = true;
}
$target = md5(strtolower(trim($username))) .'.'. pathinfo($_FILES['uploaded']['name'])['extension'];
if($ok) {
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], "../images/avatar/" . $target)){
$messages[] = "Your avatar has been uploaded. Please allow atleast 10 minutes for it to update.";
$user->setAvatar($username, $target);
} else {
$messages[] = "Sorry, there was a problem uploading your file.";
}
}
}
}
//retrieve posts/threads
$posts = $database->processQuery("SELECT `id`,`thread`,`username`,`timestamp`,`content` FROM `posts` WHERE `username` = ? AND ". time() ." - `timestamp` < 1209600 ORDER BY `id` DESC", array($user_s), true);
$threads = $database->processQuery("SELECT `id`,`parent`,`title`,`username`,`timestamp`,`content` FROM `threads` WHERE `username` = ? AND ". time() ." - `timestamp` < 1209600 ORDER BY `id` DESC", array($user_s), true);
//type:id:forum:timestamp:(if post)thread
$list = array();
foreach($posts as $post){
//get the thread's forum/parent
$t = $database->processQuery("SELECT `parent` FROM `threads` WHERE `id` = ? LIMIT 1", array($post['thread']), true);
$list[$post['timestamp']] = 'p:'.$post['id'].':'. $t[0]['parent'] .':'.$post['timestamp'].':'.$post['thread'].':'.$post['content'];
}
//add threads
foreach($threads as $thread){
$list[$thread['timestamp']] = 't:'.$thread['id'].':'.$thread['parent'].':'.$thread['timestamp'].':'.$thread['content'];
}
//now sort them
krsort($list, SORT_NUMERIC);
$r = $database->processQuery("SELECT * FROM `users` WHERE `username` = ?", array($profile_name), true);
?>
Your best bet is to use:
.htaccess route with mod_rewrite
Try Adding a file called .htaccess in your root folder, and add something like this:
RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /account.php?username=$username
This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want:
Refer to this answer by Niels Keurentjes: https://stackoverflow.com/a/16389034/3367509
If you are new to .htaccess look up this question: What is .htaccess file?

I am getting error 500

I am working on a site where people can get a bitcoin adres. When I do the GET request to the file, it gives a response of HTTP error 500. But I can't find any wrong things. Her is my script:
<?php
ob_start();
session_start();
error_reporting(0);
include("../includes/config.php");
$db = new mysqli($CONF['host'], $CONF['user'], $CONF['pass'], $CONF['name']);
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
$db->set_charset("utf8");
$settingsQuery = $db->query("SELECT * FROM btc_settings ORDER BY id DESC LIMIT 1");
$settings = $settingsQuery->fetch_assoc();
include("../includes/block_io.php");
include("../includes/functions.php");
//include(getLanguage($settings['url'],null,2));
if(checkSession()) {
$type = protect($_GET['type']);
if($type == "receive") {
} elseif($type == "new_address") {
$nums = $db->query("SELECT * FROM btc_users_addresses WHERE uid='".$_SESSION['btc_uid']."'");
if($nums->num_rows > $settings['max_addresses_per_account']) {
$data['status'] = 'error';
$data['msg'] = error("You've reached the limit of wallet addresses. Max: $settings[max_addresses_per_account]");
} else {
$label = protect($_POST['label']);
if(!empty($label) && !isValidUsername($label)) { $data['status'] = 'error'; $data['msg'] = error("Please enter valid label. Use only characters and symbols - and _."); }
else {
if(empty($label)) { $label = randomHash(7); }
$username = idinfo($_SESSION['btc_uid'],"username");
$generate_address = btc_generate_address($username,$label);
if($generate_address) {
$data['status'] = 'success';
$data['msg'] = success("Your new address is <b>" . $generate_address . "</b>.");
} else {
$data['status'] = 'error';
$data['msg'] = error("Error with creating address. Please try again.");
}
}
}
echo json_encode($data);
} elseif($type == "send_bitcoins") {
$address = protect($_GET['from_address']);
$to_address = protect($_POST['to_address']);
$amount = protect($_POST['amount']);
$secret_pin = protect($_POST['secret_pin']);
$secret_pin = md5($secret_pin);
$check = $db->query("SELECT * FROM btc_users_addresses WHERE uid='".$_SESSION[btc_uid]."' and address='$address'");
if($check->num_rows==0) {
$data['status'] = 'error';
$data['msg'] = error("This wallet address is not yours!");
} elseif(empty($address) or empty($to_address) or empty($amount)) {
$data['status'] = 'error';
$data['msg'] = error("All fields are required.");
} elseif(!is_numeric($amount)) {
$data['status'] = 'error';
$data['msg'] = error("Please enter Bitcoin amount with numbers. Format: 0.000000");
} elseif(idinfo($_SESSION['btc_uid'],"secret_pin") && idinfo($_SESSION['btc_uid'],"secret_pin") !== $secret_pin) {
$data['status'] = 'error';
$data['msg'] = error("Wrong Secret PIN!");
} else {
$row = $check->fetch_assoc();
$total = $row['available_balance'];
$total = $total - 0.0008;
$total = $total - $settings['withdrawal_comission'];
if($total < 0) { $total = '0.0000'; }
if($amount > $total) {
$data['status'] = 'error';
$data['msg'] = error("Total available minus fees <b>" . $total . "</b> BTC.");
} else {
$newamount = $row['available_balance']-$amount;
$newamount = $newamount - 0.0008 - $settings['withdrawal_comission'];
$license_query = $db->query("SELECT * FROM btc_blockio_licenses WHERE id='".$row[lid]."' ORDER BY id");
$license = $license_query->fetch_assoc();
$apiKey = $license['license'];
$pin = $license['secret_pin'];
$version = 2; // the API version
$block_io = new BlockIo($apiKey, $pin, $version);
$withdrawal = $block_io->withdraw_from_addresses(array('amounts' => $amount, 'from_addresses' => $address, 'to_addresses' => $to_address));
$withdrawal = $block_io->withdraw_from_addresses(array('amounts' => $settings[withdrawal_comission], 'from_addresses' => $address, 'to_addresses' => $license[address]));
$data['status'] = 'success';
$data['msg'] = success("You sent <b>" . $amount . "</b> BTC to <b>" . $to_address . "</b> successfully.");
$data['btc_total'] = $newamount;
}
}
echo json_encode($data);
} elseif($type == "receive_to_address") {
} elseif($type == "archive_address") {
$address_id = protect($_GET['address_id']);
$query = $db->query("SELECT * FROM btc_users_addresses WHERE uid='".$_SESSION[btc_uid]."' and id='".$address_id."'");
if($query->num_rows>0) {
$row = $query->fetch_assoc();
if($row['archived'] == "1") {
echo 'Your wallet address <b>'.$row[address].'</b> is already archived.';
} else {
$update = $db->query("UPDATE btc_users_addresses SET archived='1' WHERE id='".$row[id]."'");
echo 'Your wallet address <b>'.$row[address].'</b> was archived.';
}
} else {
echo 'This wallet address is not yours!';
}
} elseif($type == "unarchive_address") {
$address_id = protect($_GET['address_id']);
$query = $db->query("SELECT * FROM btc_users_addresses WHERE uid='".$_SESSION[btc_uid]."' and id='".$address_id."'");
if($query->num_rows>0) {
$row = $query->fetch_assoc();
if($row['archived'] == "0") {
echo 'Your wallet address <b>'.$row[address].'</b> is already unarchived.';
} else {
$update = $db->query("UPDATE btc_users_addresses SET archived='0' WHERE id='".$row[id]."'");
echo 'Your wallet address <b>'.$row[address].'</b> was unarchived.';
}
} else {
echo 'This wallet address is not yours!';
}
} else { }
}
?>
Thank you for helping me out! It must to give the address back...

Lead Save Database Error In SuiteCRM

I've created a Logic Hook within the Leads module to save to a field in the database. The problem is that when I save the Lead first it displays a duplicate message:
Database failure error check SuiteCRM logs.
If I comment out this code the Lead is then saved.
LogicHook:
<?php
class LeadData
{
public function leadSaveData(&$bean, $events, $arguments)
{
$stateId = $bean->state_c;
if ($stateId != "") {
$beanst_state = BeanFactory::getBean('s1_state', $stateId);
$StateName = $beanst_state->name;
$bean->resstate_c = $StateName;
} else {
$bean->resstate_c = "Punjab";
}
if (!empty($bean->mediatype_c)) {
$mediaType = $bean->mediatype_c;
$callstatus = $bean->callstatus_c; //for follow up
if ($mediaType == 'Selectmedia' && $mediaType != '') {
$bean->refrence_c = 'null';
} else if ($mediaType == 'Refrence') {
$bean->eventname_c = 'null';
} else {
$bean->mediatype_c = 'null';
$bean->refrence_c = 'null';
$bean->eventname_c = 'null';
}
if ($callstatus != 'followup') {
$bean->calllater_c = '0000-00-00 00:00:00';
}
$bean->save();
}
}
}
Please follow these steps in your code to make this error correct or working. Hope so it will helps you.
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if (!defined('sugarEntry') || !sugarEntry)
die('Not A Valid Entry Point');
class saveextradata_logic_hooks_class
{
static $already_ran = false;
function saveextradata_after_save_method(&$bean, $events, $arguments)
{
global $db;
if (self::$already_ran == true) return;
self::$already_ran = true;
$lead_id = $bean->id;
$stateId = $_POST['state_c'];
$sql = "select name from s1_state where id='$stateId'";
$query = $db->query($sql);
$result = $db->fetchByAssoc($query);
$statename = $result[name];
if ($stateId != "") {
$statename;
} else {
$statename = "Punjab";
}
if (!empty($_POST['mediatype_c'])) {
$mediaType = $_POST['mediatype_c'];
if ($mediaType == 'Selectmedia' && $mediaType != '') {
$mediatype = 'Selectmedia';
$reference = 'null';
$eventname = $_POST['eventname_c'];
} else if ($mediaType == 'Refrence') {
$mediatype = 'Refrence';
$reference = $_POST['refrence_c'];
$eventname = 'null';
} else {
$mediatype = 'null';
$reference = 'null';
$eventname = 'null';
}
}
$callstatus = $_POST['callstatus_c'];//for follow up
if ($callstatus != 'followup') {
$calllater = '0000-00-00 00:00:00';
}
/*$bean->eventname_c = $eventname;
$bean->refrence_c = $reference;
$bean->mediatype_c = $mediatype_c;
$bean->calllater_c = $calllater;
$bean->resstate_c = $statename;
$bean->save();*/
$leadupdate = "update leads_cstm set resstate_c='$statename',eventname_c='$eventname',refrence_c='$reference',mediatype_c='$mediatype',calllater_c='$calllater' WHERE id_c = '$lead_id'";
$resultProductmasterdetail = $db->query($leadupdate);
}
}

How to upload file in PHP if not exist

I readed all about this in PHP.net but i can't find the solution. I know how to upload files into a new row in Mysql and PHP, but I don't know how to UPDATE a row and not delete the previous uploaded file if I don't upload anything.
For example, I have this form:
LOGO
Name of Business
Image 1
For example: I have this in MYSQL:
LOGO: /img/logo1.png
NAME: business1
IMAGE 1: ""
I want to do if I don't upload anything in LOGO and I'm editing this business (leaving in blank the input file of LOGO), do not upload my logo and SET a blank one ("").
This is the code of PHP:
define("MAX_SIZE", "2000");
function getExtension($str) {
$i = strrpos($str, ".");
if (!$i) {
return "";
}
$l = strlen($str) - $i;
$ext = substr($str, $i + 1, $l);
return $ext;
}
$errors = 0;
$image = $_FILES['foto0']['name'];
$image1 = $_FILES['foto1']['name'];
if ($image) {
$filename = stripslashes($_FILES['foto0']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
$errors = 1;
$falloExtension = true;
} else {
$size = filesize($_FILES['foto0']['tmp_name']);
if ($size > MAX_SIZE * 2024) {
$errors = 1;
$falloLimite = true;
}
$image_name = uniqid() . '.' . $extension;
$newname = "img/detalles/" . $image_name;
$newname2 = "img/detalles/" . $image_name;
$copied = copy($_FILES['foto0']['tmp_name'], $newname2);
if($copied) {
$copiar = "UPDATE negocios SET logo='$newname' WHERE id=$numNegocio";
$resultado = $mysqli->query($copiar);
//header("location: ../anunciate.php");
} else {
//header("location: ../anunciate.php?fallo=true");
}
}
}
if ($image1) {
$filename = stripslashes($_FILES['foto1']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
$errors = 1;
$falloExtension = true;
} else {
$size = filesize($_FILES['foto1']['tmp_name']);
if ($size > MAX_SIZE * 2024) {
$errors = 1;
$falloLimite = true;
}
$image_name = uniqid() . '.' . $extension;
$newname = "img/detalles/" . $image_name;
$newname2 = "img/detalles/" . $image_name;
$copied = copy($_FILES['foto1']['tmp_name'], $newname2);
if($copied) {
$copiar = "UPDATE galerias SET imagen1='$newname' WHERE negocios_id=$numNegocio";
$resultado = $mysqli->query($copiar);
//header("location: ../anunciate.php");
} else {
//header("location: ../anunciate.php?fallo=true");
}
}
}
if(isset($_POST['modificanegocio'])) {
$nombrePOST = $_POST['nombre'];
$categoriaPOST = $_POST['categoria'];
$direccionPOST = $_POST['direccion'];
$telefonoPOST = $_POST['telefono'];
$correoPOST = $_POST['correo'];
$descripcionPOST = $_POST['descripcion'];
$horarioPOST = $_POST['horario'];
$paginawebPOST = $_POST['paginaweb'];
$keywordsPOST = $_POST['keywords'];
$latPOST = $_POST['lat'];
$longPOST = $_POST['long'];
$facebookPOST = $_POST['facebook'];
$googlePOST = $_POST['google'];
$twitterPOST = $_POST['twitter'];
$insagramPOST = $_POST['insagram'];
$logoPOST = $_POST['logo'];
if($modificaNegocio = $mysqli->query("UPDATE negocios SET name = '$nombrePOST, logo = '$logoPOST', image1 = $image1POST WHERE id = $id")) {
$modifica = true;
} else {
$modifica = false;
}
}
I solved this spliting the MYSQL code:
$query = "UPDATE negocios SET nombre = '$nombrePOST'";
if($image != "" || $image != null) {
//NOW I WILL UPLOAD THE IMAGE HERE AND UPLOAD THE QUERY
}
$query .= " WHERE id = $id";
if($modificaNegocio = $mysqli->query($query)) {
$modifica = true;
} else {
$modifica = false;
}
}

Update a record by taking an id from the url

Hello everyone i'm taking a value from a URL by get and pass it into an update statement, when i put WHERE ID= 1 , it work fine but when i put the ID=$id, the code work but there is no update, the record remain the same, can some help me to resolve this problem please
<?php
require 'db2.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
$dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
$q = mysqli_query($dbc,"SELECT * FROM movie WHERE MovieID = '$id' ");
while($r=mysqli_fetch_array($q))
{
$title = $r["Title"];
$tag = $r["Tag"];
$year = $r["YEAR"];
$cast = $r["Cast"];
$comment = $r["Comment"];
$IDBM = $r["IMDB"];
}
}
if (!empty($_POST) ) {
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
// keep track post values
$cast = $_POST['cast'];
$title = $_POST['title'];
$comment =$_POST['comment'];
$year = $_POST['year'];
$tag = $_POST['tags'];
$IDBM = $_POST['idbm'];
$cast = htmlspecialchars($cast);
$title = htmlspecialchars($title);
$comment = htmlspecialchars($comment);
// validate input
$valid = true;
if (empty($cast)) {
$castError = 'Please enter Cast';
$valid = false;
}
if (empty($title)) {
$titleError = 'Please enter Title';
$valid = false;
}
if (empty($comment)) {
$commentError = 'Please enter Comment';
$valid = false;
}
if ($valid) {
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
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<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysqli_query($dbc,"UPDATE movie SET Title='$title',Year = '$year',Cast='$cast',Cover='$actual_image_name',Tag='$tag',Comment='$comment',IMDB ='$IDBM' WHERE MovieID=".$id);
header ("Location: index.php");
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
}
}
echo"error";
}
How about this:
$id = strip_tags(intval($_GET['id']));
mysqli_query($dbc,"UPDATE `movie` SET `Title`='{$title}', `Year` =
'{$year}', `Cast`='{$cast}',
`Cover`='{$actual_image_name}',`Tag`='{$tag}', `Comment`='{$comment}',
`IMDB` ='{$IDBM}' WHERE `MovieID`='{$id}';");
To verify if $id have same value:
echo $id;
It sounds like maybe your MovieID isn't defined as an integer but we can't tell for sure because you haven't told us the error message that mysqli_query is throwing.
You need to be checking the error message created by mysqli_query to know. See http://www.php.net/manual/en/mysqli.error.php
try this
$id = $_GET['id']; // taking the value from URL
mysqli_query($dbc,"UPDATE movie SET Title='$title',Year = '$year',Cast='$cast',Cover='$actual_image_name',Tag='$tag',Comment='$comment',IMDB ='$IDBM' WHERE MovieID=".$id); // the sql statement of the query
and best you protect the get by using intval() to prevent injections
$id = intval($_GET['id']); // taking the value from URL

Categories