Search Results

Search found 616 results on 25 pages for 'fopen'.

Page 22/25 | < Previous Page | 18 19 20 21 22 23 24 25  | Next Page >

  • PHP: Remove Simple Session with Get-Method

    - by elmaso
    Hello, I want to Remove the Sessions from this php code, actually if someone searches i get this url search.php?searchquery=test but if I reload the page, the results are cleaned. how can I remove the Sessions to get the Results still, if someone reloads the page? this are the codes: search.php <?php session_start(); ?> <form method="get" action="querygoogle.php"> <label for="searchquery"><span class="caption">Search this site</span> <input type="text" size="20" maxlength="255" title="Enter your keywords and click the search button" name="searchquery" /></label> <input type="submit" value="Search" /> </form> <?php if(!empty($_SESSION['googleresults'])) { echo $_SESSION['googleresults']; unset($_SESSION['googleresults']); } ?> querygoogle.php <?php session_start(); $url = 'http://www.example.com'; $handle = fopen($url, 'rb'); $body = ''; while (!feof($handle)) { $body .= fread($handle, 8192); } fclose($handle); $json = json_decode($body); foreach($json->responseData->results as $searchresult) { if($searchresult->GsearchResultClass == 'GwebSearch') { $formattedresults .= ' <div class="searchresult"> <h3><a href="' . $searchresult->unescapedUrl . '">' . $searchresult->titleNoFormatting . '</a></h3> <p class="resultdesc">' . $searchresult->content . '</p> <p class="resulturl">' . $searchresult->visibleUrl . '</p> </div>'; } } $_SESSION['googleresults'] = $formattedresults; header("Location: search.php?searchquery=" . $_GET['searchquery']); exit; ?> thank you for your help!!

    Read the article

  • CSV File Content Display Issue

    - by Pankaj Khurana
    Hi, I want to retrieve contents from a csv file for that i am using following code: <?php $fo = fopen("record.csv", "rb+"); while(!feof($fo)) { $contents[] = fgetcsv($fo,0,';'); } print_r($contents); fclose($fo); ?> But my records are displayed in the following format: ????††???????†††??†††††????"Search Transactions Results" ††††??†???????††††?††††††??? ???????????? ?????????????? ?????????? My csv file format: "Search Transactions Results" "Transaction ID","Reference Transaction ID","Date","Type","Subject","Item Number","Item Name","Invoice ID","Name","Email","Shipping Name","Shipping Address Line 1","Shipping Address Line 2","Shipping Address City","Shipping State/Province","Shipping Zip/Postal Code","Shipping Address Country","Shipping Method","Address Status","Contact Phone Number","Gross Amount","Receipt ID","Custom Field","Option 1 Name","Option 1 Value","Option 2 Name","Option 2 Value","Note","Auction Site","Auction User ID","Item URL","Auction Closing Date","Insurance Amount","Currency","Fees","Net Amount","Shipping & Handling Amount","Sales Tax Amount","To Email","Time","Time Zone" "1T","",5/5/2010 2:10:44 PM,"Payment Processed","CFP Self Study Kit","1","CFP Self Study Kit","","User1","[email protected]","","","","","","","","","N","","68.18","R1","","","","","","","","","",,"","USD","-2.62","65.56","0","0","[email protected]","01:40","Asia/Calcutta" "2T","",5/19/2010 4:04:08 PM,"Payment Processed","CFP Self Study Kit","1","CFP Self Study Kit","","User2","[email protected]","","","","","","","","","N","","68.18","R2","","","","","","","","","",,"","USD","-2.62","65.56","0","0","[email protected]","03:34","Asia/Calcutta" "3T","1RT",5/19/2010 5:28:45 PM,"Currency Conversion Completed","","","",""," ","","","","","","","","","","N","","17492.6","","","","","","","","","","",,"","INR","0","17492.6","0","0","","04:58","Asia/Calcutta" "4T","2RT",5/19/2010 5:28:45 PM,"Currency Conversion Completed","","","",""," ","","","","","","","","","","N","","-393.36","","","","","","","","","","",,"","USD","0","-393.36","0","0","","04:58","Asia/Calcutta" "5T","",5/19/2010 5:28:45 PM,"Transfer to Bank Initiated","P1006","","P1006",""," ","","","","","","","","","","N","","-17492.6","","","","","","","","","","",,"","INR","0","-17492.6","0","0","","04:58","Asia/Calcutta" "6T","",5/20/2010 5:38:02 PM,"Transfer to Bank Completed","P1006","","P1006",""," ","","","","","","","","","","N","","-17492.6","","","","","","","","","","",,"","INR","0","-17492.6","0","0","","05:08","Asia/Calcutta" "7T","",5/21/2010 12:32:37 PM,"Payment Processed","FP - LVC Plus","","FP - LVC Plus","","User3","[email protected]","User3","NEW DELHI","BEHIND KARNATAKA BANK LD","SOUTH","NEW DELHI","110023","IN","","N","","283.96","","","","","","","","","","",,"","USD","-9.95","274.01","0","0","[email protected]","00:02","Asia/Calcutta" "8T","",5/25/2010 4:40:48 PM,"Transfer to Bank Initiated","P1006","","P1006",""," ","","","","","","","","","","N","","-12569.85","","","","","","","","","","",,"","INR","0","-12569.85","0","0","","04:10","Asia/Calcutta" "9T","3RT",5/25/2010 4:40:48 PM,"Currency Conversion Completed","","","",""," ","","","","","","","","","","N","","-274.01","","","","","","","","","","",,"","USD","0","-274.01","0","0","","04:10","Asia/Calcutta" "10T","4RT",5/25/2010 4:40:48 PM,"Currency Conversion Completed","","","",""," ","","","","","","","","","","N","","12569.85","","","","","","","","","","",,"","INR","0","12569.85","0","0","","04:10","Asia/Calcutta" "11T","",5/26/2010 4:57:39 PM,"Transfer to Bank Completed","P1006","","P1006",""," ","","","","","","","","","","N","","-12569.85","","","","","","","","","","",,"","INR","0","-12569.85","0","0","","04:27","Asia/Calcutta" "Total","-247.05 USD","-15.19","-262.24" "Total","0.00 INR","0.00","0.00" I want to retrieve the records where "Type"="Payment Processed". I want to retrieve content in a key value format that is for e.g. Transaction ID-1T as i have to store this values in a database but display is not proper. I am unable to find out the reason for the same please help me on this. Thanks

    Read the article

  • passing pipe to threads

    - by alaamh
    I see it's easy to open pipe between two process using fork, but how we can passing open pipe to threads. Assume we need to pass out of PROGRAM A to PROGRAM B "may by more than one thread", PROGRAM B send his output to PROGRAM C #include <stdio.h> #include <stdlib.h> #include <pthread.h> struct targ_s { int fd_reader; }; void *thread1(void *arg) { struct targ_s *targ = (struct targ_s*) arg; int status, fd[2]; pid_t pid; pipe(fd); pid = fork(); if (pid == 0) { dup2(STDIN_FILENO, targ->fd_reader); close(fd[0]); dup2(fd[1], STDOUT_FILENO); close(fd[1]); execvp ("PROGRAM B", NULL); exit(1); } else { close(fd[1]); dup2(fd[0], STDIN_FILENO); close(fd[0]); execl("PROGRAM C", NULL); wait(&status); return NULL; } } int main(void) { FILE *fpipe; char *command = "PROGRAM A"; char buffer[1024]; if (!(fpipe = (FILE*) popen(command, "r"))) { perror("Problems with pipe"); exit(1); } char* outfile = "out.dat"; FILE* f = fopen (outfile, "wb"); int fd = fileno( f ); struct targ_s targ; targ.fd_reader = fd; pthread_t thid; if (pthread_create(&thid, NULL, thread1, &targ) != 0) { perror("pthread_create() error"); exit(1); } int len; while (read(fpipe, buffer, sizeof (buffer)) != 0) { len = strlen(buffer); write(fd, buffer, len); } pclose(fpipe); return (0); }

    Read the article

  • Cannot work for 2nd iteration because of writing delay.

    - by karikari
    My code's IF-THEN does not work for 2nd iteration. This is due to, the jar processing take some time to write it result inside the output.txt. Since the writing is a bit late, my code's 2nd iteration will always read the previous written value inside the output.txt in order to pass it to the IF-THEN. For example, in 1st iteration: output.txt -- 0.9888 twrite.txt -- msg: ok 2nd iteration: output.txt -- 0.5555 twrite.txt -- msg: ok //the IF-THEN still gives this result which is based on previous iteration. it should be msg: not ok . since it is < 0.7 I need help, how to solve this 'delay' problem? HRESULT CButtonDemoBHO::onDocumentComplete(IDispatch *pDisp, VARIANT *vUrl){ ATLTRACE("CButtonDemoBHO::onDocumentComplete %S\n", vUrl->bstrVal); WinHttpClient client(vUrl->bstrVal); client.SendHttpRequest(); wstring httpResponseHeader = client.GetHttpResponseHeader(); wstring httpResponse = client.GetHttpResponse(); writeToLog(httpResponse.c_str()); if (isMainFrame(pDisp)){ m_normalPageLoad=false; FILE *child = _popen("javaw -jar c:\\simmetrics.jar c:\\chtml.txt c:\\thtml.txt > c:\\output.txt", "r"); fclose(child); char readnumber[10]; float f = 0; FILE *file11 = fopen("c:\\output.txt","r"); char* p = fgets(readnumber,10,file11); std::istringstream iss(p); iss >> f; if (f > 0.7) { wfstream file12 ("c:\\twrite.txt", ios_base::out); file12 << "Msg: ok"; file12.close(); } else { wfstream file12 ("c:\\twrite.txt", ios_base::out); file12 << "Msg: not ok"; file12.close(); } iss.clear(); fclose(file11); return S_OK; } return S_OK; }

    Read the article

  • zlib gzgets extremely slow?

    - by monkeyking
    I'm doing stuff related to parsing huge globs of textfiles, and was testing what input method to use. There is not much of a difference using c++ std::ifstreams vs c FILE, According to the documentation of zlib, it supports uncompressed files, and will read the file without decompression. I'm seeing a difference from 12 seconds using non zlib to more than 4 minutes using zlib.h This I've tested doing multiple runs, so its not a disk cache issue. Am I using zlib in some wrong way? thanks #include <zlib.h> #include <cstdio> #include <cstdlib> #include <fstream> #define LENS 1000000 size_t fg(const char *fname){ fprintf(stderr,"\t-> using fgets\n"); FILE *fp =fopen(fname,"r"); size_t nLines =0; char *buffer = new char[LENS]; while(NULL!=fgets(buffer,LENS,fp)) nLines++; fprintf(stderr,"%lu\n",nLines); return nLines; } size_t is(const char *fname){ fprintf(stderr,"\t-> using ifstream\n"); std::ifstream is(fname,std::ios::in); size_t nLines =0; char *buffer = new char[LENS]; while(is. getline(buffer,LENS)) nLines++; fprintf(stderr,"%lu\n",nLines); return nLines; } size_t iz(const char *fname){ fprintf(stderr,"\t-> using zlib\n"); gzFile fp =gzopen(fname,"r"); size_t nLines =0; char *buffer = new char[LENS]; while(0!=gzgets(fp,buffer,LENS)) nLines++; fprintf(stderr,"%lu\n",nLines); return nLines; } int main(int argc,char**argv){ if(atoi(argv[2])==0) fg(argv[1]); if(atoi(argv[2])==1) is(argv[1]); if(atoi(argv[2])==2) iz(argv[1]); }

    Read the article

  • mysql: can't set max_allowed_package to anything grater than 16MB

    - by sas
    I'm not sure if this is the right place to post these kind of questions, if it's not so, please (politely) let me know... :-) I need to save files greater than 16MB on a mysql database from a php site... I've already changed the c:\xampp\mysql\bin\my.cnf and set max_allowed_packet to 16 MB, and everything worked fine then I set it to 32 MB but there´s no way I can handle a file bigger than 16 MB I get the following error: 'MySQL server has gone away' (the same error I had when max_allowed_packet was set to 1MB) there must be some other setting that doesn´t allow me to handle files bigger than 16MB maybe the php client, I guess, but I don't know where to edit it this is the code I'm running when file.txt is smaller than 16.776.192 bytes long, it works fine, but if file.txt has 16.777.216 bytes i get the aforementioned error oh, and the field download.content is a longblob... $file = 'file.txt'; $file_handle = fopen( $file, 'r' ); $content = fread( $file_handle, filesize( $file ) ); fclose( $file_handle ); db_execute( 'truncate table download', true ); $sql = "insert into download( code, title, name, description, original_name, mime_type, size, content, user_insert_id, date_insert, user_update_id, date_update ) values ( 'new file', 'new file', 'sas.jpg', 'new file', '$file', 'mime', " . filesize( $file ) . ", '" . addslashes( $content ) . "', 0, " . db_char_to_sql( now_char(), 'datetime' ) . ", 0, " . db_char_to_sql( now_char(), 'datetime' ) . " )"; db_execute( $sql, true ); (the db_execute funcion just opens the connections and executes the sql stuff) running on windows XP sp2 server version: 5.0.67-community PHP Version 4.4.9 mysql client API version: 3.23.49 using: ApacheFriends XAMPP (Basispaket) version 1.6.8 that comes with + Apache 2.2.9 + MySQL 5.0.67 (Community Server) + PHP 5.2.6 + PHP 4.4.9 + PEAR + phpMyAdmin 2.11.9.2 ... this is part of the content of c:\xampp\mysql\bin\my.cnf # The MySQL server [mysqld] port= 3306 socket= "C:/xampp/mysql/mysql.sock" basedir="C:/xampp/mysql" tmpdir="C:/xampp/tmp" datadir="C:/xampp/mysql/data" skip-locking key_buffer = 16M # max_allowed_packet = 1M max_allowed_packet = 32M table_cache = 128 sort_buffer_size = 512K net_buffer_length = 8K read_buffer_size = 256K read_rnd_buffer_size = 512K myisam_sort_buffer_size = 8M

    Read the article

  • OpenGL Shader Compile Error

    - by Tomas Cokis
    I'm having a bit of a problem with my code for compiling shaders, namely they both register as failed compiles and no log is received. This is the shader compiling code: /* Make the shader */ Uint size; GLchar* file; loadFileRaw(filePath, file, &size); const char * pFile = file; const GLint pSize = size; newCashe.shader = glCreateShader(shaderType); glShaderSource(newCashe.shader, 1, &pFile, &pSize); glCompileShader(newCashe.shader); GLint shaderCompiled; glGetShaderiv(newCashe.shader, GL_COMPILE_STATUS, &shaderCompiled); if(shaderCompiled == GL_FALSE) { ReportFiler->makeReport("ShaderCasher.cpp", "loadShader()", "Shader did not compile", "The shader " + filePath + " failed to compile, reporting the error - " + OpenGLServices::getShaderLog(newCashe.shader)); } And these are the support functions: bool loadFileRaw(string fileName, char* data, Uint* size) { if (fileName != "") { FILE *file = fopen(fileName.c_str(), "rt"); if (file != NULL) { fseek(file, 0, SEEK_END); *size = ftell(file); rewind(file); if (*size > 0) { data = (char*)malloc(sizeof(char) * (*size + 1)); *size = fread(data, sizeof(char), *size, file); data[*size] = '\0'; } fclose(file); } } return data; } string OpenGLServices::getShaderLog(GLuint obj) { int infologLength = 0; int charsWritten = 0; char *infoLog; glGetShaderiv(obj, GL_INFO_LOG_LENGTH,&infologLength); if (infologLength > 0) { infoLog = (char *)malloc(infologLength); glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog); string log = infoLog; free(infoLog); return log; } return "<Blank Log>"; } and the shaders I'm loading: void main(void) { gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); } void main(void) { gl_Position = ftransform(); } In short I get From: ShaderCasher.cpp, In: loadShader(), Subject: Shader did not compile Message: The shader Data/Shaders/Standard/standard.vs failed to compile, reporting the error - <Blank Log> for every shader I compile I've tried replacing the file reading with just a hard coded string but I get the same error so there must be something wrong with how I'm compiling them. I have run and compiled example programs with shaders, so I doubt my drivers are the issue, but in any case I'm on a Nvidia 8600m GT. Can anyone help?

    Read the article

  • Downloading large file with php

    - by Alessandro
    Hi, I have to write a php script to download potentially large files. The file I'm reporting here works fine most of the times. However, if the client's connection is slow the request ends (with status code 200) in the middle of the downloading, but not always at the very same point, and not at the very same time. I tried to overwrite some php.ini variables (see the first statements) but the problem remains. I don't know if it's relevant but my hosting server is SiteGround, and for simple static file requests, the download works fine also with slow connections. I've found Forced downloading large file with php but I didn't understand mario's answer. I'm new to web programming. So here's my code. <?php ini_set('memory_limit','16M'); ini_set('post_max_size', '30M'); set_time_limit(0); include ('../private/database_connection.php'); $downloadFolder = '../download/'; $fileName = $_POST['file']; $filePath = $downloadFolder . $fileName; if($fileName == NULL) { exit; } ob_start(); session_start(); if(!isset($_SESSION['Username'])) { // or redirect to login (remembering this download request) $_SESSION['previousPage'] = 'download.php?file=' . $fileName; header("Location: login.php"); exit; } if (file_exists($filePath)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); //header('Content-Disposition: attachment; filename='.$fileName); header("Content-Disposition: attachment; filename=\"$fileName\""); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); //header('Pragma: public'); header('Content-Length: ' . filesize($filePath)); ob_clean(); flush(); // download // 1 // readfile($filePath); // 2 $file = @fopen($filePath,"rb"); if ($file) { while(!feof($file)) { print(fread($file, 1024*8)); flush(); if (connection_status()!=0) { @fclose($file); die(); } } @fclose($file); } exit; } else { header('HTTP/1.1 404 File not found'); exit; } ?>

    Read the article

  • Parsing CSV File to MySQL DB in PHP

    - by Austin
    I have a some 350-lined CSV File with all sorts of vendors that fall into Clothes, Tools, Entertainment, etc.. categories. Using the following code I have been able to print out my CSV File. <?php $fp = fopen('promo_catalog_expanded.csv', 'r'); echo '<tr><td>'; echo implode('</td><td>', fgetcsv($fp, 4096, ',')); echo '</td></tr>'; while(!feof($fp)) { list($cat, $var, $name, $var2, $web, $var3, $phone,$var4, $kw,$var5, $desc) = fgetcsv($fp, 4096); echo '<tr><td>'; echo $cat. '</td><td>' . $name . '</td><td><a href="http://www.' . $web .'" target="_blank">' .$web.'</a></td><td>'.$phone.'</td><td>'.$kw.'</td><td>'.$desc.'</td>' ; echo '</td></tr>'; } fclose($file_handle); show_source(__FILE__); ?> First thing you will probably notice is the extraneous vars within the list(). this is because of how the excel spreadsheet/csv file: Category,,Company Name,,Website,,Phone,,Keywords,,Description ,,,,,,,,,, Clothes,,4imprint,,4imprint.com,,877-466-7746,,"polos, jackets, coats, workwear, sweatshirts, hoodies, long sleeve, pullovers, t-shirts, tees, tshirts,",,An embroidery and apparel company based in Wisconsin. ,,Apollo Embroidery,,apolloemb.com,,1-800-982-2146,,"hats, caps, headwear, bags, totes, backpacks, blankets, embroidery",,An embroidery sales company based in California. One thing to note is that the last line starts with two commas as it is also listed within "Clothes" category. My concern is that I am going about the CSV output wrong. Should I be using a foreach loop instead of this list way? Should I first get rid of any unnecessary blank columns? Please advise any flaws you may find, improvements I can use so I can be ready to import this data to a MySQL DB.

    Read the article

  • CSS Graph- Bars not showing correctly

    - by Olivia
    I'm trying to create a CSS/HTML based graph using this tutorial here. However instead of putting the data directly into the html code I'm importing it from a CSV file using PHP with the following code. <?PHP /* Open CSV file */ $handle = fopen("defects.csv", "r"); $c = 0; /* gets data from csv file */ while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { /* stores dates as variable $date */ $date[$c] = $data[0]; $c++; /* inserts defect data into html code */ echo "<dd class=\"p" . $data[2] . "\"><span><b>" . $data[2] . "</b></span></dd>"; echo "<dd class=\"sub p" . $data[3] . "\" ><span><b>" . $data[3] . "</b></span></dd>"; } echo "</dl>"; echo "<ul class=\"xAxis\">"; /* X AXIS */ /* inserts date data into html code for x axis */ for ($d=0; $d < $c; $d++) { echo "<li>" . $date[$d] . "</li>"; } ?> The values are being placed correctly on the chart, but the bars aren't appearing. The CSS code I have for the bars is: /* default column styling */ dl#csschart span{ height:50%; background:url(../images/barx.png) repeat-y; } dl#csschart .sub{ margin-left:-33px; } dl#csschart .sub span{ background:url(../images/subBarx.png) repeat-y; } Just in case it helps, I've print screened how the graph should look. You can see it at: http://allured.info/graph/failgraph.png

    Read the article

  • Duplicate Blob field with foreach

    - by JGSilva
    I have some fields (blob) where I have uploaded some images. The images display correctly and I can open it without problem in Photoshop for example. I created a button where user can duplicate the product and everything works fine, but when it comes to duplicate the image entry I got some errors, like 1064 and others ones that I can't remember cause I am working 3 days inside this. Because de original product have 3 or more images I select then and gave an foreach. What I notice when a print de blob is that in the end it eats the next array, like if don't have an end. In other words, the next item got inside that utf-8 character in the print. That gave me some clue. The next approach was to save it in somewhere, and reupload it. The problem is that only the first one works. When I download the image saved, it opens normally so, it is not a saving in disk problem. When I gave a print in the $result, the same happens, is like the image is hungry and ate the next one. Here is the code. Notice = I created the [$count] to see if was not an rewrite in array error. Even tried to , in beging of the foreach, kind of clean the vars… $count=0; foreach ($original_image as $key => $val) { $count++; //$arquivo = ''; //$image = ''; //$file = ''; //$this->image = ''; //$return = ''; $arquivo[$count] = $val['pi_id'].'.'.$val['pi_type']; $image[$count] = $caminho_url.$arquivo[$count]; if (file_exists($image[$count])) { $this->image = Image::factory($image[$count]); $this->image->save($image[$count]); $file[$count]=mysql_real_escape_string(addslashes(fread(fopen($image[$count], "r"), filesize($image[$count])))); $return[$count] = Product::add_image($id_prod, $file[$count], $val['pi_type'],$val['pi_main']); }else { die('no'); } }

    Read the article

  • Thread feeding other MultiThreading

    - by alaamh
    I see it's easy to open pipe between two process using fork, but how we can passing open pipe to threads. Assume we need to pass out of PROGRAM A to PROGRAM B "may by more than one thread", PROGRAM B send his output to PROGRAM C #include <stdio.h> #include <stdlib.h> #include <pthread.h> struct targ_s { char* reader; }; void *thread1(void *arg) { struct targ_s *targ = (struct targ_s*) arg; int status, fd[2]; pid_t pid; pipe(fd); pid = fork(); if (pid == 0) { int fd = fileno( targ->fd_reader ); dup2(STDIN_FILENO, fd); close(fd[0]); dup2(fd[1], STDOUT_FILENO); close(fd[1]); execvp ("PROGRAM B", NULL); exit(1); } else { close(fd[1]); dup2(fd[0], STDIN_FILENO); close(fd[0]); execl("PROGRAM C", NULL); wait(&status); return NULL; } } int main(void) { FILE *fpipe; char *command = "PROGRAM A"; char buffer[1024]; if (!(fpipe = (FILE*) popen(command, "r"))) { perror("Problems with pipe"); exit(1); } char* outfile = "out.dat"; FILE* f = fopen (outfile, "wb"); int fd = fileno( f ); struct targ_s targ; targ.fd_reader = outfile; pthread_t thid; if (pthread_create(&thid, NULL, thread1, &targ) != 0) { perror("pthread_create() error"); exit(1); } int len; while (read(fpipe, buffer, sizeof (buffer)) != 0) { len = strlen(buffer); write(fd, buffer, len); } pclose(fpipe); return (0); }

    Read the article

  • C Array of string

    - by Meko
    HI. This is maybe simple question but I want to create two dimensional array and add it string like in java string str = "text" ; string [][] array = new [][] string ; array[i][j] = str ; But in C there is no string .I tried like this but here strcpy() gives error.It returns to assembly code. I am trying to read line by line from text and split line by space and add them to structure.But first I think that I must add each line and row in array and then making iteration and adding to structures fields. static const char filename[] = "student.txt"; FILE *file = fopen ( filename, "r" ); char line [ 128 ]; /* or other suitable maximum line size */ char delims [ ]=" "; char *result =NULL; char list[15]; char arra[128][128]; int i=0; int j=0; struct { char gruppa[10]; char familiya[20]; int uchaste; struct { int firsth; int second; int third; int fourht; int fifth; } exam; }student; for(i=0; i<128; i++) for(j=0; j<128; j++) arra[i][j] = '\0'; for(i=0; i<15; i++) list[i] = '\0'; if ( file != NULL ) { while ( fgets ( line, sizeof line, file ) != NULL ) { result = strtok(line,delims); while (result !=NULL) { strcpy(list,("%s",result)); strcpy(arra[i][j],list); // Here it gives errror j++; result = strtok(NULL,delims); } j=0; i++; } fclose ( file ); } else { perror ( filename ); } getchar(); return 0; }

    Read the article

  • PHP readdir(): 3 is not a valid Directory resource

    - by Jordan
    <?php function convert(){ //enable error reporting for debugging error_reporting(E_ALL | E_STRICT); //convert pdf's to html using payroll.sh script and //pdftohtml command line tool $program = "payroll.sh"; $toexec="sh /var/www/html/tmp/" . $program . " 2>&1"; $exec=shell_exec($toexec); //display message from payroll.sh //echo $exec; //echo ('<br/>'); } function process(){ $dir = '/var/www/html/tmp/converted'; //echo ('one'); if (is_dir($dir)) { //echo ('two'); if ($dh = opendir($dir)) { //echo ('three'); while (($file = readdir($dh)) !== false) { //echo ('four'); if ($file != "." && $file != ".."){ echo 'opening file: '; echo $file; echo ("<br/>"); $fp = fopen('/var/www/html/tmp/converted/' . $file, 'r+'); $count = 0; //while file is not at the EOF marker while (!feof($fp)) { $line = fgets($fp); if($count==21) { $employeeID = substr($line,71,4); echo 'employee ID: '; echo $employeeID; echo ('<br/>'); //echo ('six'); $count++; } else if($count==30) { $employeeDate = substr($line,71,10); echo 'employee Date: '; echo $employeeDate; echo ('<br/>'); //echo ('seven'); $count++; } else { //echo ('eight'); //echo ('<br/>'); $count++; } } fclose($fp); closedir($dh); } } } } } convert(); process(); ?> I am setting up a php script that will take a paystub in pdf format, convert it to html, then import it into Drupal after getting the date and employee ID. The code only seems to process the first file in the directory then it gives me this: opening file: dd00000112_28_2010142011-1.html employee ID: 9871 employee Date: 12/31/2010 Warning: readdir(): 3 is not a valid Directory resource in /var/www/html/pay.mistequaygroup.com/payroll.php on line 29 The '3' in the error really confuses me, and google is not helping much. Could it be the 3rd iteration of the loop? The only files in the directory reddir() is scanning are the .html files waiting to be processed. Any ideas? Also, how does my code look? I'm fairly new to doing any real programming and I don't get too much input around work.

    Read the article

  • Attach file to mail using php

    - by ktsixit
    Hi all, I've created a form which contains an upload field file and some other text fields. I'm using php to send the form's data via email and attach the file. This is the code I'm using but it's not working properly. The file is normally attached to the message but the rest of the data is not sent. $body="bla bla bla"; $attachment = $_FILES['cv']['tmp_name']; $attachment_name = $_FILES['cv']['name']; if (is_uploaded_file($attachment)) { $fp = fopen($attachment, "rb"); $data = fread($fp, filesize($attachment)); $data = chunk_split(base64_encode($data)); fclose($fp); } $headers = "From: $email<$email>\n"; $headers .= "Reply-To: <$email>\n"; $headers .= "MIME-Version: 1.0\n"; $headers .= "Content-Type: multipart/related; type=\"multipart/alternative\"; boundary=\"----=MIME_BOUNDRY_main_message\"\n"; $headers .= "X-Sender: $first_name $family_name<$email>\n"; $headers .= "X-Mailer: PHP4\n"; $headers .= "X-Priority: 3\n"; $headers .= "Return-Path: <$email>\n"; $headers .= "This is a multi-part message in MIME format.\n"; $headers .= "------=MIME_BOUNDRY_main_message \n"; $headers .= "Content-Type: multipart/alternative; boundary=\"----=MIME_BOUNDRY_message_parts\"\n"; $message = "------=MIME_BOUNDRY_message_parts\n"; $message .= "Content-Type: text/html; charset=\"utf-8\"\n"; $message .= "Content-Transfer-Encoding: quoted-printable\n"; $message .= "\n"; $message .= "$body\n"; $message .= "\n"; $message .= "------=MIME_BOUNDRY_message_parts--\n"; $message .= "\n"; $message .= "------=MIME_BOUNDRY_main_message\n"; $message .= "Content-Type: application/octet-stream;\n\tname=\"" . $attachment_name . "\"\n"; $message .= "Content-Transfer-Encoding: base64\n"; $message .= "Content-Disposition: attachment;\n\tfilename=\"" . $attachment_name . "\"\n\n"; $message .= $data; //The base64 encoded message $message .= "\n"; $message .= "------=MIME_BOUNDRY_main_message--\n"; $subject = 'bla bla bla'; $to="[email protected]"; mail($to,$subject,$message,$headers); Why isn't the $body data not sent? Can you help me fix it?

    Read the article

  • How to replace invalid characters in XML using Javascript or PhP

    - by Raind
    Hi, Need help here for the following: Running PhP, javascript, MySQL, XML. 1) Retrieving file from MySQL and stored it onto XML file. 2) Use javascript function to load XML file (that stored those data). 3) It produces invalid characters in XML file. STEP 1 : Sample of the code in PhP - Loading MySQL DB to store data onto XML file $file= fopen("MapDeals2.xml", "w"); $_xml ="\n"; $_xml .="\n"; while($row1_ThisWeek = mysql_fetch_array($result1_ThisWeek)) { $rRName = $row1_ThisWeek['Retailer_Name']; $rRAddress = $row1_ThisWeek['Retailer_Address1']; $rRAddressPostCode = $row1_ThisWeek['Retailer_AddressPostCode1']; } $_xml .= "<DEAL>\n"; $_xml .= "<DealDescription>" . $d_Description . "</DealDescription>\n"; $_xml .= "<DealURL>" . $d_URL . "</DealURL>\n"; $_xml .= "<DealRName>" . $rRName . "</DealRName>\n"; $_xml .= "<DealRAddress>" . $rRAddress . "</DealRAddress>\n"; $_xml .= "<DealRPostCode>" . $rRAddressPostCode . "</DealRPostCode>\n"; $_xml .= "</DEAL>\n"; } } $_xml .="\n"; fwrite($file, $_xml); fclose($file); STEP 2 : Sample of the code in Javscript - Loading XML file xhttp.open("GET","Test2.xml", false); xhttp.send(""); xmlDoc=xhttp.responseXML; var x=xmlDoc.getElementsByTagName("Employee"); parser = new DOMParser(); xmlDoc = parser.parseFromString("MapDeals2.xml", "text/xml"); for (i=0;i"; . . . } Is there a solution for the above? Looking forward to hear from you soon. Cheers

    Read the article

  • ob_start() -> ob_flush() doesn't work

    - by MB34
    I am using ob_start()/ob_flush() to, hopefully, give me some progress during a long import operation. Here is a simple outline of what I'm doing: <?php ob_start (); echo "Connecting to download Inventory file.<br>"; $conn = ftp_connect($ftp_site) or die("Could not connect"); echo "Logging into site download Inventory file.<br>"; ftp_login($conn,$ftp_username,$ftp_password) or die("Bad login credentials for ". $ftp_site); echo "Changing directory on download Inventory file.<br>"; ftp_chdir($conn,"INV") or die("could not change directory to INV"); // connection, local, remote, type, resume $localname = "INV"."_".date("m")."_".date('d').".csv"; echo "Downloading Inventory file to:".$localname."<br>"; ob_flush(); flush(); sleep(5); if (ftp_get($conn,$localname,"INV.csv",FTP_ASCII)) { echo "New Inventory File Downloaded<br>"; $datapath = $localname; ftp_close($conn); } else { ftp_close($conn); die("There was a problem downloading the Inventory file."); } ob_flush(); flush(); sleep(5); $csvfile = fopen($datapath, "r"); // open csv file $x = 1; // skip the header line $line = fgetcsv($csvfile); $y = (feof($csvfile) ? 2 : 5); while ((!$debug) ? (!feof($csvfile)) : $x <= $y) { $x++; $line = fgetcsv($csvfile); // do a lot of import stuff here with $line ob_flush(); flush(); sleep(1); } fclose($csvfile); // important: close the file ob_end_clean(); However, nothing is being output to the screen at all. I know the data file is getting downloaded because I watch the directory where it is being placed. I also know that the import is happening, meaning that it is in the while loop, because I can monitor the DB and records are being inserted. Any ideas as to why I am not getting output to the screen?

    Read the article

  • php web services not getting data from iphone application

    - by user317192
    Hi, I am connecting with a php web service from my iphone application, I am doing a simple thing i.e. 1. Getting user inputs for: username password in a text field from the iphone form and sending the same to the PHP Post request web service. At the web service end I receive nothing other than blank fields that are inserted into the MySQL Database....... The code for sample web service is: ***********SAMPLE CODE FOR WEB SERVICES***** mysql_select_db("eventsfast",$con); $username = $_REQUEST['username']; $password = $_REQUEST['password']; echo $username; echo $password; $data = $_REQUEST; $fp = fopen("log.txt", "w"); fwrite($fp, $data['username']); fwrite($fp, $data['password']); $sql="INSERT INTO users(username,password) VALUES('{$username}','{$password}')"; if(!mysql_query($sql,$con)) { die('Error:'.mysql_error()); } echo json_encode("1 record added to users table"); mysql_close($con); echo "test"; ? ***************PHP******** ****** **************IPHONE EVENT CODE******* import "postdatawithphpViewController.h" @implementation postdatawithphpViewController @synthesize userName,password; -(IBAction) postdataid) sender { NSLog(userName.text); NSLog(password.text); NSString * dataTOB=[userName.text stringByAppendingString:password.text]; NSLog(dataTOB); NSData * postData=[dataTOB dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; NSLog(postLength); NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:8888/write.php"]]; [request setURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSURLResponse *response; NSError *error; [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if(error==nil) NSLog(@"Error is nil"); else NSLog(@"Error is not nil"); NSLog(@"success!"); } Please help.............

    Read the article

  • Looping class, for template engine kind of thing

    - by tarnfeld
    Hey, I am updating my class Nesty so it's infinite but I'm having a little trouble.... Here is the class: <?php Class Nesty { // Class Variables private $text; private $data = array(); private $loops = 0; private $maxLoops = 0; public function __construct($text,$data = array(),$maxLoops = 5) { // Set the class vars $this->text = $text; $this->data = $data; $this->maxLoops = $maxLoops; } // Loop funtion private function loopThrough($data) { if( ($this->loops +1) > $this->maxLoops ) { die("ERROR: Too many loops!"); } else { $keys = array_keys($data); for($x = 0; $x < count($keys); $x++) { if(is_array($data[$keys[$x]])) { $this->loopThrough($data[$keys[$x]]); } else { return $data[$keys[$x]]; } } } } // Templater method public function template() { echo $this->loopThrough($this->data); } } ?> Here is the code you would use to create an instance of the class: <?php // The nested array $data = array( "person" => array( "name" => "Tom Arnfeld", "age" => 15 ), "product" => array ( "name" => "Cakes", "price" => array ( "single" => 59, "double" => 99 ) ), "other" => "string" ); // Retreive the template text $file = "TestData.tpl"; $fp = fopen($file,"r"); $text = fread($fp,filesize($file)); // Create the Nesty object require_once('Nesty.php'); $nesty = new Nesty($text,$data); // Save the newly templated text to a variable $message $message = $nesty->template(); // Print out $message on the page echo("<pre>".$message."</pre>"); ?> Any ideas?

    Read the article

  • [C] Programming problem: Storing values of an array in one variable

    - by OldMacDonald
    Hello, I am trying to use md5 code to calculate checksums of file. Now the given function prints out the (previously calculated) checksum on screen, but I want to store it in a variable, to be able to compare it later on. I guess the main problem is that I want to store the content of an array in one variable. How can I manage that? Probably this is a very stupid question, but maybe somone can help. Below is the function to print out the value. I want to modify it to store the result in one variable. static void MDPrint (mdContext) MD5_CTX *mdContext; { int i; for (i = 0; i < 16; i++) { printf ("%02x", mdContext->digest[i]); } // end of for } // end of function For reasons of completeness the used struct: /* typedef a 32 bit type */ typedef unsigned long int UINT4; /* Data structure for MD5 (Message Digest) computation */ typedef struct { UINT4 i[2]; /* number of _bits_ handled mod 2^64 */ UINT4 buf[4]; /* scratch buffer */ unsigned char in[64]; /* input buffer */ unsigned char digest[16]; /* actual digest after MD5Final call */ } MD5_CTX; and the used function to calculate the checksum: static int MDFile (filename) char *filename; { FILE *inFile = fopen (filename, "rb"); MD5_CTX mdContext; int bytes; unsigned char data[1024]; if (inFile == NULL) { printf ("%s can't be opened.\n", filename); return -1; } // end of if MD5Init (&mdContext); while ((bytes = fread (data, 1, 1024, inFile)) != 0) MD5Update (&mdContext, data, bytes); MD5Final (&mdContext); MDPrint (&mdContext); printf (" %s\n", filename); fclose (inFile); return 0; }

    Read the article

  • Telephone Directory

    - by Mizukage of Meron 5
    I need your help. We are ask to make a telephone directory program that asks your name, address, and telephone number. If the name you entered already exists, it will display that it already exists. This is what i have so far... #include<stdio.h> #include<conio.h> struct file { char name[25],address[25]; double telno; }; char tempname[25],tempadd[25]; double tempnum; int x; int choice; FILE *fp; main() { struct file rec; clrscr(); fp=fopen("TelDir.txt","a+"); while(!feof(fp)) { fscanf(fp,"%s %s %.0lf,&tempname,&tempadd,&tempnum); printf("\n%s\t\t%s\t\t\t%.0lf",tempname,tempadd,tempnum); printf("\nEnter Name: "); gets(rec.name); if(strcmp(rec.name,tempname)==1) { printf("\n\nALREADY EXIST!"); printf("\n%s\t\t%s\t\t\t%.0lf",tempname,tempadd,tempnum); getch(); } else { printf("Enter Address: "); scanf("%s",&rec.address); printf("Enter your Telephone No.: "); scanf("%lf",&rec.telno); printf("%s\t\t%s\t\t%\t\t0lf",rec.name,rec.address,rec.telno); fprintf(fp,"%s %s %.0lf\n",rec.name,rec.address,rec.telno); } } fclose(fp); getch(); } But this thing doesn't work. I don't know where the error is. Can someone help me on this? I would really appreciate if you could help me somehow.

    Read the article

  • SFTP not supported error with PHP & cURL

    - by Bad Programmer
    I followed the advice from this Stack Overflow question thread, but I keep hitting a snag. I am receiving the following error message: Unsupported protocol: sftp Here is my code: $ch = curl_init(); if(!$ch) { $error = curl_error($ch); die("cURL session could not be initiated. ERROR: $error.""); } $fp = fopen($docname, 'r'); if(!$fp) { $error = curl_error($ch); die("$docname could not be read."); } curl_setopt($ch, CURLOPT_URL, "sftp://$user_name:$user_pass@$server:22/$docname"); curl_setopt($ch, CURLOPT_UPLOAD, 1); curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_SFTP); curl_setopt($ch, CURLOPT_INFILE, $fp); curl_setopt($ch, CURLOPT_INFILESIZE, filesize($docname)); //this is where I get the failure $exec = curl_exec ($ch); if(!$exec) { $error = curl_error($ch); die("File $docname could not be uploaded. ERROR: $error."); } curl_close ($ch); I used the curl_version() function to see my curl information, and found that sftp doesn't seem to be in the array of supported protocols: [version_number] => 462597 [age] => 2 [features] => 1597 [ssl_version_number] => 0 [version] => 7.15.5 [host] => x86_64-redhat-linux-gnu [ssl_version] => OpenSSL/0.9.8b [libz_version] => 1.2.3 [protocols] => Array ( [0] => tftp [1] => ftp [2] => telnet [3] => dict [4] => ldap [5] => http [6] => file [7] => https [8] => ftps ) Is this a matter of my version of cURL being outdated, or is the SFTP protocol simply not supported at all? Any advice is greatly appreciated.

    Read the article

  • Optimal template for change content via XMLHTTPRequest with JQuery,PHP,SQL [closed]

    - by B.F.
    This is my method to handle XMLHTTPRequests. Avoids mysql request, foreign access, nerves user, double requests. jquery var allow=true; var is_loaded=""; $(document).ready(function(){ .... $(".xx").on("click",functio(){ if(allow){ allow=false; if(is_loaded!="that"){ $.post("job.php", {job:"that",word:"aaa",number:"123"},function(data){ $(".aaa").html(data); is_loaded="that"; }); } setTimeout(function(){allow=true},500); } .... }); job.php <?PHP ob_start('ob_gzhandler'); if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) or strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')exit("bad boy!"); if($_POST['job']=="that"){ include "includes/that.inc; } elseif($_POST['job']== .... ob_end_flush(); ?> that.inc if(!preg_match("/\w/",$_POST['word'])exit("bad boy!"); if(!is_numeric($_POST['number'])exit("bad boy!"); //exclude more. $path="temp/that_".$row['word']."txt"; if(file_exists($path) and filemtime("includes/that.inc")<$filemtime($path)){ readfile($path); } else{ include "includes/openSql.inc"; $call=sql_query("SELECT * FROM that WHERE name='".mysql_real_escape_string($_POST['word'])."'"); if(!$call)exit("ups"); $out=""; while($row=mysql_fetch_assoc($call)){ $out.=$_POST['word']." loves the color ".$row['color'].".<br/>"; } echo $out; $fn=fopen($path,"wb"); fputs($fn,$out); fclose($fn); } if something change at the database, you just have to delete involved files. Hope it was English.

    Read the article

  • Logging in to a website cURL!

    - by uknowho_freeman
    I am using cURL for the first time. I need to login to a site. I have problem with setting cookie file and to retrive, so that i can acces that page not just one time, but several times. I found the code on the web, for logging in to a site and Scrap a page for some detailed info, cause to get that page it takes to much time. so i just want to know if it is OK! the code belove(it is just for login in the code for Scraping its not ready) <?php curl_login('http://mywantedsite.com/login.php','user=******&pass=******','','off'); echo curl_grab_page('http://mywantedsite.com/somepage.php','','off'); function curl_login($url,$data,$proxy,$proxystatus){ $fp = fopen("cookie.txt", "w"); fclose($fp); $login = curl_init(); curl_setopt($login, CURLOPT_COOKIEJAR, "cookie.txt"); curl_setopt($login, CURLOPT_COOKIEFILE, "cookie.txt"); curl_setopt($login, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"); curl_setopt($login, CURLOPT_TIMEOUT, 40); curl_setopt($login, CURLOPT_RETURNTRANSFER, TRUE); if ($proxystatus == 'on') { curl_setopt($login, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($login, CURLOPT_HTTPPROXYTUNNEL, TRUE); curl_setopt($login, CURLOPT_PROXY, $proxy); } curl_setopt($login, CURLOPT_URL, $url); curl_setopt($login, CURLOPT_HEADER, TRUE); curl_setopt($login, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($login, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($login, CURLOPT_POST, TRUE); curl_setopt($login, CURLOPT_POSTFIELDS, $data); ob_start(); // prevent any output return curl_exec ($login); // execute the curl command ob_end_clean(); // stop preventing output curl_close ($login); unset($login); } function curl_grab_page($site,$proxy,$proxystatus){ $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); if ($proxystatus == 'on') { curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE); curl_setopt($ch, CURLOPT_PROXY, $proxy); } curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt"); curl_setopt($ch, CURLOPT_URL, $site); ob_start(); // prevent any output return curl_exec ($ch); // execute the curl command ob_end_clean(); // stop preventing output curl_close ($ch); }

    Read the article

  • How to avoid my script to freeze

    - by jemz
    I have socket server script that continuously running listening for the GPS device that runs in PHP CLI,my problem is that my socket will freeze if it executes long time,how do I prevent this so that my script will not freeze.I have no idea on this socket.this is the first time that I use socket connection. I appreciate someone can help my problem. <?php error_reporting(-1); ini_set('display_errors', 1); set_time_limit (0); $address_server = 'xxx.xxx.xx.xx'; $port_server = xxxx; $isTrue = true; socketfunction($address_server,$port_server,$isTrue); function socketfunction($address,$port,$done){ $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1); socket_bind($sock, $address, $port); socket_listen($sock); $clients = array($sock); while ($done ) { $file = fopen('txt.log','a'); $read = $clients; $write = NULL; $except = NULL; $tv_sec = 0; if (socket_select($read, $write , $except, $tv_sec) < 1){ continue; } // checking client if (in_array($sock, $read)) { $clients[] = $newsock = socket_accept($sock); $key = array_search($sock, $read); unset($read[$key]); } //handle client for reading foreach ($read as $read_sock) { $data = @socket_read($read_sock, 1024, PHP_NORMAL_READ); if ($data === false) { $key = array_search($read_sock, $clients); unset($clients[$key]); echo "client disconnected.\n"; echo "Remaining ".(count($clients) - 1)."client(s) connected\r\n"; continue; } $data = trim($data); if (!empty($data)) { echo("Returning stripped input\n"); fwrite($file,$data."\n"); } } // end of reading foreach fclose($file); }//end while socket_close($sock); } ?> Thank you in advance.

    Read the article

< Previous Page | 18 19 20 21 22 23 24 25  | Next Page >