Dear friends I have a simple code to move some images to dynamically created folders
Here is my code
ini_set('max_execution_time', -1);
include("connection.php");
$sql = "SELECT manufacturers.id, user_profiles.logo
FROM `manufacturers`
INNER JOIN user_profiles
WHERE manufacturers.user_id = user_profiles.user_id AND manufacturers.id > 2235";
$query=mysqli_query($live_db, $sql) or die("Connection failed: " . mysqli_connect_error($live_db));
while($row = mysqli_fetch_array($query) ){
$temp = '/home/aigae4z5r/mydomain.com/frontend/web/uploads/manufacturers/images/'. $row['logo'];
$idDir = '/home/aigae4z5r/mydomain.com/frontend/web/uploads/manufacturers/'.$id;
$destinationPath = $idDir . DIRECTORY_SEPARATOR . $row['logo'];
if (!is_dir($idDir)) {
mkdir($idDir, 0777, TRUE);
}
if (rename($temp, $destinationPath)) {
echo 'moved! <br />';
} else {
echo 'failed <br />';
}
}
The problem is to create new folders
if (!is_dir($idDir)) {
mkdir($idDir, 0777, TRUE);
}
Related
so i have this deletefile function and i want it to go back to tyhe home page after 3 seconds automaticly
public function deleteFile($id)
{
try {
$query = "SELECT naam, bestand_path FROM bestanden ";
$query .= "WHERE id='$id'";
$result = $this->datahandler->readsData($query);
$results = $result->fetchAll();
foreach ($results as $row) {
$filename = $row['naam'];
}
$file = getcwd() . "/uploads/" . $filename;
//echo "Absolute Path To Directory is: ";
//echo $delfile;
***if (unlink($file)) {
echo $filename . ' was deleted successfully!';
header('Location: ' . SERVER_URL . '/Home/');***
} else {
echo 'There was a error deleting ' . $filename;
}
$query = "DELETE FROM bestanden ";
$query .= "WHERE id=$id";
$result = $this->datahandler->deleteData($query);
} catch (PDOException $e) {
echo "Fout opgetreden";
}
}
its about the one with the stars around it.
thank you
So weird well annoying problem, I'm trying to upload images from a form (all works fine) However when there is no image it should set itself to NULL, but because i'm using $target_dir . basename it keeps taking the last part of the $target_dir instead of setting to NULL and inserting the word products into the database instead of nothing. But obv need the $target_dir for when the upload takes place to put in correct place. Please see code below, all help much appreciated.
$target_dir = "../images/products/";
if (!isset ($_FILES["img1"]["name"])) {
$target_file1 = NULL;
} else {
$target_file1 = $target_dir . basename($_FILES["img1"]["name"]);
}
if (!isset ($_FILES["img2"]["name"])) {
$target_file2 = NULL;
} else {
$target_file2 = $target_dir . basename($_FILES["img2"]["name"]);
}
if (!isset ($_FILES["img3"]["name"])) {
$target_file3 = NULL;
} else {
$target_file3 = $target_dir . basename($_FILES["img3"]["name"]);
}
if (!isset ($_FILES["img4"]["name"])) {
$target_file4 = NULL;
} else {
$target_file4 = $target_dir . basename($_FILES["img4"]["name"]);
}
SQL query and relevant info
<pre>
$image1 = basename($target_file1);
$image2 = basename($target_file2);
$image3 = basename($target_file3);
$image4 = basename($target_file4);
echo $image1;
echo $image2;
echo $image3;
echo $image4;
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO products (product_code, product_name, category,
filter, description, specification, img1, img2, img3, img4, price)
VALUES('$product_code', '$product_name', '$category', '$filter',
'$description', '$specification', '$image1', '$image2', '$image3',
'$image4', '$price')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
</pre>
K, changed it to set the values first and only assign value if isset
same thing, see screenshot of output below.
u can try
$target_dir = "../images/products/";
if (!isset ($_FILES["img1"]["name"])) {
$target_file1 = NULL;
} else {
if (!empty($_FILES["img1"]["name"])) {
$target_file1 = $target_dir . basename($_FILES["img1"]["name"]);
} else {
$target_file1 = NULL;
}
}
if (!isset ($_FILES["img2"]["name"])) {
$target_file2 = NULL;
} else {
if (!empty($_FILES["img2"]["name"])) {
$target_file2 = $target_dir . basename($_FILES["img2"]["name"]);
} else {
$target_file2 = NULL;
}
}
if (!isset ($_FILES["img3"]["name"])) {
$target_file3 = NULL;
} else {
if (!empty($_FILES["img3"]["name"])) {
$target_file3 = $target_dir . basename($_FILES["img3"]["name"]);
} else {
$target_file3 = NULL;
}
}
if (!isset ($_FILES["img4"]["name"])) {
$target_file4 = NULL;
} else {
if (!empty($_FILES["img4"]["name"])) {
$target_file4 = $target_dir . basename($_FILES["img4"]["name"]);
} else {
$target_file4 = NULL;
}
}
hi Guys my bulk image insert script for mysql isnt working.i cant figure out why.
I have the upload Script in root directory and the images in a folder called img in this folder a folders named by category with images in it so insert into mysql.but he says me everytime "There were no matching files to insert into the database." dont know why paths should be okay i think.
Here is the script guys
$connect = mysql_connect($server,$dbuser,$dbpass);
mysql_select_db($dbname,$connect);
$dirs = array_filter(glob('img/*'), 'is_dir');
foreach ($dirs as $dir) {
$path = "img/" . $dir . "/";
$files = array_map('mysql_real_escape_string', array_filter(glob("{$path}*.*"), 'is_file'));
if (empty($files)) {
echo "There were no matching files to insert into the database.";
} else {
$insertValues = array();
foreach ($files as $file) {
$data = getimagesize($file);
$width = $data[0];
$height = $data[1];
$insertValues[] = "('Titel', {$dir}, '{$file}', '$width', '$height')";
}
$query = "INSERT INTO `gbpics` (`gbpictitel`, `gbpiccat`, `gbpicurl`, `gbpicwidth`, `gbpicheight`) VALUES " . implode(', ', $insertValues);
if (!mysql_query($query)) {
echo "There was a problem inserting the data.";
trigger_error("Query failed: $query<br />Error: " . mysql_error());
} else {
echo "The data was inserted successfully.";
}
}
}
?>
I think
$path = "img/" . $dir . "/";
is duplicating the img/ part.
Probably should be
$path = $dir . "/";
Im running a Batch file as cronJob in my windows 7 machine,all I wanted is I want to create a log file ,when the cron Job is run along with the data,which it was displaying in the console.
The data ,is the echo statements which are present in the index.php which i have imported in the batch file.
Help me out to solve this issue.
index.php
<?php
echo "Welcome" ;
$fileD = "Login_".date('Y-m-d').".csv";
$fp1 = fopen($fileD, 'a+');
//Getting the files from below mentioned folder
$iterator1 = new FilesystemIterator("C:/wamp/www/logs1");
$iterator2 = new FilesystemIterator("C:/wamp/www/logs2");
$filelist = array();
foreach($iterator1 as $GLOBALS['entry1'])
{
if (strpos($entry1->getFilename(), "p1") === 0)
{
$filelist[] = $entry1->getFilename();
echo $entry1;
}
}
foreach($iterator2 as $GLOBALS['entry2']) {
if (strpos($entry2->getFilename(), "p2") === 0) {
$filelist[] = $entry2->getFilename();
echo "<br>";
echo $entry2;
}
}
$file1 = file_get_contents($entry1);
fwrite($fp1, $file1);
$file1 = file_get_contents($entry2);
fwrite($fp1, $file1);
fclose($fp1);
echo "<br/>";
echo "Done";
echo "<br/>";
//Deletes log file present in the logs folder
$n1= "$entry1";
if(!unlink($n1))
{
echo ("Error deleting file1 $n1");
}
else
{
echo ("Deleted $n1");
}
echo "<br/>";
$n2= "$entry2";
if(!unlink($n2))
{
echo ("Error deleting file2 $n2");
}
else
{
echo ("Deleted $n2");
}
echo "<br/>";
foreach (glob("*.csv") as $filename)
{
echo "$filename size " . filesize($filename) . "\n";
echo "<br>";
}
echo "<br>";
//$insertionDate = substr($filename,6,10);
$servername = "localhost";
$username = "user";
$password = "";
$dbname = "stat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$file = file_get_contents($fileD);
$count = preg_match_all("/,Login,/", $file, $matches);
echo "Csv first word ";
$insertionDate = substr($file,1,10);
echo "<br/>";
echo "Total Hits:" . $totalLines = count(file($fileD));
echo "<br/>";
echo "Login:" . $count;
// Insert the Total hits and the corresponding success and failure count
$sql = "INSERT INTO hit_s (HitDate, count, category,success,failure,tcount,ocount)
VALUES ('$insertionDate', $totalLines, 'Hits',$success,$fail,$treeCnt,$oCnt)";
if ($conn->query($sql) === TRUE) {
echo "Total hits record inserted successfully \n";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$iterator = new FilesystemIterator("C:/wamp/www/Fed");
$filelist1 = array();
foreach($iterator as $GLOBALS['entry3'])
{
if (strpos($GLOBALS['entry3']->getFilename(), "*.csv") === 0)
{
$filelist1[] = $GLOBALS['entry3']->getFilename();
}
}
echo $GLOBALS['entry3'];
echo "<br/>";
$entry3="$fileD";
$n3= "$entry3";
if(!unlink($n3))
{
echo ("Error deleting $n3");
}
else
{
echo ("Deleted $n3");
}
echo "<br/>";
$conn->close();
?>
In batch file im calling the index.php file like below
C:\wamp\bin\php\php5.4.16\php.exe C:\wamp\www\Fed\csv\index.php
It looks like syslog will work for you:
$access = date("Y/m/d H:i:s");
syslog(LOG_WARNING, "Unauthorized client: $access {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']);
I am trying to upload files to a directory created with PHP. The application should create a sub-directory inside the root directory according to a User's UserID. (for e.g. files/14/).
The directory is being created, however the files are not being uploaded to the sub-directory.
This is the code:
<?php
include("dbConfig.php");
$Username = $_SESSION["username"];
global $userid;
$Password = $_SESSION["password"];
$Password = md5($Password);
$sql = "SELECT UserID FROM users WHERE Username = '".$Username."'";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
$userid = $row['UserID'];
}
echo $userid;
$dirname = (string)$userid;
$filename = ("/folder/" . "$dirname" . "/");
if (!file_exists($filename))
{
mkdir("files/$dirname", 0777);
if (isset($_FILES['files'])) {
echo "<div id='files_table'><table class='center'.><tr><td>";
$dest = ("files/" . $dirname . "{$_FILES['files']['name'][$key]}");
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name){
move_uploaded_file($tmp_name, $dest );
echo $_FILES['files']['name'][$key], " uploaded.", "<br>";
}
}else {
if (isset($_FILES['files'])) {
echo "<div id='files_table'><table class='center'.><tr><td>";
$dest = ("files/" . $dirname . "{$_FILES['files']['name'][$key]}");
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name){
move_uploaded_file($tmp_name, $dest );
echo $_FILES['files']['name'][$key], " uploaded.", "<br>";
}
echo "</td></tr></table></div><br><br>";
}
}
}
Brain,
PHP support one file upload at one time, if you have many file fields in your form, you should keep "$dest = ("files/" . $dirname . "{$_FILES['files']['name'][$key]}");" in the loop.
$Key will be empty outside the loop.
Loop can't be on temp_name, temp_name is a temp copy of the file which php is going to upload.
Here is the modified code:
Note: I corrected some errors in your code too. please compare.
<?php
include("dbConfig.php");
$Username = $_SESSION["username"];
global $userid;
$Password = $_SESSION["password"];
$Password = md5($Password);
$sql = "SELECT UserID FROM users WHERE Username = '".$Username."'";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
$userid = $row['UserID'];
}
$dirname = (string)$userid;
$filename = ("$dirname" . "/");
if (!file_exists($filename)) {
mkdir("files/$dirname", 0775);
}
if (isset($_FILES['files'])) {
echo "<div id='files_table'><table class='center'.><tr><td>";
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name){
$dest = ("files/" . $dirname . "{$_FILES['files']['name'][$key]}");
move_uploaded_file($tmp_name, $dest );
echo $_FILES['files']['name'][$key], " uploaded.", "<br>";
}
}
?>