Issue with LONGBLOBs in MySQLi - php

I'm trying to insert LONGBLOBs to my database. Unfortunately when I click insert nothing is being inserted in the db. When I change the column type to BLOB everything is fine but the blob size capacityis too small so I really need LONGBLOBs. Using blob I can add only a 64kb file. Using longblob I can insert a file which is much larger. What's why I need to use LONGBLOB. I'm using MySQLi and PHP. Could you help me out?
if($_POST && $_FILES['uploadFile']['size'] > 0) {
$name = $_FILES['uploadFile']['name'];
$_SESSION['fileType'] = $_FILES['uploadFile']['type'];
$data = $_FILES['uploadFile']['tmp_name'];
//$data = addslashes($data);
$ifImage = getimageSize($_FILES['uploadFile']['tmp_name']);
$getAuthorID = $_SESSION['userID'];
$_SESSION['ifImage'] = $ifImage;
echo '<pre>'.print_r($_SESSION['ifImage'], true).'</pre>';
$fp = fopen($data, 'rw');
$content = fread($fp, filesize($data));
$content = addslashes($content);
fclose($fp);
/* SELECT FILE ID BY IT'S NAME */
$selectIDname= "SELECT fileID FROM files WHERE fileName = '$name'";
$selectIDnameQuery = mysqli_query($connection, $selectIDname);
$row = mysqli_fetch_array($selectIDnameQuery);
$selectIDname = $row['fileID'];
echo '<pre>ID: '.print_r($selectIDname, true).'</pre>';
$_FILES['uploadFile']['fileID'] = $row['fileID'];
/* INCREMENT FILE ID */
$selectFileIDQuery = mysqli_query($connection, "SELECT fileID FROM filescontent ORDER BY fileID DESC LIMIT 1");
$fetchFileID = mysqli_fetch_assoc($selectFileIDQuery);
$incrementFileID = $fetchFileID['fileID'] + 1;
/* GET AND INCREMENT FILE VERSION */
$getVersionsObject = new File($_FILES['uploadFile']['fileID']);
$fetchVersions = $getVersionsObject->getVersions();
$fetchLastElement = end($fetchVersions);
$incrementVersion = $fetchLastElement + 1;
echo '<pre>Version: '.print_r($incrementVersion, true).'</pre>';
/* SELECT FILE NAME FROM DB */
$selectName = mysqli_query($connection, "SELECT fileName FROM files WHERE fileName='$name'");
$fetchName = mysqli_fetch_assoc($selectName);
$fetchName = $fetchName['fileName'];
if(!strcmp($name, $fetchName)){
echo 'The file exists <br>';
$insertIntoFilescontentObject = new File($_FILES['uploadFile']['fileID']);
$insertIntoFilescontent = $insertIntoFilescontentObject->uploadContentIntoFilescontentFileExist($selectIDname, $incrementVersion, $content, $getAuthorID);
}
else{
echo 'The file does not exist';
$insertIntoFilesObject = new File($_FILES['uploadFile']['fileID']);
$insertIntoFiles = $insertIntoFilesObject->uploadContentIntoFiles($incrementFileID, $name, $getAuthorID);
$insertIntoFilescontentObject = new File($_FILES['uploadFile']['fileID']);
$insertIntoFilescontent = $insertIntoFilescontentObject->uploadContentIntoFilescontentFileNotExist($incrementFileID, $incrementVersion, $content, $getAuthorID);
}
$mysqliErorr = mysqli_error($connection);
echo '<br>'.$mysqliErorr.'<br>';
//header("Location: listFiles.php");
}
else if($_POST && $_FILES['uploadFile']['size'] == 0) {
echo 'You have not chosen a file';
}
}

Related

Problems to import csv-file into mySQL with PHP

