Rename the files while uploading - php

I am trying to rename the files while uploading, but it's not renaming as I expected. Just want to add the date and the time front of the name.
Attaching the code below.
if(isset($_FILES['img_ct_1'])){
$today = date("Ymd");
//prepare url
$temp_path = CDN_URL.'photos/';
$name_array = $_FILES['img_ct_1']['name'];
$tmp_name_array = $_FILES['img_ct_1']['tmp_name'];
$type_array = $_FILES['img_ct_1']['type'];
$size_array = $_FILES['img_ct_1']['size'];
$error_array = $_FILES['img_ct_1']['error'];
$upload_dir = $_SERVER['DOCUMENT_ROOT'].'/photos/';
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i],$upload_dir.time().$name_array[$i])){
print_r ($name_array[$i]);
$array['path'] = $temp_path.$newfilename;
$array['success'] = true ;
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}

Try this way:
for($i = 0; $i < count($tmp_name_array); $i++){
$file = $today.time().$name_array[$i];
if(move_uploaded_file($tmp_name_array[$i], $upload_dir . $file)){
print_r ($name_array[$i]);
$array['path'] = $temp_path.$newfilename;
$array['success'] = true ;
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}

Related

Php code to read multiple file and return the last line

Am trying to read multiple file and display the last line of each file but my code is not working very fine i don't know what am doing wrong.
<?php
if(isset($_GET['fid'], $_GET['timestamp']) && !empty($_GET['fid'])){
$lastmodif = isset( $_GET['timestamp']) ? $_GET['timestamp']: 0 ;
$fl_session = preg_replace("/[^0-9=]+/", "", $_GET['fid']);
if(strpos($fl_session, '==') !== false) {
$fl_session = explode('==', $fl_session);
foreach($fl_session as $fn){
$filename = dirname(__FILE__).'/logs/foo_'.$fn.'.txt';
$currentmodif = filemtime($filename);
while($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif = filemtime($filename);
}
if(file_exists($filename)){
$myfile = fopen($filename, "r") or die("Unable to load readme file!");
if($myfile){
$log = fread($myfile, filesize($filename));
fclose($myfile);
}
$log = explode("\n", trim($log));
for ($i = 0; $i < count($log); $i++) {
$log[$i] = trim($log[$i]);
$log[$i] = explode('|', $log[$i]);
}
foreach ($log as $logline) {
$response['id'] = trim($logline['0']);
$response['type'] = trim($logline['3']);
}
}
$response[$fn]['timestamp'] = $currentmodif;
//$response['timestamp'] = $currentmodif;
//var_export($response);
echo json_encode($response);
}
}
}
In my GET['fid'] parameter it contain something like this 12345==09765==87765, so i will explode it and loop on every id to locate the file name foo_12345.txt, foo_09765.txt, foo_87765.txt. This current code returned something like this from one txt file and ignored other files.
{ "id":"58287469", "type":"client", "8942180223":{
"timestamp":1505409432 } } { "id":"53094615", "type":"client",
"8942180223":{ "timestamp":1505409432 }, "4582422934":{
"timestamp":1505409420 } }

gallery with next and prev function

I'm working on an image gallery as my first real project as of learning php.. The problem I'm not able to get around somehow is using the "previous" button. My "next" function grabs the next 6 images from the folder and posts them to the page, my prev function does this in reverse.. but that's incorrect, can you help? oh, and this code is sloppy beginner code so i'm happy for tips :)
<?php
session_start();
if(session_id() == '') {
$_SESSION["count"] = 0;
}
function PostHTML($id, $file) {
if($id==0) {
echo "<div class=\"item\"><div class=\"well\"><img
class=\"img-responsive\" src=\"$file\" alt=\"\"><p>blahblahblah xxxxxx</p></div></div>";
}else{
echo "<div class=\"item\"><div class=\"well\"><video autoplay
loop class=\"img-responsive\"><source src=\"$file\" type=\"video/mp4\"></video></div></div>";
}
}
function next_img() {
$dir = "images/src/*.*";
$files = array();
$start = $_SESSION["count"];
$end = $_SESSION["count"]+6;
$y=0;
foreach(glob($dir) as $file) {
$files[$y] = $file;
$y++;
}
for($i=$start; $i < $end; $i++){
if(pathinfo($files[$i], PATHINFO_EXTENSION)=="jpg") {
PostHTML(0,$files[$i]);
} else {
PostHTML(1,$files[$i]); }
}
$_SESSION["count"]+=6;
}
function prev_img() {
$dir = "images/src/*.*";
$files = array();
$start = $_SESSION["count"]-1;
$end = $_SESSION["count"]-6;
$y=0;
foreach(glob($dir) as $file) {
$files[$y] = $file; //100 files
$y++;
}
for ($i = $start; $i > $end; $i--) {
if(pathinfo($files[$i], PATHINFO_EXTENSION)=="jpg") {
PostHTML(0,$files[$i]);
} else {
PostHTML(1,$files[$i]);
}
}
$_SESSION["count"]-=6;
}
?>
If i were to do something like this I might create a File Controller class to manage all the file operations i might need.
<?php
class FileController
{
private $_dir = "DIR";
private $files;
private $current;
function__construct()
{
$current = 0;
$files = scandir($_dir); // scans the dir to get a list of file names
if(!$files) echo "Failed To Load Files"; // failed to load files
else
{
$this->file = $files; // objects propery contains all file names in array;
}
}
function PostHTML($fileName) {
$src = $this->_dir + "/" + $fileName;
if(!$fileName)
{
return "<div class=\"item\"><div class=\"well\"><img
class=\"img-responsive\" src=\"$src\" alt=\"\"><p>blahblahblah xxxxxx</p></div></div>";
}
else
{
return "<div class=\"item\"><div class=\"well\"><video autoplay
loop class=\"img-responsive\"><source src=\"$src\" type=\"video/mp4\"></video></div></div>";
}
}
function nextImg()
{
$current = $this->getCurrent();
$end = $current + 6;
$this->setCurrent($end);
$files = $this->files;
$html = "";
for($i = $current; $i<= $end; $i++)
{
$html += postHtml($files[$i]);
}
echo $html;
}
function prevImg()
{
$current = $this->getCurrent();
$end = $current - 6;
$this->setCurrent($end);
$files = $this->files;
$html = "";
for($i = $current; $i>= $end; $i--)
{
$html += postHtml($files[$i]);
}
echo $html;
}
function getCurrent()
{
return $_SESSION['current'];
}
function setCurrent($current)
{
$_SESSION['current'] = $current;
}
}
?>

