PHP - Write File - Unique Append
I append a string to a file by fwrite as
Code: [Select] $str= 'dynamic text from each run'; $myFile = "testFile.txt"; $fh = fopen($myFile, 'a') or die("can't open file"); $stringData = "$str\n"; fwrite($fh, $stringData); fclose($fh); but I want to avoid duplicate to keep the file small. I want to avoid writing if the term is already saved in the file. I want to have a file containing unique lines. Similar TutorialsHello there people. I'm looking for the easiest & most solid way to append 1 or 2 strings to a certain PDF file. I have an application which a logged-in user will be able to print. When he prints it, his name and a counter string must be appended in a blank space in the application. So I don't need to replace a string in a PDF or something, just append. The PDF file will always be the same: the application to be filled. I've heard somewhere that you can do it easily with the Zend framework. I've also heard for some other libraries like TCPDF & FPDF. Any suggestions? Thanks hi all i'm trying to make a quick and simple '.htaccess' installer and i'm using fopen/fwrite to do this but i'm getting an error: Quote Parse error: parse error in /var/www/test.php on line 12 here's the code: Code: [Select] <?PHP $File = ".htaccess"; $fh = fopen($File, 'a'); $Data = "\n#test write <IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE text/javascript application/javascript application/x-javascript text/x-js text/ecmascript application/ecmascript text/vbscript text/fluffscript AddOutputFilterByType DEFLATE image/svg+xml application/x-font-ttf application/x-font font/opentype font/otf font/ttf application/x-font-truetype application/x-font-opentype application/vnd.ms-fontobject application/vnd.oasis.opendocument.formula-template AddOutputFilterByType DEFLATE text/xml application/xml </IfModule> <IfModule mod_expires.c> <FilesMatch "\.(ico|gif|jpg|JPG|jpeg|png|PNG|swf|css|js|html?|xml|txt)$"> ExpiresActive On ExpiresDefault "access plus 1 month" </FilesMatch> </IfModule> #test write\n"; fwrite($fh, $Data); fclose($fh); ?> how do i include the code in the $Data string bit? Whats the easiest way to rename uploaded files to a unique name that would never be duplicated? Hi, I need some help in saving the filename along with the extension in the database after i upload the file. Current Scenario: I am able to upload the file successfully and save the form details in the database. Problems: When file uploaded with same file name it overwrites the old file. How do i give the file a unique name when uploading the file and then saving the form details along with the new file name given? CODE USED TO SAVE THE FILE TO MYSQL AND UPLOAD THE FILE: <?php //This is the directory where images will be saved $target = "image/"; $target = $target . basename( $_FILES['photo']['name']); //This gets all the other information from the form $name=$_POST['name']; $email=$_POST['email']; $phone=$_POST['phone']; $pic=($_FILES['photo']['name']); // Connects to your Database mysql_connect("localhost", "data_admin2", "data25") or die(mysql_error()) ; mysql_select_db("Resumebank") or die(mysql_error()) ; //Writes the photo to the server move_uploaded_file($_FILES['photo']['tmp_name'], $target); //Writes the information to the database mysql_query("INSERT INTO `employee` VALUES ('$name', '$email', '$phone', '$pic')") ; echo "The file has been uploaded, and your information has been added to the directory"; ?> What should I do? Please help! I'm having a problem with getting the timestamp to attach to the filename. Currently when it's uploaded in the database it says $timestamp in front of the filename instead of the time. Scroll down towards the bottom of the code to see it. Thanks for your help! $username = $_GET['username']; $item_id = $_GET['id']; define( 'DESIRED_IMAGE_WIDTH', 150 ); define( 'DESIRED_IMAGE_HEIGHT', 150 ); $source_path = $_FILES[ 'thumb' ][ 'tmp_name' ]; $timestamp = time(); // // Add file validation code here // list( $source_width, $source_height, $source_type ) = getimagesize( $source_path ); switch ( $source_type ) { case IMAGETYPE_GIF: $source_gdim = imagecreatefromgif( $source_path ); break; case IMAGETYPE_JPEG: $source_gdim = imagecreatefromjpeg( $source_path ); break; case IMAGETYPE_PNG: $source_gdim = imagecreatefrompng( $source_path ); break; } $source_aspect_ratio = $source_width / $source_height; $desired_aspect_ratio = DESIRED_IMAGE_WIDTH / DESIRED_IMAGE_HEIGHT; if ( $source_aspect_ratio > $desired_aspect_ratio ) { // // Triggered when source image is wider // $temp_height = DESIRED_IMAGE_HEIGHT; $temp_width = ( int ) ( DESIRED_IMAGE_HEIGHT * $source_aspect_ratio ); } else { // // Triggered otherwise (i.e. source image is similar or taller) // $temp_width = DESIRED_IMAGE_WIDTH; $temp_height = ( int ) ( DESIRED_IMAGE_WIDTH / $source_aspect_ratio ); } // // Resize the image into a temporary GD image // $temp_gdim = imagecreatetruecolor( $temp_width, $temp_height ); imagecopyresampled( $temp_gdim, $source_gdim, 0, 0, 0, 0, $temp_width, $temp_height, $source_width, $source_height ); // // Copy cropped region from temporary image into the desired GD image // $x0 = ( $temp_width - DESIRED_IMAGE_WIDTH ) / 2; $y0 = ( $temp_height - DESIRED_IMAGE_HEIGHT ) / 2; $desired_gdim = imagecreatetruecolor( DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT ); imagecopy( $desired_gdim, $temp_gdim, 0, 0, $x0, $y0, DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT ); // // Render the image // Alternatively, you can save the image in file-system or database // header( 'Content-type: image/jpeg' ); imagejpeg( $desired_gdim, "image_files/".'$timestamp'.$_FILES["thumb"]["name"] ); mysql_connect("localhost", "root", "", "") or die(mysql_error()); mysql_select_db("") or die(mysql_error()); $timestamp = time(); $item_image = '"$timestamp"'.$_FILES['thumb']['name']; $sql="UPDATE product SET thumb='$item_image' WHERE id = '$item_id'"; if (!mysql_query($sql)) { die('Error: ' . mysql_error()); I need some help...I want to read the contents of a file into a variable and then insert/write that content into another file. Code: [Select] $handle = fopen($create_mysql_db_url, "rb"); $contents = fread($handle, filesize($create_mysql_db_url)); fclose($handle); $userFileName = $_POST['mysqluser'] . time() . ".php.txt"; $fhandle = fopen($userFileName,"wb"); fwrite($fhandle, $contents); fclose($fhandle); $fh = fopen($userFileName,"wb"); $contents = fread($fh, filesize($userFileName)); $content = preg_replace("/###USERNAME###/", $_POST['mysqluser'], $contents); $content = preg_replace("/###PASSWORD###/", $_POST['mysqlpass'], $content); fwrite($fh, $content); fclose($fh); please help I have a mysql table which will store users email addresses (each is unique and is the primary field) and a timestamp. I have added another column called `'unique_code' (varchar(64), utf8_unicode_ci)`. What I would very much appreciate assistance with is; a) Generating a 5 digit alphanumeric code, ie: 5ABH6 b) Check all rows the 'unique_code' column to ensure it is unique, otherwise re-generate and check again c) Insert the uniquely generated 5 digit alphanumeric code into `'unique_code'` column, corresponding to the email address just entered. d) display the code on screen. What code must I put and where? **My current php is as follows:** Code: [Select] require "includes/connect.php"; $msg = ''; if($_POST['email']){ // Requested with AJAX: $ajax = ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'); try{ if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){ throw new Exception('Invalid Email!'); } $mysqli->query("INSERT INTO coming_soon_emails SET email='".$mysqli->real_escape_string($_POST['email'])."'"); if($mysqli->affected_rows != 1){ throw new Exception('You are already on the notification list.'); } if($ajax){ die('{"status":1}'); } $msg = "Thank you!"; } catch (Exception $e){ if($ajax){ die(json_encode(array('error'=>$e->getMessage()))); } $msg = $e->getMessage(); } } eg http://www.xxxxxxx.com/index.php?action=viewarti&artid=5 How can I write the content of this link into file. I produce a series of php variables in a php strict (mostly come from mysql), and I want to save them as a php file. To be use for "include". What is the safest way to write them in a php file? I tried to save them in the manner of saving a text file with fwrite as Code: [Select] $data='<?php $cat=array('array created in the text'); $string='some value';?>'; $fh = fopen("file.php", 'w'); fwrite($fh, $data); Now, file.php is a normal php file and I can call it with "include"; but the problem is that this method is not safe. For example, if the string is "There's something", php gives error for the presence of ' in the string. I can skip ' and " by backslash; but this method is costy, as I need to perform this process for all strings to be saved. Moreover, there might be other source of errors too (that I have not encountered yet). Is there a safe way for writing a php code to file? <?php $a = 2; $b = 3; $z = fopen("test.txt", 'a+'); if($a > $b) { echo "A is bigger than B"; } elseif fwrite($z, $b); fclose($z); ?> is there a way to get elseif to write to a file? so if b is bigger than a it writes $b to a file? Got a little stuck here. I'm trying to format an existing .txt file, format it and then write it to .sql file. Here's my code: Code: [Select] $handle = @fopen("nations.txt", "r"); if ($handle) { while (($buffer = fgets($handle, 1024)) !== false) { $column = explode("|",$buffer); // format file $myFile = "nation_dump_".date("Y-m-d").".sql"; // create file $fh = fopen($myFile, 'w') or die("can't open file"); foreach($column as $col) { fwrite($fh, $col[0]); //write the first broken segment from explode() to file } fclose($fh); } if (!feof($handle)) { echo "Error: unexpected fgets() fail\n"; } fclose($handle); } The error is on this line, within the foreach loop. fwrite($fh, $col[0]); When I removed the index it only wrote the last line to the file, but I want it to loop through all the lines.. What am I doing wrong here? Why doesn't it add a new line when I open up index.php Code: [Select] $fp = fopen('text.txt','w'); fwrite($fp, "Your IP: ".$_SERVER['REMOTE_ADDR']."\n"); fclose($fp); Is there a way to write a file to a directory on my network? I tried creating a shortcut called automated and pointed it to the network path. I also set up a virtual directory called automated in IIS and still could not make it work. I gave it read and write permissions. error Warning: fopen(C:\Inetpub\wwwroot\dompdf\automated\resource.pdf) [function.fopen]: failed to open stream: No such file or directory in C:\Inetpub\wwwroot\date.php on line 69 Warning: fwrite() expects parameter 1 to be resource, boolean given in C:\Inetpub\wwwroot\date.php on line 70 Warning: fclose() expects parameter 1 to be resource, boolean given in C:\Inetpub\wwwroot\date.php on line 71 code Code: [Select] require_once("dompdf/dompdf_config.inc.php"); $html = '<html><body>'. '<p>Put your html here, or generate it with your favourite '. 'templating system.</p>'. '</body></html>'; $dompdf = new DOMPDF(); $dompdf->load_html($html); $dompdf->render(); $pdfoutput = $dompdf->output(); $filename = "C:\\Inetpub\\wwwroot\\dompdf\\automated\\resource.pdf"; $fp = fopen($filename, "a"); fwrite($fp, $pdfoutput); fclose($fp); Hi All, I am presently using a Debian VPS to which, if I need, I can add another disk. In my website, users can upload images, that are then stored in the primary disk into a child directory of a directory called httpdocs. Instead of the primary disk, would it be possible to have them stored in a secondary disk ? I am asking this because I am not sure that a user connected to my website is allowed to run a PHP script intended to write a file in a directory that actually does not belong to the httpdocs directory. Thanks Hi, I want to read image file and write in to word document file using php. Actually i am developing shopping cart site. for that i have created barcode image. i need to take print outs. for example if i click print means same barcode should be generate 64 times in word document. how i do it? i have tried with COM. please check the following code <?php // starting word $word = new COM("word.application") or die("Unable to instantiate Word"); echo "Loaded Word, version {$word->Version}\n"; //bring it to front $word->Visible = 1; //open an empty document $word->Documents->Add(); //do some weird stuff for($i=1;$i<=64;$i++) { $word->Selection->InlineShapes->AddPicture("D:\Program Files\wamp\www\b.jpg ",false, True); } $word->Documents[1]->SaveAs("D:\Program Files\wamp\www\Uselesstest.doc"); //closing word $word->Quit(); //free the object $word = null; ?> It works fine in local. but it is not working in server (it says COM.class is missing). i have checked some forums they said it works with MS based operation system. i have checked with windows only. Please kindly any one help me asap the way for read and write image file in word document. can we do this any other way? we are reading and writing txt files using php the same can we do with image file (read and write in word document) ?? Thanks Prema I'm trying to include a routine to catch an error but it doesn't seem to write to a text file within a function. just using the following simple code, even if I simply try to write a letter it doesn't work
if ($http_status == 200) { return $response; } else { $myfile = fopen("ErrorData.txt", "a+") or die("Unable to open file!"); $txt = date("H:i:sa d-m-Y")." / Error data- / ".json_encode($response)."\r\n"; fwrite($myfile, $txt); fclose($myfile); }
Edited September 13, 2019 by Dvae56 Added code Just trying to create a simple form that will let you enter a message that will get written to a text file. Code for SetMessage.php: Code: [Select] <?php if($_SERVER['REQUEST_METHOD'] != 'POST') { ?> <form method="POST" action="setmessage.php" name="setmessage"> <p>Message to Display:<Input type="text" name="message" size="50"></p> <p><input type="submit" value="Submit" name="submit"></p> </form> <?php } else { //Writes the contents of the message to a file echo file_put_contents('message.txt', $_POST['message']); } ?> When submitting, I get the error "Call to undefined function: file_put_contents() on line 16" Hey there, Thanks for taking the time to read my thread, well basically I'm in a bit of a dilemma. I've got a string in PHP containing the contents of a file I would like to be created and I have a method of sending the command to the remote server like so: $Connection->exec('ps aux'); Now my issue is I am unaware of any file editors via command like that don't have some sort of user prompt I've scoured Google for hours searching for the best possible method for this but all the file editors aren't simply processed by one line commands and edited in that same command e.g Create File -> Write File -> Close File Is there no possible means of doing that via one line command?. Here is my string I wish to be written to the file. $RestartFile = "#!/bin/bash export SERVER_PATH=/home/client".$Server['server_owner']."/".$Server['server_id']." cd $SERVER_PATH while [ true ]; do ./server".$Server['server_id']." & done"); Thank you for your time. I am trying to write post variables to a csv file but it writes everything in one line separated by comma <?php $list= array($_POST['purchases']); $file = fopen("purchases.csv", "w"); foreach ($list as $line) { fputcsv($file, $line); } fclose($file); ?> Result in purchases.csv file Marilyn,Nancy,Johan,Carol,Juanic,Shirley But I want every string value on separated line Marilyn Nancy Johan Carol Juanic Shirley
Hello Everyone, I'm new to PHP and got a good big stuff. I would like to write an image in excel file. There will be almost 600+ rows and each row will have url and qrcode image. I would like to write an excel file which will write url and respective image into the next cell of the url. Is it possible to write an image in excel file? If yes, can anyone please guide me how? I have read so many post saying to use a pear package but again pear package is not allowing to write jpe/gif it only allows .bmp files. So, pear package is I don't think will work for me. I have also attached an example excel file which is showing the way I require to have an output. Please anyone if having any idea guide me and let me know. Thank you in advance for your help. Looking forward to hear from you soon! |