I'm trying to import a large csv-file which is tab-seperated (\t).
My steps to achieve this:
Upload the csv-file
Create a new table in my database (filename without .csv)
Because of the size of the file, split it into batches
Send the batches to my database
The table will be created. But it is empty and I don't know why. Thank you for your help.
upload.php
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script>
//Declaration of function that will insert data into database
function senddata(filename, table){
var file = filename;
$.ajax({
type: "POST",
url: "senddata.php",
data: {file: file, table: table},
async: true,
success: function(html){
//$("#result").html(html);
}
})
}
</script>
<?php
$csv = array();
$batchsize = 1000; //split huge CSV file by 1,000
$fileName = $_FILES['csv']['name'];
$table = basename($fileName, ".csv");
$table = strval( $table);
echo "<script> console.log('File & Table-Name: $table') </script>";
// sql to create table
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
$DB_HOST = "XXXX";
$DB_NAME = "XXXX";
$DB_USER = "XXXX";
$DB_PASS = "XXXX";
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
die('Connection failed [' . $conn->connect_error . ']');
};
$query = "SELECT ID FROM " . $table; // that should be id and not ID
//$result = mysql_query($mysql_connexn, $query);
$result = mysqli_query($conn,$query);
if(empty($result)) {
echo "<script> console.log('Table: $table created!') </script>";
$query = mysqli_query($conn,"CREATE TABLE IF NOT EXISTS `$table` (
id VARCHAR(8),
preferred_term VARCHAR(217),
synonyms VARCHAR(217),
PRIMARY KEY(synonyms)
)");
}
else {
echo "<script> console.log('Table: $table already exists!') </script>";
} // else
if($_FILES['csv']['error'] == 0){
$name = $_FILES['csv']['name'];
$tmp = explode('.', $_FILES['csv']['name']);
$endTmp = end($tmp);
$ext = strtolower($endTmp);
$tmpName = $_FILES['csv']['tmp_name'];
if($ext === 'csv'){ //check if uploaded file is of CSV format
if(($handle = fopen($tmpName, 'r')) !== FALSE) {
set_time_limit(0);
$row = 0;
while(($data = fgetcsv($handle, $batchsize, "\t")) !== FALSE) {
//echo "<script>console.log($data) </script>";
$col_count = count($data);
//splitting of CSV file :
if ($row % $batchsize == 0):
$file = fopen("chunks$row.csv","w");
endif;
$csv[$row]['col1'] = $data[0];
$csv[$row]['col2'] = $data[1];
$csv[$row]['col3'] = $data[2];
$id = $data[0];
$preferred_term = $data[1];
$synonyms = $data[2];
$json = "'$id', '$preferred_term', '$synonyms'";
fwrite($file,$json.PHP_EOL);
//sending the splitted CSV files, batch by batch...
if ($row % $batchsize == 0):
//echo "<script> console.log('chunks$row.csv', '$table'); </script>";
echo "<script> senddata('chunks$row.csv', '$table'); </script>";
endif;
$row++;
}
fclose($file);
fclose($handle);
}
}
else
{
echo "Only CSV files are allowed.";
}
//alert once done.
echo "<script> console.log('CSV File imported!') </script>";
}
?>
senddata.php
<?php
include('connect.php');
$data = $_POST['file'];
$table = $_POST['table'];
$handle = fopen($data, "r");
if ($handle) {
$counter = 0;
//instead of executing query one by one,
//prepare 1 SQL query that will insert all values from the batch
$sql ="INSERT INTO `$table`(id,preferred_term,synonyms) VALUES ";
while (($line = fgets($handle, "\t")) !== false) {
$sql .= "($line),";
$counter++;
}
$sql = substr($sql, 0, strlen($sql) - 1);
if ($conn->query($sql) === TRUE) {
} else {
}
fclose($handle);
} else {
}
//unlink CSV file once already imported to DB to clear directory
unlink($data);
?>
Consider using LOAD DATA mysql function, it's extremely fast and it was developed for this purpose (heavy file loading).
https://dev.mysql.com/doc/refman/8.0/en/load-data.html
Example :
LOAD DATA INFILE 'data.csv'
INTO TABLE my_table
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
So you don't need to loop over each elements, you only configure delimiter, end of line character, etc.
It's more efficient than to do it with php and a big function.

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?

