I'm trying to set up a php that receives variables in the URL, and then creates a passbook pass using that information.
If I manually set up the variables, everything works, but if I use $_GET to get the data from the URL, it won't show up.
Here is my index, were we are loading the variables from the URL.
<?php
$ac = $_GET['ac'];
$af = $ac;
$log = print_r($_SERVER,1);
$log .= print_r($_POST,1);
$log .= print_r($_GET,1);
file_put_contents('./log/'.time().'.txt', $log);
if(($_POST['time'] != '')||($_GET['update'] != ''))
{
require('./passkit.php');
$Certificates = array('AppleWWDRCA' => './certs/AppleWWDRCA.pem',
'Certificate' => './certs/Certificate.p12',
'CertPassword' => 'password');
$ImageFiles = array('images/icon.png', 'images/icon#2x.png', 'images/logo.png');
$datostest = array( '1' => $af,
'2' => '5',
'3' => '6');
$data = array('./data/array.php',
'./data/json.php',
'./data/small.php',
'./data/coupon.json',
'./data/event.json',
'./data/small.json',
'./data/generic.json');
if($_GET['update'] != '')
{
$example_data = 4;
}
elseif(!is_numeric($_POST['aexample']))
{
$example_data = rand(0,6);
}
else
{
$example_data = $_POST['aexample'];
}
if($example_data < 3)
{
include($data[$example_data]);
}
else
{
$JSON = file_get_contents($data[$example_data]);
}
$TempPath = './temp/';
echoPass(createPass($Certificates, $ImageFiles, $JSON, 'passtest', $TempPath));
m_uwait(12500);
die();
}
?>
Here is the pass signing process
<?php
function PEM2DER($signature)
{
$signature = substr($signature, (strpos($signature, 'filename="smime.p7s"')+20));
return base64_decode(trim(substr($signature, 0, strpos($signature, '------'))));
}
function createPass($Certificates, $ImageFiles, $JSON, $PassName = 'pass', $TempPath = './temp/', $Debug = false)
{
//define pathes
$UniquePassId = time().hash("CRC32", $_SERVER["REMOTE_ADDR"].$_SERVER["HTTP_USER_AGENT"]);
$ManifestPath = $TempPath.$UniquePassId.'/manifest.json';
$SignaturePath = $TempPath.$UniquePassId.'/signature';
$PKPassPath = $TempPath.$UniquePassId.'/'.$PassName.'.pkpass';
//create temp dir
mkdir($TempPath.$UniquePassId, 0777, true);
//generate SHA1 hashes
$FileHashes['pass.json'] = hash("SHA1", $JSON);
foreach($ImageFiles as $ImagePath)
{
$ImageName = basename($ImagePath);
$FileHashes[strtolower($ImageName)] = hash("SHA1", file_get_contents($ImagePath));
}
//save hashes as json in temp file
$Manifest = json_encode($FileHashes);
file_put_contents($ManifestPath, $Manifest);
//load .p12 certificate
$PKCS12 = file_get_contents($Certificates['Certificate']);
$certs = array();
if(openssl_pkcs12_read($PKCS12, $certs, $Certificates['CertPassword']) == true)
{
$certdata = openssl_x509_read($certs['cert']);
$privkey = openssl_pkey_get_private($certs['pkey'], $Certificates['CertPassword']);
}
//sign file hashes with AppleWWDRCA certificate
openssl_pkcs7_sign($ManifestPath, $SignaturePath, $certdata, $privkey, array(), PKCS7_BINARY | PKCS7_DETACHED, $Certificates['AppleWWDRCA']);
$ManifestSignature = file_get_contents($SignaturePath);
$ManifestSignatureDER = PEM2DER($ManifestSignature);
//put files (and strings as files) in a zip archive
$ZIP = new ZipArchive();
$ZIP->open($PKPassPath, ZIPARCHIVE::CREATE);
$ZIP->addFromString('signature', $ManifestSignatureDER);
$ZIP->addFromString('manifest.json', $Manifest);
$ZIP->addFromString('pass.json', $JSON);
foreach($ImageFiles as $ImagePath)
{
$ImageName = basename($ImagePath);
$ZIP->addFile($ImagePath, $ImageName);
}
$ZIP->close();
//load pass data und delete temp files (if debug mode is off)
$Pass['data'] = file_get_contents($PKPassPath);
$Pass['size'] = filesize($PKPassPath);
$Pass['name'] = $PassName;
if(!$Debug)
{
unlink($TempPath.$UniquePassId.'/manifest.json');
unlink($TempPath.$UniquePassId.'/'.$PassName.'.pkpass');
unlink($TempPath.$UniquePassId.'/signature');
rmdir($TempPath.$UniquePassId);
}
return $Pass;
}
function echoPass($Pass)
{
//send http headers and zip archive content to client
header('Pragma: no-cache');
header('Content-type: application/vnd.apple.pkpass');
header('Content-length: '.$Pass['size']);
header('Content-Disposition: attachment; filename="'.$Pass['name'].'.pkpass"');
echo $Pass['data'];
}
?>
And finally, here I'm using those variables.
<?php
$PassStyle = "boardingPass";
$JSON = '{
"authenticationToken": "vxwxd7J8AlNNFPS8k0a0FfUFtq0ewzFdc",
"foregroundColor" : "rgb(255, 255, 255)",
"backgroundColor" : "rgb(27, 66, 152)",
"labelColor" : "rgb(108, 173, 223)",
"barcode": {
"format": "PKBarcodeFormatQR",
"message": "'.hash("SHA256", time().rand(0,2000000000)).'",
"messageEncoding": "iso-8859-1"
},
"description": "Random '.$PassStyle.' Demo Pass",
"foregroundColor": "rgb(251, 251, 251)",
"formatVersion": 1,
"'.$PassStyle.'": {
"primaryFields": [
{
"key": "number",
"value": "'.$datostest['1'].'"
}
]
},
"logoText": "passkit.php",
"organizationName": "Apple Inc",
"passTypeIdentifier": "pass.com.apple.demo",
"serialNumber": "8j23fm3",
"teamIdentifier": "123ABCDEFG"
}';
?>
Hope you can help. Can't understand why it works if the variable is manually assigned and it isn't if it is loaded from the URL.
Thanks
Look the code what you posted above is too much and i guess its difficult to check your problem...
According to the question i guess you are not able to access the Get values.
Let me tell you how get works...
<a href="filename.php?value='what_you_want_to_pass'">
and at your page...
$value = $_GET['value'];
this is the actual syntax, just check whether u have passed the value in your link...
Related
I have noticed that if a cell is empty phpexcel gives it a null value. Is there a way i can replace the null value with any empty string before i loop through the array and store into the database. Below is my code and i am using the codeigniter framework.
public function import(){
$id = $this->session->userdata('company_id');
$directoryname = get_company_full_name($id);
if (!is_dir(FCPATH.'assets/customer_documents/Databases/'.$directoryname)) {
mkdir(FCPATH.'assets/customer_documents/Databases/'.$directoryname, 0777, TRUE);
}
$database_name = $this->input->post('database_name');
// $data['addressbook'] = $this->csv_model->get_addressbook($id);
$data['errors'] = ''; //initialize upload error array to empty
$config['upload_path'] = FCPATH.'assets/customer_documents/Databases/'.$directoryname;
$config['allowed_types'] = '*';
$config['max_size'] = '';
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$data['errors'] = $this->upload->display_errors();
$data['databases'] = $this->database->get_databases($id);
$this->session->set_flashdata($data);
redirect(base_url().'Databases');
} else {
$file_data = $this->upload->data();
$file_ext = $file_data['file_ext'];
// use custom function to determine if filetype is allowed
if (allow_csv_type($file_ext))
{
$file_path = FCPATH.'assets/customer_documents/Databases/'.$directoryname. '/' .$file_data['file_name'];
//read file from path
$objPHPExcel = PHPExcel_IOFactory::load($file_path);
$date_uploaded = date("Y-m-d H:i:s");
if ($objPHPExcel) {
//get only the Cell Collection
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
//extract to a PHP readable array format
foreach ($cell_collection as $cell) {
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
//header will/should be in row 1 only. of course this can be modified to suit your need.
if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
}
}
// array_shift($arr_data); // removes the 1st/header element
//store the database name and details
$database_data = array(
'db_name'=>$database_name,
'company_id' => $id,
'deleted' => 0,
'date_uploaded'=> $date_uploaded
);
$this->database->insert_db($database_data);
$database_id = $this->db->insert_id();
foreach ($arr_data as $row) {
$insert_data = array(
'company_id' => $this->session->userdata('company_id'),
'number'=>$row['A'],
'province'=>$row['B'],
'district'=>$row['C'],
'ward'=>$row['D'],
'farming_type'=>$row['E'],
'commodity'=>$row['F'],
'database_name'=>$database_name,
'db_id' =>$database_id,
'deleted' => 0,
'date_uploaded'=>$date_uploaded
);
$this->database->insert_csv($insert_data, $id);
}
log_message('info', '*****************************Customer with the ID: '.$this->session->userdata('company_id').' and name: '.get_company_full_name($this->session->userdata('company_id')).' uploaded a csv database. The uploder phone number: '.$this->session->userdata('phone').' The database ID: '.$database_id.' The database name: '.$database_name.'*****************************');
$this->session->set_flashdata('success', 'Data Imported Succesfully');
redirect(base_url().'Databases');
} else{
$data['errors'] = "Error occured";
$data['page_class'] = 'Databases-page';
$data['title'] = 'Databases';
$data['content_view'] = 'Databases/index';
$this->template->admin_template($data);
}
}
else {
$this->session->set_flashdata('errors','File type is not allowed!');
redirect('Databases');
}
}
}
}
I am just looking for a way i can add empty sting values on the empty cells that are coming with null values.
Just use a simple array modifier before it reaches PHPExcel.
If performance is an issue, one may consider not to create multiple functions within array_map(). Note that isset() is extremely fast, and this solutions does not call any other functions at all.
$replacements = array(
'search1' => 'replace1',
'search2' => 'replace2',
'search3' => 'replace3'
);
foreach ($a as $key => $value) {
if (isset($replacements[$value])) {
$a[$key] = $replacements[$value];
}
}
See: https://stackoverflow.com/a/32321702/4272537
I am currently doing an internship and I tried to make an activity module to show playlist, from video given by a filemanager. I succeed to send the video to the database but when I want to edit my module, it doesn't show any videos in the filemanager.
I read the moodle documentation about file API and I decided to use the following code (Load existing files into draft area)
:
if (empty($entry->id)) {
$entry = new stdClass;
$entry->id = null;
}
$draftitemid = file_get_submitted_draft_itemid('attachments');
file_prepare_draft_area($draftitemid, $context->id, 'mod_glossary','attachment', $entry->id,array('subdirs' => 0, 'maxbytes' => $maxbytes, 'maxfiles' => 50));
$entry->attachments = $draftitemid;
$mform->set_data($entry);
So I put the following lines in my mod_form.php :
$filemanager_options = array();
$filemanager_options['accepted_types'] = '*';
$filemanager_options['maxbytes'] = 0;
$filemanager_options['maxfiles'] = -1;
$filemanager_options['mainfile'] = true;
$mform->addElement('filemanager', 'files', get_string('selectfiles'), null, $filemanager_options);
if (empty($entry->id)) {
$entry = new stdClass;
$entry->id = null;
}
$draftitemid = file_get_submitted_draft_itemid('mymanager');
file_prepare_draft_area($draftitemid, $this->context->id, 'mod_playlist', 'content', 0,
array('subdirs'=>true));
$entry->attachments = $draftitemid;
$mform->set_data($entry);
The problem is that the file manager is still empty, and the line "$mform->set_data($entry); " makes the page to crash(blank).
Here is a template for uploading files.
In local/myplugin/upload.php
require_once(dirname(dirname(dirname(__FILE__))) . '/config.php');
require_once(dirname(__FILE__) . '/upload_form.php');
require_login();
$context = context_system::instance();
require_capability('local/myplugin:upload', $context);
$pageurl = new moodle_url('/local/myplugin/upload.php');
$heading = get_string('myupload', 'local_myplugin');
$PAGE->set_context($context);
$PAGE->set_heading(format_string($heading));
$PAGE->set_title(format_string($heading));
$PAGE->set_url('/local/myplugin/upload.php');
echo $OUTPUT->header();
echo $OUTPUT->heading($heading);
$fileoptions = array(
'maxbytes' => 0,
'maxfiles' => '1',
'subdirs' => 0,
'context' => context_system::instance()
);
$data = new stdClass();
$data = file_prepare_standard_filemanager($data, 'myfiles',
$fileoptions, context_system::instance(), 'local_myplugin', 'myfiles', 0); // 0 is the item id.
$mform = new upload_form(
null,
array(
'fileoptions' => $fileoptions,
)
);
if ($formdata = $mform->get_data()) {
// Save the file.
$data = file_postupdate_standard_filemanager($data, 'myfiles',
$fileoptions, context_system::instance(), 'local_myplugin', 'myfiles', 0);
} else {
// Display the form.
$mform->set_data($data);
$mform->display();
}
echo $OUTPUT->footer();
Then in local/myplugin/upload_form.php
defined('MOODLE_INTERNAL') || die;
require_once($CFG->libdir . '/formslib.php');
class upload_form extends moodleform {
public function definition() {
$mform =& $this->_form;
$fileoptions = $this->_customdata['fileoptions'];
$mform->addElement('filemanager', 'myfiles_filemanager',
get_string('myfiles', 'local_myplugin'), null, $fileoptions);
$this->add_action_buttons(false, get_string('save', 'local_myplugin'));
}
}
You will also need this in /local/myplugin/lib.php
function local_myplugin_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = array()) {
if ($context->contextlevel != CONTEXT_SYSTEM) {
send_file_not_found();
}
$fs = get_file_storage();
$file = $fs->get_file($context->id, 'local_myplugin', $filearea, $args[0], '/', $args[1]);
send_stored_file($file);
}
I'm creating a form to upload a file, using yii and php 5.5.3. Here is my code in the controller:
foreach($_FILES['settings']['name'] as $settingName => $value) {
$setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName));
$setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']');
if (!empty($setting->image_file)) {
$extension = "jpg";
$filename = "";
if (($pos = strrpos($setting->image_file, '.')) !== FALSE) {
$extension = substr($setting->image_file, $pos + 1);
$filename = substr($setting->image_file, 0, $pos)."_".strtotime("now");
}
if (!file_exists("uploads") and !is_dir("uploads"))
mkdir("uploads", 0777, TRUE);
$setting->image_file->saveAs("uploads/" . $filename.".".$extension, false);
$setting->setting_value = "uploads/" . $filename.".".$extension;
$setting->save();
}
}
image_file is an extra attribute in model:
array('image_file', 'file', 'types' => 'gif, jpg, jpeg, png', 'maxSize' => 1024 * 1024, 'tooLarge' => 'File upload must not exceed 1MB.'),
and here is the view:
<input type="file" name="settings[store_logo]" class="input-small">
$setting->image_file->saveAs can successfully upload the file, but it also generates
Error 500 Creating default object from empty value
What went wrong? Any help would be much appreciated.
i guess, the $_FILES['settings']['name'] has a empty value in the last Key.
If you upload a File(s), they will be process as expected. The last value in your POST-array cause a NULL-return here:
// $setting === null
$setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName))
and this call throws the 500.
$setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']');
This is my Version of your code:
<?php
foreach($_FILES['settings']['name'] as $settingName => $value) {
$setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName));
// catch null-return
if(!$setting) {
echo "can't find stuff at<pre>"; print_r($settingName); echo "</pre>";
continue;
}
$setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']');
if ($setting->image_file) {
$extension = "jpg";
$filename = "";
if (($pos = strrpos($setting->image_file, '.')) !== FALSE) {
$extension = substr($setting->image_file, $pos + 1);
$filename = substr($setting->image_file, 0, $pos)."_".strtotime("now");
}
if (!file_exists("uploads") and !is_dir("uploads"))
// dont 0777!
mkdir("uploads", 0740, TRUE);
$setting->image_file->saveAs("uploads/" . $filename.".".$extension, false);
$setting->setting_value = "uploads/" . $filename.".".$extension;
$setting->save();
}
}
?>
What my problem is that I can not send array to solr machine in order to update. I am using codeigniter as a framework and here is my code:
$solrData = array();
$solrData['id'] = $this->data['profil_data']['id'];
$solrData['site'] = $this->data['profil_data']['site'];
$solrData['url_Domain'] = $this->data['profil_data']['url_Domain'];
$solrData['url_Page'] = $this->data['profil_data']['url_Page'];
$solrData['url_Profil'] = $this->data['profil_data']['url_Profil'];
$solrData['scr_Kobi_Rank'] = $this->data['profil_data']['scr_Kobi_Rank'];
$solrData['scr_A'] = $this->data['profil_data']['scr_A'];
$solrData['scr_B'] = $this->data['profil_data']['scr_B'];
$solrData['scr_C'] = $this->data['profil_data']['scr_C'];
$solrData['scr_D'] = $this->data['profil_data']['scr_D'];
$solrData['loc_City'] = $this->input->post('plakano');
$solrData['loc_Lat_Lon'] = $this->input->post('loc_Lat_Lon');
$solrData['com_Category'] = explode(',', $this->input->post('category'));
$urunData = $this->input->post('urun_list');
foreach($urunData as $row)
{
$ontoData = $this->m_onto->getOntoDataByOntoDataId($row);
$solrData['com_Products'][] = $ontoData['baslik'];
}
$hizmetData = $this->input->post('hizmet_list');
foreach($hizmetData as $row)
{
$ontoData = $this->m_onto->getOntoDataByOntoDataId($row);
$solrData['com_Services'][] = $ontoData['baslik'];
}
$solrData['com_Type'] = $this->input->post('sirketturu');
$solrData['com_Description'] = $this->input->post('description');
$solrData['com_Title_Selected'] = $this->input->post('title');
$solrData['com_Title_Long'] = $this->data['profil_data']['com_Title_Long'];
$solrData['crm_Tel'] = $this->input->post('tel');
$solrData['crm_Fax'] = $this->input->post('fax');
$solrData['crm_Email'] = $this->input->post('email');
$this->solr->updateSolrProfilData($solrData);
And solr process:
public function updateSolrProfilData($arrData)
{
if(count($arrData) == 0)
return FALSE;
$solrClientOptions = $this->solrClientOptionsYazProfil;
$solrClientOptionsCommit = $this->solrClientOptionsYazProfilCommit;
$solrClient = new SolrClient($solrClientOptions);
$solrDoc = new SolrInputDocument();
foreach($arrData as $firmaField => $firmaValue)
{
if(! is_array($firmaValue))
{
$solrDoc->addField($firmaField, $firmaValue);
}
else
{
foreach($firmaValue as $firmaField2 => $firmaValue2)
{
if($firmaValue2 != '')
{
$solrDoc->addField($firmaField, $firmaValue2);
}
}
}
}
try {
$this->_solrCommit($solrClientOptionsCommit);
} catch (Exception $e) {
echo $e->getMessage();
}
}
Solr Commit function:
private function _solrCommit($solrArr)
{
$urlCommit = 'http://' . $solrArr['hostname'] . ":" . $solrArr['port'] . '/' . $solrArr['path'] . "/update?stream.body=%3Ccommit/%3E&wt=json";
$output = file_get_contents($urlCommit);
$outputArr = json_decode($output, TRUE);
if ($outputArr['responseHeader']['status'] === 0)
return TRUE;
else
return FALSE;
}
And that is the options:
private $solrClientOptionsYazProfilCommit = array(
'hostname' => SOLR_HOST_YAZ,
'login' => '',
'password' => '',
'port' => SOLR_PORT,
'path' => 'solr/collection1'
);
Altough try-catch returns no error, the data can not be updated. Moreover, code sends solr commit succesfully. I checked the url but it is in correct form. What is wrong in here?
Dont use PHP/Pecl solr libs. If you can access solr via a URL then you should just use PHP and CURL:
static function doCurl($url, $username = null, $password = null) {
if (!function_exists('curl_init')) {
// throw error
}
$ch = curl_init();
$opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_TIMEOUT => 120,
CURLOPT_FAILONERROR => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY
);
if ($password != null && $username != null) {
$opts[CURLOPT_USERPWD] = "$username:$password";
}
curl_setopt_array($ch, $opts);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
usage is:
doCurl("http://hostNameHere:8983/solr/select/?q=solr&start=0&rows=10&indent=on", "user", "pass");
Your issue is that you are never issuing a command to Solr to add the document that you have built to your index. You are only issuing the commit command, which is executing successfully.
Since you are using PHP, I would recommend using the PHP SolrClient. This will save you from having to manually write all of the functions (add, delete, commit, etc.) yourself. In this case, you would need to call the addDocument function.
I'm trying to rename each file before uploading to Amazon S3.
I am trying to use this exact method of which was answered by #Silvertiger: PHP - upload and overwrite a file (or upload and rename it)?
If exists, rename to a random name although somehow it doesn't work.
Here is the upload post Parameter from the Amazon S3 Class:
public static function getHttpUploadPostParams($bucket, $uriPrefix = '', $acl = self::ACL_PRIVATE, $lifetime = 3600,
$maxFileSize = 5242880, $successRedirect = "201", $amzHeaders = array(), $headers = array(), $flashVars = false)
{
// Create policy object
$policy = new stdClass;
$policy->expiration = gmdate('Y-m-d\TH:i:s\Z', (time() + $lifetime));
$policy->conditions = array();
$obj = new stdClass; $obj->bucket = $bucket; array_push($policy->conditions, $obj);
$obj = new stdClass; $obj->acl = $acl; array_push($policy->conditions, $obj);
$obj = new stdClass; // 200 for non-redirect uploads
if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201)))
$obj->success_action_status = (string)$successRedirect;
else // URL
$obj->success_action_redirect = $successRedirect;
array_push($policy->conditions, $obj);
if ($acl !== self::ACL_PUBLIC_READ)
array_push($policy->conditions, array('eq', '$acl', $acl));
array_push($policy->conditions, array('starts-with', '$key', $uriPrefix));
if ($flashVars) array_push($policy->conditions, array('starts-with', '$Filename', ''));
foreach (array_keys($headers) as $headerKey)
array_push($policy->conditions, array('starts-with', '$'.$headerKey, ''));
foreach ($amzHeaders as $headerKey => $headerVal)
{
$obj = new stdClass;
$obj->{$headerKey} = (string)$headerVal;
array_push($policy->conditions, $obj);
}
array_push($policy->conditions, array('content-length-range', 0, $maxFileSize));
$policy = base64_encode(str_replace('\/', '/', json_encode($policy)));
// Create parameters
$params = new stdClass;
$params->AWSAccessKeyId = self::$__accessKey;
$params->key = $uriPrefix.'${filename}';
$params->acl = $acl;
$params->policy = $policy; unset($policy);
$params->signature = self::__getHash($params->policy);
if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201)))
$params->success_action_status = (string)$successRedirect;
else
$params->success_action_redirect = $successRedirect;
foreach ($headers as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal;
foreach ($amzHeaders as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal;
return $params;
}
Here is #Silvertiger's method:
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
This is my upload form:
<form method="post" action="<?php echo $uploadURL; ?>" enctype="multipart/form-data">
<?php
foreach ($params as $p => $v)
echo " <input type=\"hidden\" name=\"{$p}\" value=\"{$v}\" />\n";
?>
<input type="file" name="file" /> <input type="submit" value="Upload" />
</form>
And this is the Input info:
public static function inputFile($file, $md5sum = true)
{
if (!file_exists($file) || !is_file($file) || !is_readable($file))
{
self::__triggerError('S3::inputFile(): Unable to open input file: '.$file, __FILE__, __LINE__);
return false;
}
return array('file' => $file, 'size' => filesize($file), 'md5sum' => $md5sum !== false ?
(is_string($md5sum) ? $md5sum : base64_encode(md5_file($file, true))) : '');
}
You can do your renaming at this point in your code:
move_uploaded_file($tmp, $filelocation);
The $filelocation can be changed to whatever you want and the uploaded file will be renamed to that path.
Edit: The S3::getHttpUploadPostParams method always uses the file name from the upload to create the S3 resource. To change that you have to copy the method but change this line:
$params->key = $uriPrefix.'${filename}';
The '${filename} must be changed to a path of your choosing.
Replace this:
// Create parameters
$params = new stdClass;
$params->AWSAccessKeyId = self::$__accessKey;
$params->key = $uriPrefix.'${filename}';
with this:
function rand_string( $length ) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ ) {
$str .= $chars[ rand( 0, $size - 1 ) ];
}
return $str;
}
// Create parameters
$params = new stdClass;
$params->AWSAccessKeyId = self::$__accessKey;
$params->key = $uriPrefix.rand_string(5).'${filename}';
You can easily put this code.. 100 percent working.
<?php
$file=$_FILES['file']['name'];
$path ="upload/".$file;
$ext=pathinfo($path,PATHINFO_EXTENSION);
$name=pathinfo($path,PATHINFO_FILENAME);
if(file_exists($path))
{
echo "File alredy exists .So name is changed automatically & moved";
$path1="upload/";
$new_name=$path1.$name.rand(1,500).".".$ext;
move_uploaded_file($_FILES['file']['tmp_name'],$new_name);
}
else
{
echo"uploaded Sucessfully without any change";
move_uploaded_file($_FILES['file']['tmp_name'],$path);
}
?>