Removing the filename extension from a string

I'm creating a breadcrumb script like this:
<?php
if($location = substr(dirname($_SERVER['PHP_SELF']), 1))
$dirlist = explode('/', $location);
else
$dirlist = array();
$count = array_push($dirlist, basename($_SERVER['PHP_SELF']));
$address = 'http://'.$_SERVER['HTTP_HOST'];
echo 'home';
for ($i = 0; $i < $count; $i++)
echo ' » '.$dirlist[$i].'';
?>
If form url is http:// domain /school/students.php,
the result is like this: ( home » school » students.php )
Question: How to eliminate the extension .php file students.php,
be like this ( home » school » students ) ??
No matter how long is the extension or its name, this will work :
<?php
if($location = substr(dirname($_SERVER['PHP_SELF']), 1))
$dirlist = explode('/', $location);
else
$dirlist = array();
$count = array_push($dirlist, basename($_SERVER['PHP_SELF']));
$address = 'http://'.$_SERVER['HTTP_HOST'];
echo 'home';
for ($i = 0; $i < $count; $i++) {
$result = $dirlist[$i];
if ($i == ($count-1)) { // if last element
$lastDot = strripos($result,'.') ;
$result = substr($result,0,$lastDot) ;
}
echo ' » '.$result.'';
}
?>
how about using string replacement?
Here's a bit of code that may point you in the right direction, replacing your for loop.
for ($i = 0; $i < $count; $i++) {
$label = str_replace('.php', '', $dirlist[$i]);
echo ' » '.$label.'';
}
Try deducting string
<?php
if($location = substr(dirname($_SERVER['PHP_SELF']), 1))
$dirlist = explode('/', $location);
else
$dirlist = array();
$count = array_push($dirlist, basename($_SERVER['PHP_SELF']));
$address = 'http://'.$_SERVER['HTTP_HOST'];
echo 'home';
for ($i = 0; $i < $count; $i++)
if(!isset($dirlist[$i+1]))
{
echo ' » '.substr($dirlist[$i],0,-4).'';
}
else
{
echo ' » '.$dirlist[$i].'';
}
?>
this will work.

Sort result alphabetically