Cannot upload large csv files

I wrote a php script to extract data from a csv script and insert it into an mysql database. It does the job but does not extract data and insert into database for large csv files.(I tried extracting and inserting from a csv file with 40,000 rows. Did not work but worked when i tested it out with a far smaller (60 rows) size csv file). I get no error message. It just doesn't work. During debugging i realised even echoing a string after selecting a large csv file and clicking my upload button does not work. I've searched and tried all the possible configurations in php.ini as well as LimitRequestBody for apache config as well as setting configs directly in my code to no success. Some help would be greatly appreciated. My code is below.
<?php
include ("connection.php");
if(isset($_POST["submit"]))
{
ini_set('auto_detect_line_endings',TRUE);
$file_name = $_FILES['file']['tmp_name'];
$sql10 = "insert into upload (filename) values ('$file_name')";
if(mysqli_query($conn, $sql10)){
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " .$last_id;
}
//mysqli_close($conn);
$file = $_FILES['file']['tmp_name'];
//ini_set("auto_detect_line_endings", true);
$handle = fopen($file, "r");
$c = 0;
while(($filesop = fgetcsv($handle, ",")) !== false)
{
if ($c > 0) {
$event_id = $filesop[0];
$conf_session_id = $filesop[1];
$service_provider_id = $filesop[2];
$service_provider_id2 = $filesop[3];
$billed_flag = $filesop[4];
$offering_id = $filesop[5];
$time_start = $filesop[6];
$time_ended = $filesop[7];
$duration = $filesop[8];
$orig_calling_code = $filesop[9];
$orig_area_code = $filesop[10];
$termination_reason = $filesop[11];
$rtp_encoding = $filesop[12];
$rtp_clock_rate = $filesop[13];
$sip_from = $filesop[14];
$sip_to = $filesop[15];
$sip_call_id = $filesop[16];
$orig_nbr = $filesop[17];
$dest_nbr = $filesop[18];
$popd_account_number = $filesop[19];
$intl_dest_flag = $filesop[20];
$sip_status = $filesop[21];
$gw_ip_ingress = $filesop[22];
$gw_port_egress = $filesop[23];
$phone_number = $filesop[24];
$orig_flag = $filesop[25];
$subscriber_sip_caller_id = $filesop[26];
$orig_route_type = $filesop[27];
$term_route_type = $filesop[28];
$call_type = $filesop[29];
$mny_BasePrice = $filesop[30];
$call_cost = $filesop[31];
$uploadID = $last_id;
$sql11 = "insert into cdr (event_id, conf_session_id, service_provider_id, service_provider_id2, billed_flag, offering_id, time_start, time_ended, duration, orig_calling_code, orig_area_code, termination_reason, rtp_encoding, rtp_clock_rate, sip_from, sip_to, sip_call_id, orig_nbr, dest_nbr, popd_account_number, intl_dest_flag, sip_status, gw_ip_ingress, gw_port_egress, phone_number, orig_flag, subscriber_sip_caller_id, orig_route_type, term_route_type, call_type, mny_BasePrice, call_cost, uploadID, date_uploaded) values ('$event_id', '$conf_session_id', '$service_provider_id', '$service_provider_id2', '$billed_flag', '$offering_id', '$time_start', '$time_ended', '$duration', '$orig_calling_code', '$orig_area_code', '$termination_reason', '$rtp_encoding', '$rtp_clock_rate', '$sip_from', '$sip_to', '$sip_call_id', '$orig_nbr', '$dest_nbr', '$popd_account_number', '$intl_dest_flag', '$sip_status', '$gw_ip_ingress', '$gw_port_egress', '$phone_number', '$orig_flag', '$subscriber_sip_caller_id', '$orig_route_type', '$term_route_type', '$call_type', '$mny_BasePrice', '$call_cost', '$uploadID', CURRENT_DATE)";
if(mysqli_query($conn, $sql11)){
// $last_id = mysqli_insert_id($conn);
// echo "New record created successfully. Last inserted ID is: " .$last_id;
$updatequery = "UPDATE cdr JOIN client ON cdr.orig_nbr = client.phonenumber SET cdr.clientname = client.clientname";
mysqli_query($conn, $updatequery);
} else{
echo "error: ".mysqli_error($conn);
}
}
$c++;
}
fclose($handle) ;
}
?>

Use a variable from one IF - Statement into the other IF - Statement in PHP

I have a variable $target inside an IF - Statement in my login.php. I created the folders and sub-folders based on this variable. Now i want to move the uploaded file to this location. How can I do that?
here is the code
$upload = "E:/demons";
if(isset($_POST['userid'], $_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM template WHERE uname = '$userid' and pword = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo "公司".'<br/>';
echo $row['client'].'<br/>'.'<br/>';
echo "第".'<br/>';
echo '<a href="upload.html"/>'.$row['day1'].'</a>'.'<br/>';
$target = $upload.'/'.$row['week'].'/'.$row['day1'].'/'.$row['client'].'/'.$row['brand'].'/'.$row['sc'].'/';
$imagename = $row['week'].'.'.$row['day1'].'.'.$row['client'].'.'.$row['brand'].'.'.$row['sc'].'.'.'jpg';
if(!file_exists($target))
{
mkdir($target,null,true);
}
}
else if(isset($_FILES['image']))
{
$image = basename($_FILES["image"]["name"]);
echo $image;
//$target4 = $upload.'/'.$row['week'].'/'.$row['day1'].'/'.$row['client'].'/'.$row['brand'].'/'.$row['sc'].'/';
move_uploaded_file($_FILES['image']['tmp_name'], $target);
}
else
{
echo "asdfg";
}
Userid and Pid comes from login.html and Image value comes from upload.html
Nest the else-if as an if in the first if. Otherwise it won't be executed.
$upload = "E:/demons";
if(isset($_POST['userid'], $_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM template WHERE uname = '$userid' and pword = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo "公司".'<br/>';
echo $row['client'].'<br/>'.'<br/>';
echo "第".'<br/>';
echo '<a href="upload.html"/>'.$row['day1'].'</a>'.'<br/>';
$target = $upload.'/'.$row['week'].'/'.$row['day1'].'/'.$row['client'].'/'.$row['brand'].'/'.$row['sc'].'/';
$imagename = $row['week'].'.'.$row['day1'].'.'.$row['client'].'.'.$row['brand'].'.'.$row['sc'].'.'.'jpg';
if(!file_exists($target))
{
mkdir($target,null,true);
}
if(isset($_FILES['image']))
{
$image = basename($_FILES["image"]["name"]);
echo $image;
move_uploaded_file($_FILES['image']['tmp_name'], $target);
}
}
$upload = "Your desired location";
//comes from the login.html page
if(isset($_POST['userid'],$_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM template WHERE uname = '$userid' and pword = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo "Whatever coloumn you wish to echo from database".'<br/>';
echo $row['col1'].'<br/>'.'<br/>';
echo "Second Coloumn".'<br/>';
echo '<a href="upload.html"/>'.$row['col2'].'</a>'.'<br/>';
//create the folders and subfolders based on the data from the database
$target = $upload.'/'.$row['col1'].'/'.$row['col2'].'/'.$row['col3'].'/'.$row['col4'].'/'.$row['col5'].'/';
//for renaming the image.
$imagename = $row['col1'].'.'.$row['col2'].'.'.$row['col3'].'.'.$row['col4'].'.'.$row['col5'].'.'.'jpg';
//create the folders and subfolders
if(!file_exists($target))
{
mkdir($target,null,0777);
}
//start session and store the value of $target and $imagename in a variable
session_start();
$_SESSION['str'] = $target;
$_SESSION['img'] = $imagename;
//This comes from other HTML page but to the same PHP.
if(isset($_FILES['image']))
// image upload from upload.html
// Want the value of target here.
{
session_start();
$_SESSION['str'];
$_SESSION['img'];
$image = basename($_FILES["image"]["name"]);
//Move the uploaded file to the desired location.
move_uploaded_file($_FILES['image']['tmp_name'], $_SESSION['str'].$_SESSION['img']);
echo "Upload Successful";
Hope this would be helpful for all.

Problems deleting File PHP

This is my code to pull information from my sql database and then I want to delete the .txt files in each directory, but I can't seem to figure out why it won't delete the files.
<?php
session_start();
$user = $_SESSION['SESS_USERNAME'];
$id = array();
$id = $_POST['selected'];
//Include database connection details
require_once('config_order.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if (!$db) {
die("Unable to select database");
}
//Create query
$query = mysql_query("SELECT * FROM `PropertyInfo` WHERE `order_number` = '$id[0]'");
// display query results
while ($row = mysql_fetch_array($query)) {
$c_name = $row['clientname'];
$sitestreet = $row['sitestreet'];
$inspector = $row['inspector'];
}
mysql_close($link);
$client_name = str_replace(" ", "_", $c_name);
$site_street = str_replace(" ", "_", $sitestreet);
$client_name = "{$client_name}.txt";
$site_street = "{$site_street}.txt";
$client_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Clients";
$inspection_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Inspections";
if (unlink($client_path . "/" . $client_name)) {
echo 'File Deleted';
} else {
echo 'File could not be deleted';
}
?>
I think this is because your while loop is overwriting the $c_name, $sitestreet and $inspector variables. This means you will only ever delete the last file.
Is this what you were trying to do? (Edited Again...)
$query = mysql_query("SELECT * FROM `PropertyInfo` WHERE `order_number` IN (".mysql_real_escape_string(implode(',',$id)).")");
while ($row = mysql_fetch_array($query)) {
$inspector = $row['inspector'];
$client_name = str_replace(" ", "_", $row['clientname']).'.txt';
$site_street = str_replace(" ", "_", $row['sitestreet']).'.txt';
$client_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Clients";
$inspection_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Inspections";
if (!file_exists($client_path.'/'.$client_name)) {
echo "File $client_path/$client_name does not exist!\n";
} else echo (unlink($client_path.'/'.$client_name)) ? "File $client_path/$client_name was deleted\n" : "File $client_path/$client_name could not be deleted\n";
}
mysql_close($link);
Try some extra debugging:
$realpath = $client_path . '/' . $client_name;
if (file_exists($realpath)) {
if (is_writable($realpath)) {
if (unlink($realpath)) {
echo "$realpath deleted";
} else {
echo "Unable to delete $realpath";
}
} else {
echo "$realpath is not writable";
}
} else {
echo "$realpath does not exist";
}
On first glance, this is a problem, if $_POST['selected'] is not an array:
$id = array();
$id = $_POST['selected'];
...
$query = mysql_query("SELECT * FROM `PropertyInfo` WHERE `order_number` = '$id[0]'");
You are instantiating $id as an empty array, then overwriting it with $_POST['selected'], so $id[0] is the first character of the string $id.
For example, if $_POST['selected'] is 12345:
"SELECT * FROM `PropertyInfo` WHERE `order_number` = '$id[0]'"
is equivalent to:
"SELECT * FROM `PropertyInfo` WHERE `order_number` = '1'"
Either don't try to access it with an index or do $id[] = $_POST['selected']; to add the element onto the $id array instead.
Whether that is an array or not, you do need to either sanitize that input before you insert it into the query or use prepared statements, though!

Categories