function printAll($dirName)
{
if (empty($leid)) { $leid = "1"; }
$root = $_SERVER['DOCUMENT_ROOT'];
$site = $_GET['site'];
$user = $_GET['user'];
$tag = "";
$dirs=array($dirName);
$files=array();
while($dir=array_pop($dirs)){
$handle=opendir($dir);
while($file=readdir($handle)){
if($file!='.' && $file!='..'){
$dest=$dir.'/'.$file;
$userid = str_replace("$root/", "", $dir);
$userid = str_replace("dl/$site","",$userid);
$userid = str_replace("/","",$userid);
if(is_file($dest)){
$files[]=$file;
$titrepost = htmlspecialchars($file);
$downloadlink = "$dest";
$downloadlink = str_replace("$root/", "", $downloadlink);
$za = new ZipArchive();
$za->open($downloadlink);
$leid = $leid + 1;
echo "<br>
<b>File = $file</b><br>
Userid = $userid
<br>";
for( $i = 0; $i < $za->numFiles; $i++ ){
$stat = $za->statIndex( $i );
$toune = basename( $stat['name'] );
echo "$toune <br>";
}
} else {
$dirs[]=$dest;
}
}
}
}
return $files;
}
$site = $_GET['site'];
$currentdir = getcwd();
$source = "$currentdir/dl/$site";
if (!empty($user)) {
$source = "$currentdir/dl/$site/$user";
}
printAll($source);
This script will list all files inside a ZIP archive then echo the name of each files.
Now i'm having some trouble figuring how to sort the files names ($toune) alphabetically
Here's what i tried:
for( $i = 0; $i < $za->numFiles; $i++ ){
$stat = $za->statIndex( $i );
$toune_arr[] = basename( $stat['name'] );
}
asort($toune_arr);
print_r($toune_arr);
But it doesn't work for this code, $toune_arr won't empty after each zip file is listed so each time the script output the filelist it contains the files of the previous zip archives.
Just reset your array in the begining of your function:
function printAll($dirName)
{
$toune_arr = array();
...

Export row from CSV file to JSON

I want to export a row in CSV file to JSON file with require : 1 line in CSV export 1 file JSON. I success to export file,but can't filter the row that i want to export. Can anyone help me?
<?php
header('Content-type: application/json');
$feed = 'jsondata_palpad.csv';
$keys = array();
$newArray = array();
function csvToArray($file, $delimiter) {
if (($handle = fopen($file, 'r')) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) {
for ($j = 0; $j < count($lineArray); $j++) {
$arr[$i][$j] = $lineArray[$j];
}
$i++;
}
fclose($handle);
}
return $arr;
}
$data = csvToArray($feed, ',');
$count = count($data) - 1;
$labels = array_shift($data);
foreach ($labels as $label) {
$keys[] = $label;
}
$keys[] = 'id';
for ($i = 0; $i < $count; $i++) {
$data[$i][] = $i;
}
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
$newArray[$j] = $d;
}
//Xuat file JSON
for ($i = 0; $i < 5; $i++) {
$json = json_encode($newArray[$i]);
echo $json . "<br />\n";
$filename = $data[$i][1] . ".json";
echo $filename . "<br />\n";
//echo "title[" . $data[$i][4] . "]";
$handle = fopen("./" . $filename, "w");
fwrite($handle, $json);
fclose($handle);
}
?>
If recommend = 2,it will export line whre id=2.
I want to export id,product_id,title,outline to JSON file.This is sample JSON file:
http://img839.imageshack.us/img839/5277/21527799.png
This is CSV file :
http://img690.imageshack.us/img690/1526/43004273.png
You are looping through all 6 lines of the csv file and saving them to the JSON file:
for ($i = 0; $i < 5; $i++) {
...
}
If you know what row number it is you want, don't loop through every row - just call the code inside the loop for that row. For example, if you wanted the 2nd row:
$row_we_want = 1;
$json = json_encode($newArray[$row_we_want]);
$filename = $data[$row_we_want][1] . ".json";
$handle = fopen("./" . $filename, "w");
fwrite($handle, $json);
fclose($handle);
If you are unsure about which row it is and need to check each one, you could do so in the loop:
for ($i = 0; $i < 5; $i++) {
if (some_condition) {
$json = json_encode($newArray[$i]);
$filename = $i][1] . ".json";
$handle = fopen("./" . $filename, "w");
fwrite($handle, $json);
fclose($handle);
}
}
Also it might be worth replacing 5 in your loop with the length of the array using the count function if it is not always a fixed length.

Categories